Completed
Branch BUG-10851-events-shortcode (6a6497)
by
unknown
44:06 queued 32:50
created
caffeinated/brewing_regular.php 1 patch
Indentation   +269 added lines, -269 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\services\database\TableAnalysis;
5 5
 
6 6
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 /**
10 10
  * the purpose of this file is to simply contain any action/filter hook callbacks etc for specific aspects of EE
@@ -29,277 +29,277 @@  discard block
 block discarded – undo
29 29
 class EE_Brewing_Regular extends EE_BASE implements InterminableInterface
30 30
 {
31 31
 
32
-    /**
33
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
34
-     */
35
-    protected $_table_analysis;
36
-
37
-
38
-
39
-    /**
40
-     * EE_Brewing_Regular constructor.
41
-     */
42
-    public function __construct(TableAnalysis $table_analysis)
43
-    {
44
-        $this->_table_analysis = $table_analysis;
45
-        if (defined('EE_CAFF_PATH')) {
46
-            // activation
47
-            add_action('AHEE__EEH_Activation__initialize_db_content', array($this, 'initialize_caf_db_content'));
48
-            // load caff init
49
-            add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'caffeinated_init'));
50
-            // remove the "powered by" credit link from receipts and invoices
51
-            add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
52
-            // add caffeinated modules
53
-            add_filter(
54
-                'FHEE__EE_Config__register_modules__modules_to_register',
55
-                array($this, 'caffeinated_modules_to_register')
56
-            );
57
-            // load caff scripts
58
-            add_action('wp_enqueue_scripts', array($this, 'enqueue_caffeinated_scripts'), 10);
59
-            add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
60
-            add_filter(
61
-                'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
62
-                array($this, 'caf_payment_methods')
63
-            );
64
-            // caffeinated constructed
65
-            do_action('AHEE__EE_Brewing_Regular__construct__complete');
66
-            //seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
67
-            add_filter('FHEE__ee_show_affiliate_links', '__return_false');
68
-        }
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
75
-     *
76
-     * @param array $paths original helper paths array
77
-     * @return array             new array of paths
78
-     */
79
-    public function caf_helper_paths($paths)
80
-    {
81
-        $paths[] = EE_CAF_CORE . 'helpers' . DS;
82
-        return $paths;
83
-    }
84
-
85
-
86
-
87
-    /**
88
-     * Upon brand-new activation, if this is a new activation of CAF, we want to add
89
-     * some global prices that will show off EE4's capabilities. However, if they're upgrading
90
-     * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
91
-     * This action should only be called when EE 4.x.0.P is initially activated.
92
-     * Right now the only CAF content are these global prices. If there's more in the future, then
93
-     * we should probably create a caf file to contain it all instead just a function like this.
94
-     * Right now, we ASSUME the only price types in the system are default ones
95
-     *
96
-     * @global wpdb $wpdb
97
-     */
98
-    public function initialize_caf_db_content()
99
-    {
100
-        global $wpdb;
101
-        //use same method of getting creator id as the version introducing the change
102
-        $default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
103
-        $price_type_table = $wpdb->prefix . "esp_price_type";
104
-        $price_table = $wpdb->prefix . "esp_price";
105
-        if ($this->_get_table_analysis()->tableExists($price_type_table)) {
106
-            $SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
107
-            $tax_price_type_count = $wpdb->get_var($SQL);
108
-            if ($tax_price_type_count <= 1) {
109
-                $wpdb->insert(
110
-                    $price_type_table,
111
-                    array(
112
-                        'PRT_name'       => __("Regional Tax", "event_espresso"),
113
-                        'PBT_ID'         => 4,
114
-                        'PRT_is_percent' => true,
115
-                        'PRT_order'      => 60,
116
-                        'PRT_deleted'    => false,
117
-                        'PRT_wp_user'    => $default_creator_id,
118
-                    ),
119
-                    array(
120
-                        '%s',//PRT_name
121
-                        '%d',//PBT_id
122
-                        '%d',//PRT_is_percent
123
-                        '%d',//PRT_order
124
-                        '%d',//PRT_deleted
125
-                        '%d', //PRT_wp_user
126
-                    )
127
-                );
128
-                //federal tax
129
-                $result = $wpdb->insert(
130
-                    $price_type_table,
131
-                    array(
132
-                        'PRT_name'       => __("Federal Tax", "event_espresso"),
133
-                        'PBT_ID'         => 4,
134
-                        'PRT_is_percent' => true,
135
-                        'PRT_order'      => 70,
136
-                        'PRT_deleted'    => false,
137
-                        'PRT_wp_user'    => $default_creator_id,
138
-                    ),
139
-                    array(
140
-                        '%s',//PRT_name
141
-                        '%d',//PBT_id
142
-                        '%d',//PRT_is_percent
143
-                        '%d',//PRT_order
144
-                        '%d',//PRT_deleted
145
-                        '%d' //PRT_wp_user
146
-                    )
147
-                );
148
-                if ($result) {
149
-                    $wpdb->insert(
150
-                        $price_table,
151
-                        array(
152
-                            'PRT_ID'         => $wpdb->insert_id,
153
-                            'PRC_amount'     => 15.00,
154
-                            'PRC_name'       => __("Sales Tax", "event_espresso"),
155
-                            'PRC_desc'       => '',
156
-                            'PRC_is_default' => true,
157
-                            'PRC_overrides'  => null,
158
-                            'PRC_deleted'    => false,
159
-                            'PRC_order'      => 50,
160
-                            'PRC_parent'     => null,
161
-                            'PRC_wp_user'    => $default_creator_id,
162
-                        ),
163
-                        array(
164
-                            '%d',//PRT_id
165
-                            '%f',//PRC_amount
166
-                            '%s',//PRC_name
167
-                            '%s',//PRC_desc
168
-                            '%d',//PRC_is_default
169
-                            '%d',//PRC_overrides
170
-                            '%d',//PRC_deleted
171
-                            '%d',//PRC_order
172
-                            '%d',//PRC_parent
173
-                            '%d' //PRC_wp_user
174
-                        )
175
-                    );
176
-                }
177
-            }
178
-        }
179
-    }
180
-
181
-
182
-
183
-    /**
184
-     *    caffeinated_modules_to_register
185
-     *
186
-     * @access public
187
-     * @param array $modules_to_register
188
-     * @return array
189
-     */
190
-    public function caffeinated_modules_to_register($modules_to_register = array())
191
-    {
192
-        if (is_readable(EE_CAFF_PATH . 'modules')) {
193
-            $caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
194
-            if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
195
-                $modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
196
-            }
197
-        }
198
-        return $modules_to_register;
199
-    }
200
-
201
-
202
-
203
-    public function caffeinated_init()
204
-    {
205
-        // EE_Register_CPTs hooks
206
-        add_filter('FHEE__EE_Register_CPTs__get_taxonomies__taxonomies', array($this, 'filter_taxonomies'), 10);
207
-        add_filter('FHEE__EE_Register_CPTs__get_CPTs__cpts', array($this, 'filter_cpts'), 10);
208
-        add_filter('FHEE__EE_Admin__get_extra_nav_menu_pages_items', array($this, 'nav_metabox_items'), 10);
209
-        EE_Registry::instance()->load_file(EE_CAFF_PATH, 'EE_Caf_Messages', 'class', array(), false);
210
-        // caffeinated_init__complete hook
211
-        do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
212
-    }
213
-
214
-
215
-
216
-    public function enqueue_caffeinated_scripts()
217
-    {
218
-        // sound of crickets...
219
-    }
220
-
221
-
222
-
223
-    /**
224
-     * callbacks below here
225
-     *
226
-     * @param array $taxonomy_array
227
-     * @return array
228
-     */
229
-    public function filter_taxonomies(array $taxonomy_array)
230
-    {
231
-        $taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
232
-        return $taxonomy_array;
233
-    }
234
-
235
-
236
-
237
-    /**
238
-     * @param array $cpt_array
239
-     * @return mixed
240
-     */
241
-    public function filter_cpts(array $cpt_array)
242
-    {
243
-        $cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
244
-        return $cpt_array;
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * @param array $menuitems
251
-     * @return array
252
-     */
253
-    public function nav_metabox_items(array $menuitems)
254
-    {
255
-        $menuitems[] = array(
256
-            'title'       => __('Venue List', 'event_espresso'),
257
-            'url'         => get_post_type_archive_link('espresso_venues'),
258
-            'description' => __('Archive page for all venues.', 'event_espresso'),
259
-        );
260
-        return $menuitems;
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     * Adds the payment methods in {event-espresso-core}/caffeinated/payment_methods
267
-     *
268
-     * @param array $payment_method_paths
269
-     * @return array values are folder paths to payment method folders
270
-     */
271
-    public function caf_payment_methods($payment_method_paths)
272
-    {
273
-        $caf_payment_methods_paths = glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
274
-        $payment_method_paths = array_merge($payment_method_paths, $caf_payment_methods_paths);
275
-        return $payment_method_paths;
276
-    }
277
-
278
-
279
-
280
-    /**
281
-     * Gets the injected table analyzer, or throws an exception
282
-     *
283
-     * @return TableAnalysis
284
-     * @throws \EE_Error
285
-     */
286
-    protected function _get_table_analysis()
287
-    {
288
-        if ($this->_table_analysis instanceof TableAnalysis) {
289
-            return $this->_table_analysis;
290
-        } else {
291
-            throw new \EE_Error(
292
-                sprintf(
293
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
294
-                    get_class($this)
295
-                )
296
-            );
297
-        }
298
-    }
32
+	/**
33
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
34
+	 */
35
+	protected $_table_analysis;
36
+
37
+
38
+
39
+	/**
40
+	 * EE_Brewing_Regular constructor.
41
+	 */
42
+	public function __construct(TableAnalysis $table_analysis)
43
+	{
44
+		$this->_table_analysis = $table_analysis;
45
+		if (defined('EE_CAFF_PATH')) {
46
+			// activation
47
+			add_action('AHEE__EEH_Activation__initialize_db_content', array($this, 'initialize_caf_db_content'));
48
+			// load caff init
49
+			add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'caffeinated_init'));
50
+			// remove the "powered by" credit link from receipts and invoices
51
+			add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
52
+			// add caffeinated modules
53
+			add_filter(
54
+				'FHEE__EE_Config__register_modules__modules_to_register',
55
+				array($this, 'caffeinated_modules_to_register')
56
+			);
57
+			// load caff scripts
58
+			add_action('wp_enqueue_scripts', array($this, 'enqueue_caffeinated_scripts'), 10);
59
+			add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
60
+			add_filter(
61
+				'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
62
+				array($this, 'caf_payment_methods')
63
+			);
64
+			// caffeinated constructed
65
+			do_action('AHEE__EE_Brewing_Regular__construct__complete');
66
+			//seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
67
+			add_filter('FHEE__ee_show_affiliate_links', '__return_false');
68
+		}
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
75
+	 *
76
+	 * @param array $paths original helper paths array
77
+	 * @return array             new array of paths
78
+	 */
79
+	public function caf_helper_paths($paths)
80
+	{
81
+		$paths[] = EE_CAF_CORE . 'helpers' . DS;
82
+		return $paths;
83
+	}
84
+
85
+
86
+
87
+	/**
88
+	 * Upon brand-new activation, if this is a new activation of CAF, we want to add
89
+	 * some global prices that will show off EE4's capabilities. However, if they're upgrading
90
+	 * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
91
+	 * This action should only be called when EE 4.x.0.P is initially activated.
92
+	 * Right now the only CAF content are these global prices. If there's more in the future, then
93
+	 * we should probably create a caf file to contain it all instead just a function like this.
94
+	 * Right now, we ASSUME the only price types in the system are default ones
95
+	 *
96
+	 * @global wpdb $wpdb
97
+	 */
98
+	public function initialize_caf_db_content()
99
+	{
100
+		global $wpdb;
101
+		//use same method of getting creator id as the version introducing the change
102
+		$default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
103
+		$price_type_table = $wpdb->prefix . "esp_price_type";
104
+		$price_table = $wpdb->prefix . "esp_price";
105
+		if ($this->_get_table_analysis()->tableExists($price_type_table)) {
106
+			$SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
107
+			$tax_price_type_count = $wpdb->get_var($SQL);
108
+			if ($tax_price_type_count <= 1) {
109
+				$wpdb->insert(
110
+					$price_type_table,
111
+					array(
112
+						'PRT_name'       => __("Regional Tax", "event_espresso"),
113
+						'PBT_ID'         => 4,
114
+						'PRT_is_percent' => true,
115
+						'PRT_order'      => 60,
116
+						'PRT_deleted'    => false,
117
+						'PRT_wp_user'    => $default_creator_id,
118
+					),
119
+					array(
120
+						'%s',//PRT_name
121
+						'%d',//PBT_id
122
+						'%d',//PRT_is_percent
123
+						'%d',//PRT_order
124
+						'%d',//PRT_deleted
125
+						'%d', //PRT_wp_user
126
+					)
127
+				);
128
+				//federal tax
129
+				$result = $wpdb->insert(
130
+					$price_type_table,
131
+					array(
132
+						'PRT_name'       => __("Federal Tax", "event_espresso"),
133
+						'PBT_ID'         => 4,
134
+						'PRT_is_percent' => true,
135
+						'PRT_order'      => 70,
136
+						'PRT_deleted'    => false,
137
+						'PRT_wp_user'    => $default_creator_id,
138
+					),
139
+					array(
140
+						'%s',//PRT_name
141
+						'%d',//PBT_id
142
+						'%d',//PRT_is_percent
143
+						'%d',//PRT_order
144
+						'%d',//PRT_deleted
145
+						'%d' //PRT_wp_user
146
+					)
147
+				);
148
+				if ($result) {
149
+					$wpdb->insert(
150
+						$price_table,
151
+						array(
152
+							'PRT_ID'         => $wpdb->insert_id,
153
+							'PRC_amount'     => 15.00,
154
+							'PRC_name'       => __("Sales Tax", "event_espresso"),
155
+							'PRC_desc'       => '',
156
+							'PRC_is_default' => true,
157
+							'PRC_overrides'  => null,
158
+							'PRC_deleted'    => false,
159
+							'PRC_order'      => 50,
160
+							'PRC_parent'     => null,
161
+							'PRC_wp_user'    => $default_creator_id,
162
+						),
163
+						array(
164
+							'%d',//PRT_id
165
+							'%f',//PRC_amount
166
+							'%s',//PRC_name
167
+							'%s',//PRC_desc
168
+							'%d',//PRC_is_default
169
+							'%d',//PRC_overrides
170
+							'%d',//PRC_deleted
171
+							'%d',//PRC_order
172
+							'%d',//PRC_parent
173
+							'%d' //PRC_wp_user
174
+						)
175
+					);
176
+				}
177
+			}
178
+		}
179
+	}
180
+
181
+
182
+
183
+	/**
184
+	 *    caffeinated_modules_to_register
185
+	 *
186
+	 * @access public
187
+	 * @param array $modules_to_register
188
+	 * @return array
189
+	 */
190
+	public function caffeinated_modules_to_register($modules_to_register = array())
191
+	{
192
+		if (is_readable(EE_CAFF_PATH . 'modules')) {
193
+			$caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
194
+			if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
195
+				$modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
196
+			}
197
+		}
198
+		return $modules_to_register;
199
+	}
200
+
201
+
202
+
203
+	public function caffeinated_init()
204
+	{
205
+		// EE_Register_CPTs hooks
206
+		add_filter('FHEE__EE_Register_CPTs__get_taxonomies__taxonomies', array($this, 'filter_taxonomies'), 10);
207
+		add_filter('FHEE__EE_Register_CPTs__get_CPTs__cpts', array($this, 'filter_cpts'), 10);
208
+		add_filter('FHEE__EE_Admin__get_extra_nav_menu_pages_items', array($this, 'nav_metabox_items'), 10);
209
+		EE_Registry::instance()->load_file(EE_CAFF_PATH, 'EE_Caf_Messages', 'class', array(), false);
210
+		// caffeinated_init__complete hook
211
+		do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
212
+	}
213
+
214
+
215
+
216
+	public function enqueue_caffeinated_scripts()
217
+	{
218
+		// sound of crickets...
219
+	}
220
+
221
+
222
+
223
+	/**
224
+	 * callbacks below here
225
+	 *
226
+	 * @param array $taxonomy_array
227
+	 * @return array
228
+	 */
229
+	public function filter_taxonomies(array $taxonomy_array)
230
+	{
231
+		$taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
232
+		return $taxonomy_array;
233
+	}
234
+
235
+
236
+
237
+	/**
238
+	 * @param array $cpt_array
239
+	 * @return mixed
240
+	 */
241
+	public function filter_cpts(array $cpt_array)
242
+	{
243
+		$cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
244
+		return $cpt_array;
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * @param array $menuitems
251
+	 * @return array
252
+	 */
253
+	public function nav_metabox_items(array $menuitems)
254
+	{
255
+		$menuitems[] = array(
256
+			'title'       => __('Venue List', 'event_espresso'),
257
+			'url'         => get_post_type_archive_link('espresso_venues'),
258
+			'description' => __('Archive page for all venues.', 'event_espresso'),
259
+		);
260
+		return $menuitems;
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 * Adds the payment methods in {event-espresso-core}/caffeinated/payment_methods
267
+	 *
268
+	 * @param array $payment_method_paths
269
+	 * @return array values are folder paths to payment method folders
270
+	 */
271
+	public function caf_payment_methods($payment_method_paths)
272
+	{
273
+		$caf_payment_methods_paths = glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
274
+		$payment_method_paths = array_merge($payment_method_paths, $caf_payment_methods_paths);
275
+		return $payment_method_paths;
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * Gets the injected table analyzer, or throws an exception
282
+	 *
283
+	 * @return TableAnalysis
284
+	 * @throws \EE_Error
285
+	 */
286
+	protected function _get_table_analysis()
287
+	{
288
+		if ($this->_table_analysis instanceof TableAnalysis) {
289
+			return $this->_table_analysis;
290
+		} else {
291
+			throw new \EE_Error(
292
+				sprintf(
293
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
294
+					get_class($this)
295
+				)
296
+			);
297
+		}
298
+	}
299 299
 }
300 300
 
301 301
 
302 302
 
303 303
 $brewing = new EE_Brewing_Regular(
304
-    EE_Registry::instance()->create('TableAnalysis', array(), true)
304
+	EE_Registry::instance()->create('TableAnalysis', array(), true)
305 305
 );
306 306
\ No newline at end of file
Please login to merge, or discard this patch.
core/EE_Request_Handler.core.php 1 patch
Spacing   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\interfaces\InterminableInterface;
2 2
 
3
-if ( ! defined( 'EVENT_ESPRESSO_VERSION')) {exit('No direct script access allowed');}
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {exit('No direct script access allowed'); }
4 4
 /**
5 5
  * class EE_Request_Handler
6 6
  *
@@ -51,13 +51,13 @@  discard block
 block discarded – undo
51 51
 	 * @access public
52 52
 	 * @param  EE_Request $request
53 53
 	 */
54
-	public function __construct( EE_Request $request ) {
54
+	public function __construct(EE_Request $request) {
55 55
 		// grab request vars
56 56
 		$this->_params = $request->params();
57 57
 		// AJAX ???
58
-		$this->ajax = defined( 'DOING_AJAX' ) && DOING_AJAX ? true : false;
59
-		$this->front_ajax = defined( 'EE_FRONT_AJAX' ) && EE_FRONT_AJAX ? true : false;
60
-		do_action( 'AHEE__EE_Request_Handler__construct__complete' );
58
+		$this->ajax = defined('DOING_AJAX') && DOING_AJAX ? true : false;
59
+		$this->front_ajax = defined('EE_FRONT_AJAX') && EE_FRONT_AJAX ? true : false;
60
+		do_action('AHEE__EE_Request_Handler__construct__complete');
61 61
 	}
62 62
 
63 63
 
@@ -69,12 +69,12 @@  discard block
 block discarded – undo
69 69
 	 * @param WP $wp
70 70
 	 * @return void
71 71
 	 */
72
-	public function parse_request( $wp = null ) {
72
+	public function parse_request($wp = null) {
73 73
 		//if somebody forgot to provide us with WP, that's ok because its global
74
-		if ( ! $wp instanceof WP ) {
74
+		if ( ! $wp instanceof WP) {
75 75
 			global $wp;
76 76
 		}
77
-		$this->set_request_vars( $wp );
77
+		$this->set_request_vars($wp);
78 78
 	}
79 79
 
80 80
 
@@ -86,14 +86,14 @@  discard block
 block discarded – undo
86 86
 	 * @param WP $wp
87 87
 	 * @return void
88 88
 	 */
89
-	public function set_request_vars( $wp = null ) {
90
-		if ( ! is_admin() ) {
89
+	public function set_request_vars($wp = null) {
90
+		if ( ! is_admin()) {
91 91
 			// set request post_id
92
-			$this->set( 'post_id', $this->get_post_id_from_request( $wp ));
92
+			$this->set('post_id', $this->get_post_id_from_request($wp));
93 93
 			// set request post name
94
-			$this->set( 'post_name', $this->get_post_name_from_request( $wp ));
94
+			$this->set('post_name', $this->get_post_name_from_request($wp));
95 95
 			// set request post_type
96
-			$this->set( 'post_type', $this->get_post_type_from_request( $wp ));
96
+			$this->set('post_type', $this->get_post_type_from_request($wp));
97 97
 			// true or false ? is this page being used by EE ?
98 98
 			$this->set_espresso_page();
99 99
 		}
@@ -108,19 +108,19 @@  discard block
 block discarded – undo
108 108
 	 * @param WP $wp
109 109
 	 * @return int
110 110
 	 */
111
-	public function get_post_id_from_request( $wp = null ) {
112
-		if ( ! $wp instanceof WP ){
111
+	public function get_post_id_from_request($wp = null) {
112
+		if ( ! $wp instanceof WP) {
113 113
 			global $wp;
114 114
 		}
115 115
 		$post_id = null;
116
-		if ( isset( $wp->query_vars['p'] )) {
116
+		if (isset($wp->query_vars['p'])) {
117 117
 			$post_id = $wp->query_vars['p'];
118 118
 		}
119
-		if ( ! $post_id && isset( $wp->query_vars['page_id'] )) {
119
+		if ( ! $post_id && isset($wp->query_vars['page_id'])) {
120 120
 			$post_id = $wp->query_vars['page_id'];
121 121
 		}
122
-		if ( ! $post_id && isset( $wp->request ) && is_numeric( basename( $wp->request ))) {
123
-			$post_id = basename( $wp->request );
122
+		if ( ! $post_id && isset($wp->request) && is_numeric(basename($wp->request))) {
123
+			$post_id = basename($wp->request);
124 124
 		}
125 125
 		return $post_id;
126 126
 	}
@@ -134,35 +134,35 @@  discard block
 block discarded – undo
134 134
 	 * @param WP $wp
135 135
 	 * @return string
136 136
 	 */
137
-	public function get_post_name_from_request( $wp = null ) {
138
-		if ( ! $wp instanceof WP ){
137
+	public function get_post_name_from_request($wp = null) {
138
+		if ( ! $wp instanceof WP) {
139 139
 			global $wp;
140 140
 		}
141 141
 		$post_name = null;
142
-		if ( isset( $wp->query_vars['name'] ) && ! empty( $wp->query_vars['name'] )) {
142
+		if (isset($wp->query_vars['name']) && ! empty($wp->query_vars['name'])) {
143 143
 			$post_name = $wp->query_vars['name'];
144 144
 		}
145
-		if ( ! $post_name && isset( $wp->query_vars['pagename'] ) && ! empty( $wp->query_vars['pagename'] )) {
145
+		if ( ! $post_name && isset($wp->query_vars['pagename']) && ! empty($wp->query_vars['pagename'])) {
146 146
 			$post_name = $wp->query_vars['pagename'];
147 147
 		}
148
-		if ( ! $post_name && isset( $wp->request ) && ! empty( $wp->request )) {
149
-			$possible_post_name = basename( $wp->request );
150
-			if ( ! is_numeric( $possible_post_name )) {
148
+		if ( ! $post_name && isset($wp->request) && ! empty($wp->request)) {
149
+			$possible_post_name = basename($wp->request);
150
+			if ( ! is_numeric($possible_post_name)) {
151 151
 				/** @type WPDB $wpdb */
152 152
 				global $wpdb;
153 153
 				$SQL = "SELECT ID from {$wpdb->posts} WHERE post_status='publish' AND post_name=%s";
154
-				$possible_post_name = $wpdb->get_var( $wpdb->prepare( $SQL, $possible_post_name ));
155
-				if ( $possible_post_name ) {
154
+				$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
155
+				if ($possible_post_name) {
156 156
 					$post_name = $possible_post_name;
157 157
 				}
158 158
 			}
159 159
 		}
160
-		if ( ! $post_name && $this->get( 'post_id' )) {
160
+		if ( ! $post_name && $this->get('post_id')) {
161 161
 			/** @type WPDB $wpdb */
162 162
 			global $wpdb;
163 163
 			$SQL = "SELECT post_name from {$wpdb->posts} WHERE post_status='publish' AND ID=%d";
164
-			$possible_post_name = $wpdb->get_var( $wpdb->prepare( $SQL, $this->get( 'post_id' )));
165
-			if( $possible_post_name ) {
164
+			$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->get('post_id')));
165
+			if ($possible_post_name) {
166 166
 				$post_name = $possible_post_name;
167 167
 			}
168 168
 		}
@@ -178,11 +178,11 @@  discard block
 block discarded – undo
178 178
 	 * @param WP $wp
179 179
 	 * @return mixed
180 180
 	 */
181
-	public function get_post_type_from_request( $wp = null ) {
182
-		if ( ! $wp instanceof WP ){
181
+	public function get_post_type_from_request($wp = null) {
182
+		if ( ! $wp instanceof WP) {
183 183
 			global $wp;
184 184
 		}
185
-		return isset( $wp->query_vars['post_type'] ) ? $wp->query_vars['post_type'] : null;
185
+		return isset($wp->query_vars['post_type']) ? $wp->query_vars['post_type'] : null;
186 186
 	}
187 187
 
188 188
 
@@ -192,18 +192,18 @@  discard block
 block discarded – undo
192 192
 	 * @param  WP $wp
193 193
 	 * @return string
194 194
 	 */
195
-	public function get_current_page_permalink( $wp = null ) {
196
-		$post_id = $this->get_post_id_from_request( $wp );
197
-		if ( $post_id ) {
198
-			$current_page_permalink = get_permalink( $post_id );
195
+	public function get_current_page_permalink($wp = null) {
196
+		$post_id = $this->get_post_id_from_request($wp);
197
+		if ($post_id) {
198
+			$current_page_permalink = get_permalink($post_id);
199 199
 		} else {
200
-			if ( ! $wp instanceof WP ) {
200
+			if ( ! $wp instanceof WP) {
201 201
 				global $wp;
202 202
 			}
203
-			if ( $wp->request ) {
204
-				$current_page_permalink = site_url( $wp->request );
203
+			if ($wp->request) {
204
+				$current_page_permalink = site_url($wp->request);
205 205
 			} else {
206
-				$current_page_permalink = esc_url( site_url( $_SERVER[ 'REQUEST_URI' ] ) );
206
+				$current_page_permalink = esc_url(site_url($_SERVER['REQUEST_URI']));
207 207
 			}
208 208
 		}
209 209
 		return $current_page_permalink;
@@ -220,31 +220,31 @@  discard block
 block discarded – undo
220 220
 	public function test_for_espresso_page() {
221 221
 		global $wp;
222 222
 		/** @type EE_CPT_Strategy $EE_CPT_Strategy */
223
-		$EE_CPT_Strategy = EE_Registry::instance()->load_core( 'CPT_Strategy' );
223
+		$EE_CPT_Strategy = EE_Registry::instance()->load_core('CPT_Strategy');
224 224
 		$espresso_CPT_taxonomies = $EE_CPT_Strategy->get_CPT_taxonomies();
225
-		if ( is_array( $espresso_CPT_taxonomies ) ) {
226
-			foreach ( $espresso_CPT_taxonomies as $espresso_CPT_taxonomy =>$details ) {
227
-				if ( isset( $wp->query_vars, $wp->query_vars[ $espresso_CPT_taxonomy ] ) ) {
225
+		if (is_array($espresso_CPT_taxonomies)) {
226
+			foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy =>$details) {
227
+				if (isset($wp->query_vars, $wp->query_vars[$espresso_CPT_taxonomy])) {
228 228
 					return true;
229 229
 				}
230 230
 			}
231 231
 		}
232 232
 		// load espresso CPT endpoints
233 233
 		$espresso_CPT_endpoints = $EE_CPT_Strategy->get_CPT_endpoints();
234
-		$post_type_CPT_endpoints = array_flip( $espresso_CPT_endpoints );
235
-		$post_types = (array)$this->get( 'post_type' );
236
-		foreach ( $post_types as $post_type ) {
234
+		$post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
235
+		$post_types = (array) $this->get('post_type');
236
+		foreach ($post_types as $post_type) {
237 237
 			// was a post name passed ?
238
-			if ( isset( $post_type_CPT_endpoints[ $post_type ] ) ) {
238
+			if (isset($post_type_CPT_endpoints[$post_type])) {
239 239
 				// kk we know this is an espresso page, but is it a specific post ?
240
-				if ( ! $this->get( 'post_name' ) ) {
240
+				if ( ! $this->get('post_name')) {
241 241
 					// there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
242
-					$post_name = isset( $post_type_CPT_endpoints[ $this->get( 'post_type' ) ] )
243
-                        ? $post_type_CPT_endpoints[ $this->get( 'post_type' ) ]
242
+					$post_name = isset($post_type_CPT_endpoints[$this->get('post_type')])
243
+                        ? $post_type_CPT_endpoints[$this->get('post_type')]
244 244
                         : '';
245 245
 					// if the post type matches on of our then set the endpoint
246
-					if ( $post_name ) {
247
-						$this->set( 'post_name', $post_name );
246
+					if ($post_name) {
247
+						$this->set('post_name', $post_name);
248 248
 					}
249 249
 				}
250 250
 				return true;
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
 	 * @param null|bool $value
263 263
 	 * @return    void
264 264
 	 */
265
-	public function set_espresso_page( $value = null ) {
265
+	public function set_espresso_page($value = null) {
266 266
         $this->_params['is_espresso_page'] = ! empty($value) ? $value : $this->test_for_espresso_page();
267 267
 	}
268 268
 
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 	 *  @return 	mixed
276 276
 	 */
277 277
 	public function is_espresso_page() {
278
-		return isset( $this->_params['is_espresso_page'] ) ? $this->_params['is_espresso_page'] : false;
278
+		return isset($this->_params['is_espresso_page']) ? $this->_params['is_espresso_page'] : false;
279 279
 	}
280 280
 
281 281
 
@@ -299,14 +299,14 @@  discard block
 block discarded – undo
299 299
 	 * @param bool $override_ee
300 300
 	 * @return    void
301 301
 	 */
302
-	public function set( $key, $value, $override_ee = false ) {
302
+	public function set($key, $value, $override_ee = false) {
303 303
 		// don't allow "ee" to be overwritten unless explicitly instructed to do so
304 304
 		if (
305 305
 			$key !== 'ee' ||
306
-			( $key === 'ee' && empty( $this->_params['ee'] ))
307
-			|| ( $key === 'ee' && ! empty( $this->_params['ee'] ) && $override_ee )
306
+			($key === 'ee' && empty($this->_params['ee']))
307
+			|| ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
308 308
 		) {
309
-			$this->_params[ $key ] = $value;
309
+			$this->_params[$key] = $value;
310 310
 		}
311 311
 	}
312 312
 
@@ -320,8 +320,8 @@  discard block
 block discarded – undo
320 320
 	 * @param null $default
321 321
 	 * @return    mixed
322 322
 	 */
323
-	public function get( $key, $default = null ) {
324
-		return isset( $this->_params[ $key ] ) ? $this->_params[ $key ] : $default;
323
+	public function get($key, $default = null) {
324
+		return isset($this->_params[$key]) ? $this->_params[$key] : $default;
325 325
 	}
326 326
 
327 327
 
@@ -333,8 +333,8 @@  discard block
 block discarded – undo
333 333
 	 * @param $key
334 334
 	 * @return    boolean
335 335
 	 */
336
-	public function is_set( $key ) {
337
-		return isset( $this->_params[ $key ] ) ? true : false;
336
+	public function is_set($key) {
337
+		return isset($this->_params[$key]) ? true : false;
338 338
 	}
339 339
 
340 340
 
@@ -346,8 +346,8 @@  discard block
 block discarded – undo
346 346
 	 * @param $key
347 347
 	 * @return    void
348 348
 	 */
349
-	public function un_set( $key ) {
350
-		unset( $this->_params[ $key ] );
349
+	public function un_set($key) {
350
+		unset($this->_params[$key]);
351 351
 	}
352 352
 
353 353
 
@@ -360,8 +360,8 @@  discard block
 block discarded – undo
360 360
 	 * @param $value
361 361
 	 * @return    void
362 362
 	 */
363
-	public function set_notice( $key, $value ) {
364
-		$this->_notice[ $key ] = $value;
363
+	public function set_notice($key, $value) {
364
+		$this->_notice[$key] = $value;
365 365
 	}
366 366
 
367 367
 
@@ -373,8 +373,8 @@  discard block
 block discarded – undo
373 373
 	 * @param $key
374 374
 	 * @return    mixed
375 375
 	 */
376
-	public function get_notice( $key ) {
377
-		return isset( $this->_notice[ $key ] ) ? $this->_notice[ $key ] : null;
376
+	public function get_notice($key) {
377
+		return isset($this->_notice[$key]) ? $this->_notice[$key] : null;
378 378
 	}
379 379
 
380 380
 
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 	 * @param $string
387 387
 	 * @return    void
388 388
 	 */
389
-	public function add_output( $string ) {
389
+	public function add_output($string) {
390 390
 		$this->_output .= $string;
391 391
 	}
392 392
 
@@ -408,8 +408,8 @@  discard block
 block discarded – undo
408 408
 	 * @param $item
409 409
 	 * @param $key
410 410
 	 */
411
-	public function sanitize_text_field_for_array_walk( &$item, &$key ) {
412
-		$item = strpos( $item, 'email' ) !== false ? sanitize_email( $item ) : sanitize_text_field( $item );
411
+	public function sanitize_text_field_for_array_walk(&$item, &$key) {
412
+		$item = strpos($item, 'email') !== false ? sanitize_email($item) : sanitize_text_field($item);
413 413
 	}
414 414
 
415 415
 
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 	 * @param $b
420 420
 	 * @return bool
421 421
 	 */
422
-	public function __set($a,$b) { return false; }
422
+	public function __set($a, $b) { return false; }
423 423
 
424 424
 
425 425
 
Please login to merge, or discard this patch.
core/EE_Config.core.php 1 patch
Indentation   +3061 added lines, -3061 removed lines patch added patch discarded remove patch
@@ -17,2443 +17,2443 @@  discard block
 block discarded – undo
17 17
 final class EE_Config implements ResettableInterface
18 18
 {
19 19
 
20
-    const OPTION_NAME        = 'ee_config';
20
+	const OPTION_NAME        = 'ee_config';
21
+
22
+	const LOG_NAME           = 'ee_config_log';
23
+
24
+	const LOG_LENGTH         = 100;
25
+
26
+	const ADDON_OPTION_NAMES = 'ee_config_option_names';
27
+
28
+
29
+	/**
30
+	 *    instance of the EE_Config object
31
+	 *
32
+	 * @var    EE_Config $_instance
33
+	 * @access    private
34
+	 */
35
+	private static $_instance;
36
+
37
+	/**
38
+	 * @var boolean $_logging_enabled
39
+	 */
40
+	private static $_logging_enabled = false;
41
+
42
+	/**
43
+	 * @var LegacyShortcodesManager $legacy_shortcodes_manager
44
+	 */
45
+	private $legacy_shortcodes_manager;
46
+
47
+	/**
48
+	 * An StdClass whose property names are addon slugs,
49
+	 * and values are their config classes
50
+	 *
51
+	 * @var StdClass
52
+	 */
53
+	public $addons;
54
+
55
+	/**
56
+	 * @var EE_Admin_Config
57
+	 */
58
+	public $admin;
59
+
60
+	/**
61
+	 * @var EE_Core_Config
62
+	 */
63
+	public $core;
64
+
65
+	/**
66
+	 * @var EE_Currency_Config
67
+	 */
68
+	public $currency;
69
+
70
+	/**
71
+	 * @var EE_Organization_Config
72
+	 */
73
+	public $organization;
74
+
75
+	/**
76
+	 * @var EE_Registration_Config
77
+	 */
78
+	public $registration;
79
+
80
+	/**
81
+	 * @var EE_Template_Config
82
+	 */
83
+	public $template_settings;
84
+
85
+	/**
86
+	 * Holds EE environment values.
87
+	 *
88
+	 * @var EE_Environment_Config
89
+	 */
90
+	public $environment;
91
+
92
+	/**
93
+	 * settings pertaining to Google maps
94
+	 *
95
+	 * @var EE_Map_Config
96
+	 */
97
+	public $map_settings;
98
+
99
+	/**
100
+	 * settings pertaining to Taxes
101
+	 *
102
+	 * @var EE_Tax_Config
103
+	 */
104
+	public $tax_settings;
105
+
106
+
107
+	/**
108
+	 * Settings pertaining to global messages settings.
109
+	 *
110
+	 * @var EE_Messages_Config
111
+	 */
112
+	public $messages;
113
+
114
+	/**
115
+	 * @deprecated
116
+	 * @var EE_Gateway_Config
117
+	 */
118
+	public $gateway;
119
+
120
+	/**
121
+	 * @var    array $_addon_option_names
122
+	 * @access    private
123
+	 */
124
+	private $_addon_option_names = array();
125
+
126
+	/**
127
+	 * @var    array $_module_route_map
128
+	 * @access    private
129
+	 */
130
+	private static $_module_route_map = array();
131
+
132
+	/**
133
+	 * @var    array $_module_forward_map
134
+	 * @access    private
135
+	 */
136
+	private static $_module_forward_map = array();
137
+
138
+	/**
139
+	 * @var    array $_module_view_map
140
+	 * @access    private
141
+	 */
142
+	private static $_module_view_map = array();
143
+
144
+
145
+
146
+	/**
147
+	 * @singleton method used to instantiate class object
148
+	 * @access    public
149
+	 * @return EE_Config instance
150
+	 */
151
+	public static function instance()
152
+	{
153
+		// check if class object is instantiated, and instantiated properly
154
+		if (! self::$_instance instanceof EE_Config) {
155
+			self::$_instance = new self();
156
+		}
157
+		return self::$_instance;
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 * Resets the config
164
+	 *
165
+	 * @param bool    $hard_reset    if TRUE, sets EE_CONFig back to its original settings in the database. If FALSE
166
+	 *                               (default) leaves the database alone, and merely resets the EE_Config object to
167
+	 *                               reflect its state in the database
168
+	 * @param boolean $reinstantiate if TRUE (default) call instance() and return it. Otherwise, just leave
169
+	 *                               $_instance as NULL. Useful in case you want to forget about the old instance on
170
+	 *                               EE_Config, but might not be ready to instantiate EE_Config currently (eg if the
171
+	 *                               site was put into maintenance mode)
172
+	 * @return EE_Config
173
+	 */
174
+	public static function reset($hard_reset = false, $reinstantiate = true)
175
+	{
176
+		if (self::$_instance instanceof EE_Config) {
177
+			if ($hard_reset) {
178
+				self::$_instance->legacy_shortcodes_manager = null;
179
+				self::$_instance->_addon_option_names = array();
180
+				self::$_instance->_initialize_config();
181
+				self::$_instance->update_espresso_config();
182
+			}
183
+			self::$_instance->update_addon_option_names();
184
+		}
185
+		self::$_instance = null;
186
+		//we don't need to reset the static properties imo because those should
187
+		//only change when a module is added or removed. Currently we don't
188
+		//support removing a module during a request when it previously existed
189
+		if ($reinstantiate) {
190
+			return self::instance();
191
+		} else {
192
+			return null;
193
+		}
194
+	}
195
+
196
+
197
+
198
+	/**
199
+	 *    class constructor
200
+	 *
201
+	 * @access    private
202
+	 */
203
+	private function __construct()
204
+	{
205
+		do_action('AHEE__EE_Config__construct__begin', $this);
206
+		EE_Config::$_logging_enabled = apply_filters('FHEE__EE_Config___construct__logging_enabled', false);
207
+		// setup empty config classes
208
+		$this->_initialize_config();
209
+		// load existing EE site settings
210
+		$this->_load_core_config();
211
+		// confirm everything loaded correctly and set filtered defaults if not
212
+		$this->_verify_config();
213
+		//  register shortcodes and modules
214
+		add_action(
215
+			'AHEE__EE_System__register_shortcodes_modules_and_widgets',
216
+			array($this, 'register_shortcodes_and_modules'),
217
+			999
218
+		);
219
+		//  initialize shortcodes and modules
220
+		add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'initialize_shortcodes_and_modules'));
221
+		// register widgets
222
+		add_action('widgets_init', array($this, 'widgets_init'), 10);
223
+		// shutdown
224
+		add_action('shutdown', array($this, 'shutdown'), 10);
225
+		// construct__end hook
226
+		do_action('AHEE__EE_Config__construct__end', $this);
227
+		// hardcoded hack
228
+		$this->template_settings->current_espresso_theme = 'Espresso_Arabica_2014';
229
+	}
230
+
231
+
232
+
233
+	/**
234
+	 * @return boolean
235
+	 */
236
+	public static function logging_enabled()
237
+	{
238
+		return self::$_logging_enabled;
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * use to get the current theme if needed from static context
245
+	 *
246
+	 * @return string current theme set.
247
+	 */
248
+	public static function get_current_theme()
249
+	{
250
+		return isset(self::$_instance->template_settings->current_espresso_theme)
251
+			? self::$_instance->template_settings->current_espresso_theme : 'Espresso_Arabica_2014';
252
+	}
253
+
254
+
255
+
256
+	/**
257
+	 *        _initialize_config
258
+	 *
259
+	 * @access private
260
+	 * @return void
261
+	 */
262
+	private function _initialize_config()
263
+	{
264
+		EE_Config::trim_log();
265
+		//set defaults
266
+		$this->_addon_option_names = get_option(EE_Config::ADDON_OPTION_NAMES, array());
267
+		$this->addons = new stdClass();
268
+		// set _module_route_map
269
+		EE_Config::$_module_route_map = array();
270
+		// set _module_forward_map
271
+		EE_Config::$_module_forward_map = array();
272
+		// set _module_view_map
273
+		EE_Config::$_module_view_map = array();
274
+	}
275
+
276
+
277
+
278
+	/**
279
+	 *        load core plugin configuration
280
+	 *
281
+	 * @access private
282
+	 * @return void
283
+	 */
284
+	private function _load_core_config()
285
+	{
286
+		// load_core_config__start hook
287
+		do_action('AHEE__EE_Config___load_core_config__start', $this);
288
+		$espresso_config = $this->get_espresso_config();
289
+		foreach ($espresso_config as $config => $settings) {
290
+			// load_core_config__start hook
291
+			$settings = apply_filters(
292
+				'FHEE__EE_Config___load_core_config__config_settings',
293
+				$settings,
294
+				$config,
295
+				$this
296
+			);
297
+			if (is_object($settings) && property_exists($this, $config)) {
298
+				$this->{$config} = apply_filters('FHEE__EE_Config___load_core_config__' . $config, $settings);
299
+				//call configs populate method to ensure any defaults are set for empty values.
300
+				if (method_exists($settings, 'populate')) {
301
+					$this->{$config}->populate();
302
+				}
303
+				if (method_exists($settings, 'do_hooks')) {
304
+					$this->{$config}->do_hooks();
305
+				}
306
+			}
307
+		}
308
+		if (apply_filters('FHEE__EE_Config___load_core_config__update_espresso_config', false)) {
309
+			$this->update_espresso_config();
310
+		}
311
+		// load_core_config__end hook
312
+		do_action('AHEE__EE_Config___load_core_config__end', $this);
313
+	}
314
+
315
+
316
+
317
+	/**
318
+	 *    _verify_config
319
+	 *
320
+	 * @access    protected
321
+	 * @return    void
322
+	 */
323
+	protected function _verify_config()
324
+	{
325
+		$this->core = $this->core instanceof EE_Core_Config
326
+			? $this->core
327
+			: new EE_Core_Config();
328
+		$this->core = apply_filters('FHEE__EE_Config___initialize_config__core', $this->core);
329
+		$this->organization = $this->organization instanceof EE_Organization_Config
330
+			? $this->organization
331
+			: new EE_Organization_Config();
332
+		$this->organization = apply_filters(
333
+			'FHEE__EE_Config___initialize_config__organization',
334
+			$this->organization
335
+		);
336
+		$this->currency = $this->currency instanceof EE_Currency_Config
337
+			? $this->currency
338
+			: new EE_Currency_Config();
339
+		$this->currency = apply_filters('FHEE__EE_Config___initialize_config__currency', $this->currency);
340
+		$this->registration = $this->registration instanceof EE_Registration_Config
341
+			? $this->registration
342
+			: new EE_Registration_Config();
343
+		$this->registration = apply_filters(
344
+			'FHEE__EE_Config___initialize_config__registration',
345
+			$this->registration
346
+		);
347
+		$this->admin = $this->admin instanceof EE_Admin_Config
348
+			? $this->admin
349
+			: new EE_Admin_Config();
350
+		$this->admin = apply_filters('FHEE__EE_Config___initialize_config__admin', $this->admin);
351
+		$this->template_settings = $this->template_settings instanceof EE_Template_Config
352
+			? $this->template_settings
353
+			: new EE_Template_Config();
354
+		$this->template_settings = apply_filters(
355
+			'FHEE__EE_Config___initialize_config__template_settings',
356
+			$this->template_settings
357
+		);
358
+		$this->map_settings = $this->map_settings instanceof EE_Map_Config
359
+			? $this->map_settings
360
+			: new EE_Map_Config();
361
+		$this->map_settings = apply_filters('FHEE__EE_Config___initialize_config__map_settings',
362
+			$this->map_settings);
363
+		$this->environment = $this->environment instanceof EE_Environment_Config
364
+			? $this->environment
365
+			: new EE_Environment_Config();
366
+		$this->environment = apply_filters('FHEE__EE_Config___initialize_config__environment',
367
+			$this->environment);
368
+		$this->tax_settings = $this->tax_settings instanceof EE_Tax_Config
369
+			? $this->tax_settings
370
+			: new EE_Tax_Config();
371
+		$this->tax_settings = apply_filters('FHEE__EE_Config___initialize_config__tax_settings',
372
+			$this->tax_settings);
373
+		$this->messages = apply_filters('FHEE__EE_Config__initialize_config__messages', $this->messages);
374
+		$this->messages = $this->messages instanceof EE_Messages_Config
375
+			? $this->messages
376
+			: new EE_Messages_Config();
377
+		$this->gateway = $this->gateway instanceof EE_Gateway_Config
378
+			? $this->gateway
379
+			: new EE_Gateway_Config();
380
+		$this->gateway = apply_filters('FHEE__EE_Config___initialize_config__gateway', $this->gateway);
381
+		$this->legacy_shortcodes_manager = null;
382
+	}
383
+
384
+
385
+	/**
386
+	 *    get_espresso_config
387
+	 *
388
+	 * @access    public
389
+	 * @return    array of espresso config stuff
390
+	 */
391
+	public function get_espresso_config()
392
+	{
393
+		// grab espresso configuration
394
+		return apply_filters(
395
+			'FHEE__EE_Config__get_espresso_config__CFG',
396
+			get_option(EE_Config::OPTION_NAME, array())
397
+		);
398
+	}
399
+
400
+
401
+
402
+	/**
403
+	 *    double_check_config_comparison
404
+	 *
405
+	 * @access    public
406
+	 * @param string $option
407
+	 * @param        $old_value
408
+	 * @param        $value
409
+	 */
410
+	public function double_check_config_comparison($option = '', $old_value, $value)
411
+	{
412
+		// make sure we're checking the ee config
413
+		if ($option === EE_Config::OPTION_NAME) {
414
+			// run a loose comparison of the old value against the new value for type and properties,
415
+			// but NOT exact instance like WP update_option does (ie: NOT type safe comparison)
416
+			if ($value != $old_value) {
417
+				// if they are NOT the same, then remove the hook,
418
+				// which means the subsequent update results will be based solely on the update query results
419
+				// the reason we do this is because, as stated above,
420
+				// WP update_option performs an exact instance comparison (===) on any update values passed to it
421
+				// this happens PRIOR to serialization and any subsequent update.
422
+				// If values are found to match their previous old value,
423
+				// then WP bails before performing any update.
424
+				// Since we are passing the EE_Config object, it is comparing the EXACT instance of the saved version
425
+				// it just pulled from the db, with the one being passed to it (which will not match).
426
+				// HOWEVER, once the object is serialized and passed off to MySQL to update,
427
+				// MySQL MAY ALSO NOT perform the update because
428
+				// the string it sees in the db looks the same as the new one it has been passed!!!
429
+				// This results in the query returning an "affected rows" value of ZERO,
430
+				// which gets returned immediately by WP update_option and looks like an error.
431
+				remove_action('update_option', array($this, 'check_config_updated'));
432
+			}
433
+		}
434
+	}
435
+
436
+
437
+
438
+	/**
439
+	 *    update_espresso_config
440
+	 *
441
+	 * @access   public
442
+	 */
443
+	protected function _reset_espresso_addon_config()
444
+	{
445
+		$this->_addon_option_names = array();
446
+		foreach ($this->addons as $addon_name => $addon_config_obj) {
447
+			$addon_config_obj = maybe_unserialize($addon_config_obj);
448
+			$config_class = get_class($addon_config_obj);
449
+			if ($addon_config_obj instanceof $config_class && ! $addon_config_obj instanceof __PHP_Incomplete_Class) {
450
+				$this->update_config('addons', $addon_name, $addon_config_obj, false);
451
+			}
452
+			$this->addons->{$addon_name} = null;
453
+		}
454
+	}
455
+
456
+
457
+
458
+	/**
459
+	 *    update_espresso_config
460
+	 *
461
+	 * @access   public
462
+	 * @param   bool $add_success
463
+	 * @param   bool $add_error
464
+	 * @return   bool
465
+	 */
466
+	public function update_espresso_config($add_success = false, $add_error = true)
467
+	{
468
+		// don't allow config updates during WP heartbeats
469
+		if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
470
+			return false;
471
+		}
472
+		// commented out the following re: https://events.codebasehq.com/projects/event-espresso/tickets/8197
473
+		//$clone = clone( self::$_instance );
474
+		//self::$_instance = NULL;
475
+		do_action('AHEE__EE_Config__update_espresso_config__begin', $this);
476
+		$this->_reset_espresso_addon_config();
477
+		// hook into update_option because that happens AFTER the ( $value === $old_value ) conditional
478
+		// but BEFORE the actual update occurs
479
+		add_action('update_option', array($this, 'double_check_config_comparison'), 1, 3);
480
+		// don't want to persist legacy_shortcodes_manager, but don't want to lose it either
481
+		$legacy_shortcodes_manager = $this->legacy_shortcodes_manager;
482
+		$this->legacy_shortcodes_manager = null;
483
+		// now update "ee_config"
484
+		$saved = update_option(EE_Config::OPTION_NAME, $this);
485
+		$this->legacy_shortcodes_manager = $legacy_shortcodes_manager;
486
+		EE_Config::log(EE_Config::OPTION_NAME);
487
+		// if not saved... check if the hook we just added still exists;
488
+		// if it does, it means one of two things:
489
+		// 		that update_option bailed at the ( $value === $old_value ) conditional,
490
+		//		 or...
491
+		// 		the db update query returned 0 rows affected
492
+		// 		(probably because the data  value was the same from it's perspective)
493
+		// so the existence of the hook means that a negative result from update_option is NOT an error,
494
+		// but just means no update occurred, so don't display an error to the user.
495
+		// BUT... if update_option returns FALSE, AND the hook is missing,
496
+		// then it means that something truly went wrong
497
+		$saved = ! $saved ? has_action('update_option', array($this, 'double_check_config_comparison')) : $saved;
498
+		// remove our action since we don't want it in the system anymore
499
+		remove_action('update_option', array($this, 'double_check_config_comparison'), 1);
500
+		do_action('AHEE__EE_Config__update_espresso_config__end', $this, $saved);
501
+		//self::$_instance = $clone;
502
+		//unset( $clone );
503
+		// if config remains the same or was updated successfully
504
+		if ($saved) {
505
+			if ($add_success) {
506
+				EE_Error::add_success(
507
+					__('The Event Espresso Configuration Settings have been successfully updated.', 'event_espresso'),
508
+					__FILE__,
509
+					__FUNCTION__,
510
+					__LINE__
511
+				);
512
+			}
513
+			return true;
514
+		} else {
515
+			if ($add_error) {
516
+				EE_Error::add_error(
517
+					__('The Event Espresso Configuration Settings were not updated.', 'event_espresso'),
518
+					__FILE__,
519
+					__FUNCTION__,
520
+					__LINE__
521
+				);
522
+			}
523
+			return false;
524
+		}
525
+	}
526
+
527
+
528
+
529
+	/**
530
+	 *    _verify_config_params
531
+	 *
532
+	 * @access    private
533
+	 * @param    string         $section
534
+	 * @param    string         $name
535
+	 * @param    string         $config_class
536
+	 * @param    EE_Config_Base $config_obj
537
+	 * @param    array          $tests_to_run
538
+	 * @param    bool           $display_errors
539
+	 * @return    bool    TRUE on success, FALSE on fail
540
+	 */
541
+	private function _verify_config_params(
542
+		$section = '',
543
+		$name = '',
544
+		$config_class = '',
545
+		$config_obj = null,
546
+		$tests_to_run = array(1, 2, 3, 4, 5, 6, 7, 8),
547
+		$display_errors = true
548
+	) {
549
+		try {
550
+			foreach ($tests_to_run as $test) {
551
+				switch ($test) {
552
+					// TEST #1 : check that section was set
553
+					case 1 :
554
+						if (empty($section)) {
555
+							if ($display_errors) {
556
+								throw new EE_Error(
557
+									sprintf(
558
+										__(
559
+											'No configuration section has been provided while attempting to save "%s".',
560
+											'event_espresso'
561
+										),
562
+										$config_class
563
+									)
564
+								);
565
+							}
566
+							return false;
567
+						}
568
+						break;
569
+					// TEST #2 : check that settings section exists
570
+					case 2 :
571
+						if (! isset($this->{$section})) {
572
+							if ($display_errors) {
573
+								throw new EE_Error(
574
+									sprintf(
575
+										__('The "%s" configuration section does not exist.', 'event_espresso'),
576
+										$section
577
+									)
578
+								);
579
+							}
580
+							return false;
581
+						}
582
+						break;
583
+					// TEST #3 : check that section is the proper format
584
+					case 3 :
585
+						if (
586
+						! ($this->{$section} instanceof EE_Config_Base || $this->{$section} instanceof stdClass)
587
+						) {
588
+							if ($display_errors) {
589
+								throw new EE_Error(
590
+									sprintf(
591
+										__(
592
+											'The "%s" configuration settings have not been formatted correctly.',
593
+											'event_espresso'
594
+										),
595
+										$section
596
+									)
597
+								);
598
+							}
599
+							return false;
600
+						}
601
+						break;
602
+					// TEST #4 : check that config section name has been set
603
+					case 4 :
604
+						if (empty($name)) {
605
+							if ($display_errors) {
606
+								throw new EE_Error(
607
+									__(
608
+										'No name has been provided for the specific configuration section.',
609
+										'event_espresso'
610
+									)
611
+								);
612
+							}
613
+							return false;
614
+						}
615
+						break;
616
+					// TEST #5 : check that a config class name has been set
617
+					case 5 :
618
+						if (empty($config_class)) {
619
+							if ($display_errors) {
620
+								throw new EE_Error(
621
+									__(
622
+										'No class name has been provided for the specific configuration section.',
623
+										'event_espresso'
624
+									)
625
+								);
626
+							}
627
+							return false;
628
+						}
629
+						break;
630
+					// TEST #6 : verify config class is accessible
631
+					case 6 :
632
+						if (! class_exists($config_class)) {
633
+							if ($display_errors) {
634
+								throw new EE_Error(
635
+									sprintf(
636
+										__(
637
+											'The "%s" class does not exist. Please ensure that an autoloader has been set for it.',
638
+											'event_espresso'
639
+										),
640
+										$config_class
641
+									)
642
+								);
643
+							}
644
+							return false;
645
+						}
646
+						break;
647
+					// TEST #7 : check that config has even been set
648
+					case 7 :
649
+						if (! isset($this->{$section}->{$name})) {
650
+							if ($display_errors) {
651
+								throw new EE_Error(
652
+									sprintf(
653
+										__('No configuration has been set for "%1$s->%2$s".', 'event_espresso'),
654
+										$section,
655
+										$name
656
+									)
657
+								);
658
+							}
659
+							return false;
660
+						} else {
661
+							// and make sure it's not serialized
662
+							$this->{$section}->{$name} = maybe_unserialize($this->{$section}->{$name});
663
+						}
664
+						break;
665
+					// TEST #8 : check that config is the requested type
666
+					case 8 :
667
+						if (! $this->{$section}->{$name} instanceof $config_class) {
668
+							if ($display_errors) {
669
+								throw new EE_Error(
670
+									sprintf(
671
+										__(
672
+											'The configuration for "%1$s->%2$s" is not of the "%3$s" class.',
673
+											'event_espresso'
674
+										),
675
+										$section,
676
+										$name,
677
+										$config_class
678
+									)
679
+								);
680
+							}
681
+							return false;
682
+						}
683
+						break;
684
+					// TEST #9 : verify config object
685
+					case 9 :
686
+						if (! $config_obj instanceof EE_Config_Base) {
687
+							if ($display_errors) {
688
+								throw new EE_Error(
689
+									sprintf(
690
+										__('The "%s" class is not an instance of EE_Config_Base.', 'event_espresso'),
691
+										print_r($config_obj, true)
692
+									)
693
+								);
694
+							}
695
+							return false;
696
+						}
697
+						break;
698
+				}
699
+			}
700
+		} catch (EE_Error $e) {
701
+			$e->get_error();
702
+		}
703
+		// you have successfully run the gauntlet
704
+		return true;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 *    _generate_config_option_name
711
+	 *
712
+	 * @access        protected
713
+	 * @param        string $section
714
+	 * @param        string $name
715
+	 * @return        string
716
+	 */
717
+	private function _generate_config_option_name($section = '', $name = '')
718
+	{
719
+		return 'ee_config-' . strtolower($section . '-' . str_replace(array('EE_', 'EED_'), '', $name));
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 *    _set_config_class
726
+	 * ensures that a config class is set, either from a passed config class or one generated from the config name
727
+	 *
728
+	 * @access    private
729
+	 * @param    string $config_class
730
+	 * @param    string $name
731
+	 * @return    string
732
+	 */
733
+	private function _set_config_class($config_class = '', $name = '')
734
+	{
735
+		return ! empty($config_class)
736
+			? $config_class
737
+			: str_replace(' ', '_', ucwords(str_replace('_', ' ', $name))) . '_Config';
738
+	}
739
+
740
+
741
+
742
+	/**
743
+	 *    set_config
744
+	 *
745
+	 * @access    protected
746
+	 * @param    string         $section
747
+	 * @param    string         $name
748
+	 * @param    string         $config_class
749
+	 * @param    EE_Config_Base $config_obj
750
+	 * @return    EE_Config_Base
751
+	 */
752
+	public function set_config($section = '', $name = '', $config_class = '', EE_Config_Base $config_obj = null)
753
+	{
754
+		// ensure config class is set to something
755
+		$config_class = $this->_set_config_class($config_class, $name);
756
+		// run tests 1-4, 6, and 7 to verify all config params are set and valid
757
+		if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
758
+			return null;
759
+		}
760
+		$config_option_name = $this->_generate_config_option_name($section, $name);
761
+		// if the config option name hasn't been added yet to the list of option names we're tracking, then do so now
762
+		if (! isset($this->_addon_option_names[$config_option_name])) {
763
+			$this->_addon_option_names[$config_option_name] = $config_class;
764
+			$this->update_addon_option_names();
765
+		}
766
+		// verify the incoming config object but suppress errors
767
+		if (! $this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
768
+			$config_obj = new $config_class();
769
+		}
770
+		if (get_option($config_option_name)) {
771
+			EE_Config::log($config_option_name);
772
+			update_option($config_option_name, $config_obj);
773
+			$this->{$section}->{$name} = $config_obj;
774
+			return $this->{$section}->{$name};
775
+		} else {
776
+			// create a wp-option for this config
777
+			if (add_option($config_option_name, $config_obj, '', 'no')) {
778
+				$this->{$section}->{$name} = maybe_unserialize($config_obj);
779
+				return $this->{$section}->{$name};
780
+			} else {
781
+				EE_Error::add_error(
782
+					sprintf(__('The "%s" could not be saved to the database.', 'event_espresso'), $config_class),
783
+					__FILE__,
784
+					__FUNCTION__,
785
+					__LINE__
786
+				);
787
+				return null;
788
+			}
789
+		}
790
+	}
791
+
792
+
793
+
794
+	/**
795
+	 *    update_config
796
+	 * Important: the config object must ALREADY be set, otherwise this will produce an error.
797
+	 *
798
+	 * @access    public
799
+	 * @param    string                $section
800
+	 * @param    string                $name
801
+	 * @param    EE_Config_Base|string $config_obj
802
+	 * @param    bool                  $throw_errors
803
+	 * @return    bool
804
+	 */
805
+	public function update_config($section = '', $name = '', $config_obj = '', $throw_errors = true)
806
+	{
807
+		// don't allow config updates during WP heartbeats
808
+		if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
809
+			return false;
810
+		}
811
+		$config_obj = maybe_unserialize($config_obj);
812
+		// get class name of the incoming object
813
+		$config_class = get_class($config_obj);
814
+		// run tests 1-5 and 9 to verify config
815
+		if (! $this->_verify_config_params(
816
+			$section,
817
+			$name,
818
+			$config_class,
819
+			$config_obj,
820
+			array(1, 2, 3, 4, 7, 9)
821
+		)
822
+		) {
823
+			return false;
824
+		}
825
+		$config_option_name = $this->_generate_config_option_name($section, $name);
826
+		// check if config object has been added to db by seeing if config option name is in $this->_addon_option_names array
827
+		if (! isset($this->_addon_option_names[$config_option_name])) {
828
+			// save new config to db
829
+			if ($this->set_config($section, $name, $config_class, $config_obj)) {
830
+				return true;
831
+			}
832
+		} else {
833
+			// first check if the record already exists
834
+			$existing_config = get_option($config_option_name);
835
+			$config_obj = serialize($config_obj);
836
+			// just return if db record is already up to date (NOT type safe comparison)
837
+			if ($existing_config == $config_obj) {
838
+				$this->{$section}->{$name} = $config_obj;
839
+				return true;
840
+			} else if (update_option($config_option_name, $config_obj)) {
841
+				EE_Config::log($config_option_name);
842
+				// update wp-option for this config class
843
+				$this->{$section}->{$name} = $config_obj;
844
+				return true;
845
+			} elseif ($throw_errors) {
846
+				EE_Error::add_error(
847
+					sprintf(
848
+						__(
849
+							'The "%1$s" object stored at"%2$s" was not successfully updated in the database.',
850
+							'event_espresso'
851
+						),
852
+						$config_class,
853
+						'EE_Config->' . $section . '->' . $name
854
+					),
855
+					__FILE__,
856
+					__FUNCTION__,
857
+					__LINE__
858
+				);
859
+			}
860
+		}
861
+		return false;
862
+	}
863
+
864
+
865
+
866
+	/**
867
+	 *    get_config
868
+	 *
869
+	 * @access    public
870
+	 * @param    string $section
871
+	 * @param    string $name
872
+	 * @param    string $config_class
873
+	 * @return    mixed EE_Config_Base | NULL
874
+	 */
875
+	public function get_config($section = '', $name = '', $config_class = '')
876
+	{
877
+		// ensure config class is set to something
878
+		$config_class = $this->_set_config_class($config_class, $name);
879
+		// run tests 1-4, 6 and 7 to verify that all params have been set
880
+		if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
881
+			return null;
882
+		}
883
+		// now test if the requested config object exists, but suppress errors
884
+		if ($this->_verify_config_params($section, $name, $config_class, null, array(7, 8), false)) {
885
+			// config already exists, so pass it back
886
+			return $this->{$section}->{$name};
887
+		}
888
+		// load config option from db if it exists
889
+		$config_obj = $this->get_config_option($this->_generate_config_option_name($section, $name));
890
+		// verify the newly retrieved config object, but suppress errors
891
+		if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
892
+			// config is good, so set it and pass it back
893
+			$this->{$section}->{$name} = $config_obj;
894
+			return $this->{$section}->{$name};
895
+		}
896
+		// oops! $config_obj is not already set and does not exist in the db, so create a new one
897
+		$config_obj = $this->set_config($section, $name, $config_class);
898
+		// verify the newly created config object
899
+		if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9))) {
900
+			return $this->{$section}->{$name};
901
+		} else {
902
+			EE_Error::add_error(
903
+				sprintf(__('The "%s" could not be retrieved from the database.', 'event_espresso'), $config_class),
904
+				__FILE__,
905
+				__FUNCTION__,
906
+				__LINE__
907
+			);
908
+		}
909
+		return null;
910
+	}
911
+
912
+
913
+
914
+	/**
915
+	 *    get_config_option
916
+	 *
917
+	 * @access    public
918
+	 * @param    string $config_option_name
919
+	 * @return    mixed EE_Config_Base | FALSE
920
+	 */
921
+	public function get_config_option($config_option_name = '')
922
+	{
923
+		// retrieve the wp-option for this config class.
924
+		$config_option = maybe_unserialize(get_option($config_option_name, array()));
925
+		if (empty($config_option)) {
926
+			EE_Config::log($config_option_name . '-NOT-FOUND');
927
+		}
928
+		return $config_option;
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * log
935
+	 *
936
+	 * @param string $config_option_name
937
+	 */
938
+	public static function log($config_option_name = '')
939
+	{
940
+		if (EE_Config::logging_enabled() && ! empty($config_option_name)) {
941
+			$config_log = get_option(EE_Config::LOG_NAME, array());
942
+			//copy incoming $_REQUEST and sanitize it so we can save it
943
+			$_request = $_REQUEST;
944
+			array_walk_recursive($_request, 'sanitize_text_field');
945
+			$config_log[(string)microtime(true)] = array(
946
+				'config_name' => $config_option_name,
947
+				'request'     => $_request,
948
+			);
949
+			update_option(EE_Config::LOG_NAME, $config_log);
950
+		}
951
+	}
952
+
953
+
954
+
955
+	/**
956
+	 * trim_log
957
+	 * reduces the size of the config log to the length specified by EE_Config::LOG_LENGTH
958
+	 */
959
+	public static function trim_log()
960
+	{
961
+		if (! EE_Config::logging_enabled()) {
962
+			return;
963
+		}
964
+		$config_log = maybe_unserialize(get_option(EE_Config::LOG_NAME, array()));
965
+		$log_length = count($config_log);
966
+		if ($log_length > EE_Config::LOG_LENGTH) {
967
+			ksort($config_log);
968
+			$config_log = array_slice($config_log, $log_length - EE_Config::LOG_LENGTH, null, true);
969
+			update_option(EE_Config::LOG_NAME, $config_log);
970
+		}
971
+	}
972
+
973
+
974
+
975
+	/**
976
+	 *    get_page_for_posts
977
+	 *    if the wp-option "show_on_front" is set to "page", then this is the post_name for the post set in the
978
+	 *    wp-option "page_for_posts", or "posts" if no page is selected
979
+	 *
980
+	 * @access    public
981
+	 * @return    string
982
+	 */
983
+	public static function get_page_for_posts()
984
+	{
985
+		$page_for_posts = get_option('page_for_posts');
986
+		if (! $page_for_posts) {
987
+			return 'posts';
988
+		}
989
+		/** @type WPDB $wpdb */
990
+		global $wpdb;
991
+		$SQL = "SELECT post_name from $wpdb->posts WHERE post_type='posts' OR post_type='page' AND post_status='publish' AND ID=%d";
992
+		return $wpdb->get_var($wpdb->prepare($SQL, $page_for_posts));
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 *    register_shortcodes_and_modules.
999
+	 *    At this point, it's too early to tell if we're maintenance mode or not.
1000
+	 *    In fact, this is where we give modules a chance to let core know they exist
1001
+	 *    so they can help trigger maintenance mode if it's needed
1002
+	 *
1003
+	 * @access    public
1004
+	 * @return    void
1005
+	 */
1006
+	public function register_shortcodes_and_modules()
1007
+	{
1008
+		// allow modules to set hooks for the rest of the system
1009
+		EE_Registry::instance()->modules = $this->_register_modules();
1010
+	}
1011
+
1012
+
1013
+
1014
+	/**
1015
+	 *    initialize_shortcodes_and_modules
1016
+	 *    meaning they can start adding their hooks to get stuff done
1017
+	 *
1018
+	 * @access    public
1019
+	 * @return    void
1020
+	 */
1021
+	public function initialize_shortcodes_and_modules()
1022
+	{
1023
+		// allow modules to set hooks for the rest of the system
1024
+		$this->_initialize_modules();
1025
+	}
1026
+
1027
+
1028
+
1029
+	/**
1030
+	 *    widgets_init
1031
+	 *
1032
+	 * @access private
1033
+	 * @return void
1034
+	 */
1035
+	public function widgets_init()
1036
+	{
1037
+		//only init widgets on admin pages when not in complete maintenance, and
1038
+		//on frontend when not in any maintenance mode
1039
+		if (
1040
+			! EE_Maintenance_Mode::instance()->level()
1041
+			|| (
1042
+				is_admin()
1043
+				&& EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
1044
+			)
1045
+		) {
1046
+			// grab list of installed widgets
1047
+			$widgets_to_register = glob(EE_WIDGETS . '*', GLOB_ONLYDIR);
1048
+			// filter list of modules to register
1049
+			$widgets_to_register = apply_filters(
1050
+				'FHEE__EE_Config__register_widgets__widgets_to_register',
1051
+				$widgets_to_register
1052
+			);
1053
+			if (! empty($widgets_to_register)) {
1054
+				// cycle thru widget folders
1055
+				foreach ($widgets_to_register as $widget_path) {
1056
+					// add to list of installed widget modules
1057
+					EE_Config::register_ee_widget($widget_path);
1058
+				}
1059
+			}
1060
+			// filter list of installed modules
1061
+			EE_Registry::instance()->widgets = apply_filters(
1062
+				'FHEE__EE_Config__register_widgets__installed_widgets',
1063
+				EE_Registry::instance()->widgets
1064
+			);
1065
+		}
1066
+	}
1067
+
1068
+
1069
+
1070
+	/**
1071
+	 *    register_ee_widget - makes core aware of this widget
1072
+	 *
1073
+	 * @access    public
1074
+	 * @param    string $widget_path - full path up to and including widget folder
1075
+	 * @return    void
1076
+	 */
1077
+	public static function register_ee_widget($widget_path = null)
1078
+	{
1079
+		do_action('AHEE__EE_Config__register_widget__begin', $widget_path);
1080
+		$widget_ext = '.widget.php';
1081
+		// make all separators match
1082
+		$widget_path = rtrim(str_replace('/\\', DS, $widget_path), DS);
1083
+		// does the file path INCLUDE the actual file name as part of the path ?
1084
+		if (strpos($widget_path, $widget_ext) !== false) {
1085
+			// grab and shortcode file name from directory name and break apart at dots
1086
+			$file_name = explode('.', basename($widget_path));
1087
+			// take first segment from file name pieces and remove class prefix if it exists
1088
+			$widget = strpos($file_name[0], 'EEW_') === 0 ? substr($file_name[0], 4) : $file_name[0];
1089
+			// sanitize shortcode directory name
1090
+			$widget = sanitize_key($widget);
1091
+			// now we need to rebuild the shortcode path
1092
+			$widget_path = explode(DS, $widget_path);
1093
+			// remove last segment
1094
+			array_pop($widget_path);
1095
+			// glue it back together
1096
+			$widget_path = implode(DS, $widget_path);
1097
+		} else {
1098
+			// grab and sanitize widget directory name
1099
+			$widget = sanitize_key(basename($widget_path));
1100
+		}
1101
+		// create classname from widget directory name
1102
+		$widget = str_replace(' ', '_', ucwords(str_replace('_', ' ', $widget)));
1103
+		// add class prefix
1104
+		$widget_class = 'EEW_' . $widget;
1105
+		// does the widget exist ?
1106
+		if (! is_readable($widget_path . DS . $widget_class . $widget_ext)) {
1107
+			$msg = sprintf(
1108
+				__(
1109
+					'The requested %s widget file could not be found or is not readable due to file permissions. Please ensure the following path is correct: %s',
1110
+					'event_espresso'
1111
+				),
1112
+				$widget_class,
1113
+				$widget_path . DS . $widget_class . $widget_ext
1114
+			);
1115
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1116
+			return;
1117
+		}
1118
+		// load the widget class file
1119
+		require_once($widget_path . DS . $widget_class . $widget_ext);
1120
+		// verify that class exists
1121
+		if (! class_exists($widget_class)) {
1122
+			$msg = sprintf(__('The requested %s widget class does not exist.', 'event_espresso'), $widget_class);
1123
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1124
+			return;
1125
+		}
1126
+		register_widget($widget_class);
1127
+		// add to array of registered widgets
1128
+		EE_Registry::instance()->widgets->{$widget_class} = $widget_path . DS . $widget_class . $widget_ext;
1129
+	}
1130
+
1131
+
1132
+
1133
+	/**
1134
+	 *        _register_modules
1135
+	 *
1136
+	 * @access private
1137
+	 * @return array
1138
+	 */
1139
+	private function _register_modules()
1140
+	{
1141
+		// grab list of installed modules
1142
+		$modules_to_register = glob(EE_MODULES . '*', GLOB_ONLYDIR);
1143
+		// filter list of modules to register
1144
+		$modules_to_register = apply_filters(
1145
+			'FHEE__EE_Config__register_modules__modules_to_register',
1146
+			$modules_to_register
1147
+		);
1148
+		if (! empty($modules_to_register)) {
1149
+			// loop through folders
1150
+			foreach ($modules_to_register as $module_path) {
1151
+				/**TEMPORARILY EXCLUDE gateways from modules for time being**/
1152
+				if (
1153
+					$module_path !== EE_MODULES . 'zzz-copy-this-module-template'
1154
+					&& $module_path !== EE_MODULES . 'gateways'
1155
+				) {
1156
+					// add to list of installed modules
1157
+					EE_Config::register_module($module_path);
1158
+				}
1159
+			}
1160
+		}
1161
+		// filter list of installed modules
1162
+		return apply_filters(
1163
+			'FHEE__EE_Config___register_modules__installed_modules',
1164
+			EE_Registry::instance()->modules
1165
+		);
1166
+	}
1167
+
1168
+
1169
+
1170
+	/**
1171
+	 *    register_module - makes core aware of this module
1172
+	 *
1173
+	 * @access    public
1174
+	 * @param    string $module_path - full path up to and including module folder
1175
+	 * @return    bool
1176
+	 */
1177
+	public static function register_module($module_path = null)
1178
+	{
1179
+		do_action('AHEE__EE_Config__register_module__begin', $module_path);
1180
+		$module_ext = '.module.php';
1181
+		// make all separators match
1182
+		$module_path = str_replace(array('\\', '/'), DS, $module_path);
1183
+		// does the file path INCLUDE the actual file name as part of the path ?
1184
+		if (strpos($module_path, $module_ext) !== false) {
1185
+			// grab and shortcode file name from directory name and break apart at dots
1186
+			$module_file = explode('.', basename($module_path));
1187
+			// now we need to rebuild the shortcode path
1188
+			$module_path = explode(DS, $module_path);
1189
+			// remove last segment
1190
+			array_pop($module_path);
1191
+			// glue it back together
1192
+			$module_path = implode(DS, $module_path) . DS;
1193
+			// take first segment from file name pieces and sanitize it
1194
+			$module = preg_replace('/[^a-zA-Z0-9_\-]/', '', $module_file[0]);
1195
+			// ensure class prefix is added
1196
+			$module_class = strpos($module, 'EED_') !== 0 ? 'EED_' . $module : $module;
1197
+		} else {
1198
+			// we need to generate the filename based off of the folder name
1199
+			// grab and sanitize module name
1200
+			$module = strtolower(basename($module_path));
1201
+			$module = preg_replace('/[^a-z0-9_\-]/', '', $module);
1202
+			// like trailingslashit()
1203
+			$module_path = rtrim($module_path, DS) . DS;
1204
+			// create classname from module directory name
1205
+			$module = str_replace(' ', '_', ucwords(str_replace('_', ' ', $module)));
1206
+			// add class prefix
1207
+			$module_class = 'EED_' . $module;
1208
+		}
1209
+		// does the module exist ?
1210
+		if (! is_readable($module_path . DS . $module_class . $module_ext)) {
1211
+			$msg = sprintf(
1212
+				__(
1213
+					'The requested %s module file could not be found or is not readable due to file permissions.',
1214
+					'event_espresso'
1215
+				),
1216
+				$module
1217
+			);
1218
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1219
+			return false;
1220
+		}
1221
+		// load the module class file
1222
+		require_once($module_path . $module_class . $module_ext);
1223
+		// verify that class exists
1224
+		if (! class_exists($module_class)) {
1225
+			$msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
1226
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1227
+			return false;
1228
+		}
1229
+		// add to array of registered modules
1230
+		EE_Registry::instance()->modules->{$module_class} = $module_path . $module_class . $module_ext;
1231
+		do_action(
1232
+			'AHEE__EE_Config__register_module__complete',
1233
+			$module_class,
1234
+			EE_Registry::instance()->modules->{$module_class}
1235
+		);
1236
+		return true;
1237
+	}
1238
+
1239
+
1240
+
1241
+	/**
1242
+	 *    _initialize_modules
1243
+	 *    allow modules to set hooks for the rest of the system
1244
+	 *
1245
+	 * @access private
1246
+	 * @return void
1247
+	 */
1248
+	private function _initialize_modules()
1249
+	{
1250
+		// cycle thru shortcode folders
1251
+		foreach (EE_Registry::instance()->modules as $module_class => $module_path) {
1252
+			// fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
1253
+			// which set hooks ?
1254
+			if (is_admin()) {
1255
+				// fire immediately
1256
+				call_user_func(array($module_class, 'set_hooks_admin'));
1257
+			} else {
1258
+				// delay until other systems are online
1259
+				add_action(
1260
+					'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
1261
+					array($module_class, 'set_hooks')
1262
+				);
1263
+			}
1264
+		}
1265
+	}
1266
+
1267
+
1268
+
1269
+	/**
1270
+	 *    register_route - adds module method routes to route_map
1271
+	 *
1272
+	 * @access    public
1273
+	 * @param    string $route       - "pretty" public alias for module method
1274
+	 * @param    string $module      - module name (classname without EED_ prefix)
1275
+	 * @param    string $method_name - the actual module method to be routed to
1276
+	 * @param    string $key         - url param key indicating a route is being called
1277
+	 * @return    bool
1278
+	 */
1279
+	public static function register_route($route = null, $module = null, $method_name = null, $key = 'ee')
1280
+	{
1281
+		do_action('AHEE__EE_Config__register_route__begin', $route, $module, $method_name);
1282
+		$module = str_replace('EED_', '', $module);
1283
+		$module_class = 'EED_' . $module;
1284
+		if (! isset(EE_Registry::instance()->modules->{$module_class})) {
1285
+			$msg = sprintf(__('The module %s has not been registered.', 'event_espresso'), $module);
1286
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1287
+			return false;
1288
+		}
1289
+		if (empty($route)) {
1290
+			$msg = sprintf(__('No route has been supplied.', 'event_espresso'), $route);
1291
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1292
+			return false;
1293
+		}
1294
+		if (! method_exists('EED_' . $module, $method_name)) {
1295
+			$msg = sprintf(
1296
+				__('A valid class method for the %s route has not been supplied.', 'event_espresso'),
1297
+				$route
1298
+			);
1299
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1300
+			return false;
1301
+		}
1302
+		EE_Config::$_module_route_map[$key][$route] = array('EED_' . $module, $method_name);
1303
+		return true;
1304
+	}
1305
+
1306
+
1307
+
1308
+	/**
1309
+	 *    get_route - get module method route
1310
+	 *
1311
+	 * @access    public
1312
+	 * @param    string $route - "pretty" public alias for module method
1313
+	 * @param    string $key   - url param key indicating a route is being called
1314
+	 * @return    string
1315
+	 */
1316
+	public static function get_route($route = null, $key = 'ee')
1317
+	{
1318
+		do_action('AHEE__EE_Config__get_route__begin', $route);
1319
+		$route = (string)apply_filters('FHEE__EE_Config__get_route', $route);
1320
+		if (isset(EE_Config::$_module_route_map[$key][$route])) {
1321
+			return EE_Config::$_module_route_map[$key][$route];
1322
+		}
1323
+		return null;
1324
+	}
1325
+
1326
+
1327
+
1328
+	/**
1329
+	 *    get_routes - get ALL module method routes
1330
+	 *
1331
+	 * @access    public
1332
+	 * @return    array
1333
+	 */
1334
+	public static function get_routes()
1335
+	{
1336
+		return EE_Config::$_module_route_map;
1337
+	}
1338
+
1339
+
1340
+
1341
+	/**
1342
+	 *    register_forward - allows modules to forward request to another module for further processing
1343
+	 *
1344
+	 * @access    public
1345
+	 * @param    string       $route   - "pretty" public alias for module method
1346
+	 * @param    integer      $status  - integer value corresponding  to status constant strings set in module parent
1347
+	 *                                 class, allows different forwards to be served based on status
1348
+	 * @param    array|string $forward - function name or array( class, method )
1349
+	 * @param    string       $key     - url param key indicating a route is being called
1350
+	 * @return    bool
1351
+	 */
1352
+	public static function register_forward($route = null, $status = 0, $forward = null, $key = 'ee')
1353
+	{
1354
+		do_action('AHEE__EE_Config__register_forward', $route, $status, $forward);
1355
+		if (! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1356
+			$msg = sprintf(
1357
+				__('The module route %s for this forward has not been registered.', 'event_espresso'),
1358
+				$route
1359
+			);
1360
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1361
+			return false;
1362
+		}
1363
+		if (empty($forward)) {
1364
+			$msg = sprintf(__('No forwarding route has been supplied.', 'event_espresso'), $route);
1365
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1366
+			return false;
1367
+		}
1368
+		if (is_array($forward)) {
1369
+			if (! isset($forward[1])) {
1370
+				$msg = sprintf(
1371
+					__('A class method for the %s forwarding route has not been supplied.', 'event_espresso'),
1372
+					$route
1373
+				);
1374
+				EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1375
+				return false;
1376
+			}
1377
+			if (! method_exists($forward[0], $forward[1])) {
1378
+				$msg = sprintf(
1379
+					__('The class method %s for the %s forwarding route is in invalid.', 'event_espresso'),
1380
+					$forward[1],
1381
+					$route
1382
+				);
1383
+				EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1384
+				return false;
1385
+			}
1386
+		} else if (! function_exists($forward)) {
1387
+			$msg = sprintf(
1388
+				__('The function %s for the %s forwarding route is in invalid.', 'event_espresso'),
1389
+				$forward,
1390
+				$route
1391
+			);
1392
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1393
+			return false;
1394
+		}
1395
+		EE_Config::$_module_forward_map[$key][$route][absint($status)] = $forward;
1396
+		return true;
1397
+	}
1398
+
1399
+
1400
+
1401
+	/**
1402
+	 *    get_forward - get forwarding route
1403
+	 *
1404
+	 * @access    public
1405
+	 * @param    string  $route  - "pretty" public alias for module method
1406
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1407
+	 *                           allows different forwards to be served based on status
1408
+	 * @param    string  $key    - url param key indicating a route is being called
1409
+	 * @return    string
1410
+	 */
1411
+	public static function get_forward($route = null, $status = 0, $key = 'ee')
1412
+	{
1413
+		do_action('AHEE__EE_Config__get_forward__begin', $route, $status);
1414
+		if (isset(EE_Config::$_module_forward_map[$key][$route][$status])) {
1415
+			return apply_filters(
1416
+				'FHEE__EE_Config__get_forward',
1417
+				EE_Config::$_module_forward_map[$key][$route][$status],
1418
+				$route,
1419
+				$status
1420
+			);
1421
+		}
1422
+		return null;
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 *    register_forward - allows modules to specify different view templates for different method routes and status
1429
+	 *    results
1430
+	 *
1431
+	 * @access    public
1432
+	 * @param    string  $route  - "pretty" public alias for module method
1433
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1434
+	 *                           allows different views to be served based on status
1435
+	 * @param    string  $view
1436
+	 * @param    string  $key    - url param key indicating a route is being called
1437
+	 * @return    bool
1438
+	 */
1439
+	public static function register_view($route = null, $status = 0, $view = null, $key = 'ee')
1440
+	{
1441
+		do_action('AHEE__EE_Config__register_view__begin', $route, $status, $view);
1442
+		if (! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1443
+			$msg = sprintf(
1444
+				__('The module route %s for this view has not been registered.', 'event_espresso'),
1445
+				$route
1446
+			);
1447
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1448
+			return false;
1449
+		}
1450
+		if (! is_readable($view)) {
1451
+			$msg = sprintf(
1452
+				__(
1453
+					'The %s view file could not be found or is not readable due to file permissions.',
1454
+					'event_espresso'
1455
+				),
1456
+				$view
1457
+			);
1458
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1459
+			return false;
1460
+		}
1461
+		EE_Config::$_module_view_map[$key][$route][absint($status)] = $view;
1462
+		return true;
1463
+	}
1464
+
1465
+
1466
+
1467
+	/**
1468
+	 *    get_view - get view for route and status
1469
+	 *
1470
+	 * @access    public
1471
+	 * @param    string  $route  - "pretty" public alias for module method
1472
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1473
+	 *                           allows different views to be served based on status
1474
+	 * @param    string  $key    - url param key indicating a route is being called
1475
+	 * @return    string
1476
+	 */
1477
+	public static function get_view($route = null, $status = 0, $key = 'ee')
1478
+	{
1479
+		do_action('AHEE__EE_Config__get_view__begin', $route, $status);
1480
+		if (isset(EE_Config::$_module_view_map[$key][$route][$status])) {
1481
+			return apply_filters(
1482
+				'FHEE__EE_Config__get_view',
1483
+				EE_Config::$_module_view_map[$key][$route][$status],
1484
+				$route,
1485
+				$status
1486
+			);
1487
+		}
1488
+		return null;
1489
+	}
1490
+
1491
+
1492
+
1493
+	public function update_addon_option_names()
1494
+	{
1495
+		update_option(EE_Config::ADDON_OPTION_NAMES, $this->_addon_option_names);
1496
+	}
1497
+
1498
+
1499
+
1500
+	public function shutdown()
1501
+	{
1502
+		$this->update_addon_option_names();
1503
+	}
1504
+
1505
+
1506
+
1507
+	/**
1508
+	 * @return LegacyShortcodesManager
1509
+	 */
1510
+	public static function getLegacyShortcodesManager()
1511
+	{
1512
+
1513
+		if ( ! EE_Config::instance()->legacy_shortcodes_manager instanceof LegacyShortcodesManager) {
1514
+			EE_Config::instance()->legacy_shortcodes_manager = new LegacyShortcodesManager(
1515
+				EE_Registry::instance()
1516
+			);
1517
+		}
1518
+		return EE_Config::instance()->legacy_shortcodes_manager;
1519
+	}
1520
+
1521
+
1522
+
1523
+	/**
1524
+	 * register_shortcode - makes core aware of this shortcode
1525
+	 *
1526
+	 * @deprecated 4.9.26
1527
+	 * @param    string $shortcode_path - full path up to and including shortcode folder
1528
+	 * @return    bool
1529
+	 */
1530
+	public static function register_shortcode($shortcode_path = null)
1531
+	{
1532
+		EE_Error::doing_it_wrong(
1533
+			__METHOD__,
1534
+			__(
1535
+				'Usage is deprecated. Use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::registerShortcode() as direct replacement, or better yet, please see the new \EventEspresso\core\services\shortcodes\ShortcodesManager class.',
1536
+				'event_espresso'
1537
+			),
1538
+			'4.9.26'
1539
+		);
1540
+		return EE_Config::instance()->getLegacyShortcodesManager()->registerShortcode($shortcode_path);
1541
+	}
21 1542
 
22
-    const LOG_NAME           = 'ee_config_log';
23 1543
 
24
-    const LOG_LENGTH         = 100;
25 1544
 
26
-    const ADDON_OPTION_NAMES = 'ee_config_option_names';
27
-
28
-
29
-    /**
30
-     *    instance of the EE_Config object
31
-     *
32
-     * @var    EE_Config $_instance
33
-     * @access    private
34
-     */
35
-    private static $_instance;
36
-
37
-    /**
38
-     * @var boolean $_logging_enabled
39
-     */
40
-    private static $_logging_enabled = false;
41
-
42
-    /**
43
-     * @var LegacyShortcodesManager $legacy_shortcodes_manager
44
-     */
45
-    private $legacy_shortcodes_manager;
46
-
47
-    /**
48
-     * An StdClass whose property names are addon slugs,
49
-     * and values are their config classes
50
-     *
51
-     * @var StdClass
52
-     */
53
-    public $addons;
54
-
55
-    /**
56
-     * @var EE_Admin_Config
57
-     */
58
-    public $admin;
59
-
60
-    /**
61
-     * @var EE_Core_Config
62
-     */
63
-    public $core;
64
-
65
-    /**
66
-     * @var EE_Currency_Config
67
-     */
68
-    public $currency;
69
-
70
-    /**
71
-     * @var EE_Organization_Config
72
-     */
73
-    public $organization;
74
-
75
-    /**
76
-     * @var EE_Registration_Config
77
-     */
78
-    public $registration;
79
-
80
-    /**
81
-     * @var EE_Template_Config
82
-     */
83
-    public $template_settings;
84
-
85
-    /**
86
-     * Holds EE environment values.
87
-     *
88
-     * @var EE_Environment_Config
89
-     */
90
-    public $environment;
91
-
92
-    /**
93
-     * settings pertaining to Google maps
94
-     *
95
-     * @var EE_Map_Config
96
-     */
97
-    public $map_settings;
98
-
99
-    /**
100
-     * settings pertaining to Taxes
101
-     *
102
-     * @var EE_Tax_Config
103
-     */
104
-    public $tax_settings;
105
-
106
-
107
-    /**
108
-     * Settings pertaining to global messages settings.
109
-     *
110
-     * @var EE_Messages_Config
111
-     */
112
-    public $messages;
113
-
114
-    /**
115
-     * @deprecated
116
-     * @var EE_Gateway_Config
117
-     */
118
-    public $gateway;
119
-
120
-    /**
121
-     * @var    array $_addon_option_names
122
-     * @access    private
123
-     */
124
-    private $_addon_option_names = array();
125
-
126
-    /**
127
-     * @var    array $_module_route_map
128
-     * @access    private
129
-     */
130
-    private static $_module_route_map = array();
131
-
132
-    /**
133
-     * @var    array $_module_forward_map
134
-     * @access    private
135
-     */
136
-    private static $_module_forward_map = array();
137
-
138
-    /**
139
-     * @var    array $_module_view_map
140
-     * @access    private
141
-     */
142
-    private static $_module_view_map = array();
143
-
144
-
145
-
146
-    /**
147
-     * @singleton method used to instantiate class object
148
-     * @access    public
149
-     * @return EE_Config instance
150
-     */
151
-    public static function instance()
152
-    {
153
-        // check if class object is instantiated, and instantiated properly
154
-        if (! self::$_instance instanceof EE_Config) {
155
-            self::$_instance = new self();
156
-        }
157
-        return self::$_instance;
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     * Resets the config
164
-     *
165
-     * @param bool    $hard_reset    if TRUE, sets EE_CONFig back to its original settings in the database. If FALSE
166
-     *                               (default) leaves the database alone, and merely resets the EE_Config object to
167
-     *                               reflect its state in the database
168
-     * @param boolean $reinstantiate if TRUE (default) call instance() and return it. Otherwise, just leave
169
-     *                               $_instance as NULL. Useful in case you want to forget about the old instance on
170
-     *                               EE_Config, but might not be ready to instantiate EE_Config currently (eg if the
171
-     *                               site was put into maintenance mode)
172
-     * @return EE_Config
173
-     */
174
-    public static function reset($hard_reset = false, $reinstantiate = true)
175
-    {
176
-        if (self::$_instance instanceof EE_Config) {
177
-            if ($hard_reset) {
178
-                self::$_instance->legacy_shortcodes_manager = null;
179
-                self::$_instance->_addon_option_names = array();
180
-                self::$_instance->_initialize_config();
181
-                self::$_instance->update_espresso_config();
182
-            }
183
-            self::$_instance->update_addon_option_names();
184
-        }
185
-        self::$_instance = null;
186
-        //we don't need to reset the static properties imo because those should
187
-        //only change when a module is added or removed. Currently we don't
188
-        //support removing a module during a request when it previously existed
189
-        if ($reinstantiate) {
190
-            return self::instance();
191
-        } else {
192
-            return null;
193
-        }
194
-    }
195
-
196
-
197
-
198
-    /**
199
-     *    class constructor
200
-     *
201
-     * @access    private
202
-     */
203
-    private function __construct()
204
-    {
205
-        do_action('AHEE__EE_Config__construct__begin', $this);
206
-        EE_Config::$_logging_enabled = apply_filters('FHEE__EE_Config___construct__logging_enabled', false);
207
-        // setup empty config classes
208
-        $this->_initialize_config();
209
-        // load existing EE site settings
210
-        $this->_load_core_config();
211
-        // confirm everything loaded correctly and set filtered defaults if not
212
-        $this->_verify_config();
213
-        //  register shortcodes and modules
214
-        add_action(
215
-            'AHEE__EE_System__register_shortcodes_modules_and_widgets',
216
-            array($this, 'register_shortcodes_and_modules'),
217
-            999
218
-        );
219
-        //  initialize shortcodes and modules
220
-        add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'initialize_shortcodes_and_modules'));
221
-        // register widgets
222
-        add_action('widgets_init', array($this, 'widgets_init'), 10);
223
-        // shutdown
224
-        add_action('shutdown', array($this, 'shutdown'), 10);
225
-        // construct__end hook
226
-        do_action('AHEE__EE_Config__construct__end', $this);
227
-        // hardcoded hack
228
-        $this->template_settings->current_espresso_theme = 'Espresso_Arabica_2014';
229
-    }
230
-
231
-
232
-
233
-    /**
234
-     * @return boolean
235
-     */
236
-    public static function logging_enabled()
237
-    {
238
-        return self::$_logging_enabled;
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * use to get the current theme if needed from static context
245
-     *
246
-     * @return string current theme set.
247
-     */
248
-    public static function get_current_theme()
249
-    {
250
-        return isset(self::$_instance->template_settings->current_espresso_theme)
251
-            ? self::$_instance->template_settings->current_espresso_theme : 'Espresso_Arabica_2014';
252
-    }
253
-
254
-
255
-
256
-    /**
257
-     *        _initialize_config
258
-     *
259
-     * @access private
260
-     * @return void
261
-     */
262
-    private function _initialize_config()
263
-    {
264
-        EE_Config::trim_log();
265
-        //set defaults
266
-        $this->_addon_option_names = get_option(EE_Config::ADDON_OPTION_NAMES, array());
267
-        $this->addons = new stdClass();
268
-        // set _module_route_map
269
-        EE_Config::$_module_route_map = array();
270
-        // set _module_forward_map
271
-        EE_Config::$_module_forward_map = array();
272
-        // set _module_view_map
273
-        EE_Config::$_module_view_map = array();
274
-    }
275
-
276
-
277
-
278
-    /**
279
-     *        load core plugin configuration
280
-     *
281
-     * @access private
282
-     * @return void
283
-     */
284
-    private function _load_core_config()
285
-    {
286
-        // load_core_config__start hook
287
-        do_action('AHEE__EE_Config___load_core_config__start', $this);
288
-        $espresso_config = $this->get_espresso_config();
289
-        foreach ($espresso_config as $config => $settings) {
290
-            // load_core_config__start hook
291
-            $settings = apply_filters(
292
-                'FHEE__EE_Config___load_core_config__config_settings',
293
-                $settings,
294
-                $config,
295
-                $this
296
-            );
297
-            if (is_object($settings) && property_exists($this, $config)) {
298
-                $this->{$config} = apply_filters('FHEE__EE_Config___load_core_config__' . $config, $settings);
299
-                //call configs populate method to ensure any defaults are set for empty values.
300
-                if (method_exists($settings, 'populate')) {
301
-                    $this->{$config}->populate();
302
-                }
303
-                if (method_exists($settings, 'do_hooks')) {
304
-                    $this->{$config}->do_hooks();
305
-                }
306
-            }
307
-        }
308
-        if (apply_filters('FHEE__EE_Config___load_core_config__update_espresso_config', false)) {
309
-            $this->update_espresso_config();
310
-        }
311
-        // load_core_config__end hook
312
-        do_action('AHEE__EE_Config___load_core_config__end', $this);
313
-    }
314
-
315
-
316
-
317
-    /**
318
-     *    _verify_config
319
-     *
320
-     * @access    protected
321
-     * @return    void
322
-     */
323
-    protected function _verify_config()
324
-    {
325
-        $this->core = $this->core instanceof EE_Core_Config
326
-            ? $this->core
327
-            : new EE_Core_Config();
328
-        $this->core = apply_filters('FHEE__EE_Config___initialize_config__core', $this->core);
329
-        $this->organization = $this->organization instanceof EE_Organization_Config
330
-            ? $this->organization
331
-            : new EE_Organization_Config();
332
-        $this->organization = apply_filters(
333
-            'FHEE__EE_Config___initialize_config__organization',
334
-            $this->organization
335
-        );
336
-        $this->currency = $this->currency instanceof EE_Currency_Config
337
-            ? $this->currency
338
-            : new EE_Currency_Config();
339
-        $this->currency = apply_filters('FHEE__EE_Config___initialize_config__currency', $this->currency);
340
-        $this->registration = $this->registration instanceof EE_Registration_Config
341
-            ? $this->registration
342
-            : new EE_Registration_Config();
343
-        $this->registration = apply_filters(
344
-            'FHEE__EE_Config___initialize_config__registration',
345
-            $this->registration
346
-        );
347
-        $this->admin = $this->admin instanceof EE_Admin_Config
348
-            ? $this->admin
349
-            : new EE_Admin_Config();
350
-        $this->admin = apply_filters('FHEE__EE_Config___initialize_config__admin', $this->admin);
351
-        $this->template_settings = $this->template_settings instanceof EE_Template_Config
352
-            ? $this->template_settings
353
-            : new EE_Template_Config();
354
-        $this->template_settings = apply_filters(
355
-            'FHEE__EE_Config___initialize_config__template_settings',
356
-            $this->template_settings
357
-        );
358
-        $this->map_settings = $this->map_settings instanceof EE_Map_Config
359
-            ? $this->map_settings
360
-            : new EE_Map_Config();
361
-        $this->map_settings = apply_filters('FHEE__EE_Config___initialize_config__map_settings',
362
-            $this->map_settings);
363
-        $this->environment = $this->environment instanceof EE_Environment_Config
364
-            ? $this->environment
365
-            : new EE_Environment_Config();
366
-        $this->environment = apply_filters('FHEE__EE_Config___initialize_config__environment',
367
-            $this->environment);
368
-        $this->tax_settings = $this->tax_settings instanceof EE_Tax_Config
369
-            ? $this->tax_settings
370
-            : new EE_Tax_Config();
371
-        $this->tax_settings = apply_filters('FHEE__EE_Config___initialize_config__tax_settings',
372
-            $this->tax_settings);
373
-        $this->messages = apply_filters('FHEE__EE_Config__initialize_config__messages', $this->messages);
374
-        $this->messages = $this->messages instanceof EE_Messages_Config
375
-            ? $this->messages
376
-            : new EE_Messages_Config();
377
-        $this->gateway = $this->gateway instanceof EE_Gateway_Config
378
-            ? $this->gateway
379
-            : new EE_Gateway_Config();
380
-        $this->gateway = apply_filters('FHEE__EE_Config___initialize_config__gateway', $this->gateway);
381
-        $this->legacy_shortcodes_manager = null;
382
-    }
383
-
384
-
385
-    /**
386
-     *    get_espresso_config
387
-     *
388
-     * @access    public
389
-     * @return    array of espresso config stuff
390
-     */
391
-    public function get_espresso_config()
392
-    {
393
-        // grab espresso configuration
394
-        return apply_filters(
395
-            'FHEE__EE_Config__get_espresso_config__CFG',
396
-            get_option(EE_Config::OPTION_NAME, array())
397
-        );
398
-    }
399
-
400
-
401
-
402
-    /**
403
-     *    double_check_config_comparison
404
-     *
405
-     * @access    public
406
-     * @param string $option
407
-     * @param        $old_value
408
-     * @param        $value
409
-     */
410
-    public function double_check_config_comparison($option = '', $old_value, $value)
411
-    {
412
-        // make sure we're checking the ee config
413
-        if ($option === EE_Config::OPTION_NAME) {
414
-            // run a loose comparison of the old value against the new value for type and properties,
415
-            // but NOT exact instance like WP update_option does (ie: NOT type safe comparison)
416
-            if ($value != $old_value) {
417
-                // if they are NOT the same, then remove the hook,
418
-                // which means the subsequent update results will be based solely on the update query results
419
-                // the reason we do this is because, as stated above,
420
-                // WP update_option performs an exact instance comparison (===) on any update values passed to it
421
-                // this happens PRIOR to serialization and any subsequent update.
422
-                // If values are found to match their previous old value,
423
-                // then WP bails before performing any update.
424
-                // Since we are passing the EE_Config object, it is comparing the EXACT instance of the saved version
425
-                // it just pulled from the db, with the one being passed to it (which will not match).
426
-                // HOWEVER, once the object is serialized and passed off to MySQL to update,
427
-                // MySQL MAY ALSO NOT perform the update because
428
-                // the string it sees in the db looks the same as the new one it has been passed!!!
429
-                // This results in the query returning an "affected rows" value of ZERO,
430
-                // which gets returned immediately by WP update_option and looks like an error.
431
-                remove_action('update_option', array($this, 'check_config_updated'));
432
-            }
433
-        }
434
-    }
435
-
436
-
437
-
438
-    /**
439
-     *    update_espresso_config
440
-     *
441
-     * @access   public
442
-     */
443
-    protected function _reset_espresso_addon_config()
444
-    {
445
-        $this->_addon_option_names = array();
446
-        foreach ($this->addons as $addon_name => $addon_config_obj) {
447
-            $addon_config_obj = maybe_unserialize($addon_config_obj);
448
-            $config_class = get_class($addon_config_obj);
449
-            if ($addon_config_obj instanceof $config_class && ! $addon_config_obj instanceof __PHP_Incomplete_Class) {
450
-                $this->update_config('addons', $addon_name, $addon_config_obj, false);
451
-            }
452
-            $this->addons->{$addon_name} = null;
453
-        }
454
-    }
455
-
456
-
457
-
458
-    /**
459
-     *    update_espresso_config
460
-     *
461
-     * @access   public
462
-     * @param   bool $add_success
463
-     * @param   bool $add_error
464
-     * @return   bool
465
-     */
466
-    public function update_espresso_config($add_success = false, $add_error = true)
467
-    {
468
-        // don't allow config updates during WP heartbeats
469
-        if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
470
-            return false;
471
-        }
472
-        // commented out the following re: https://events.codebasehq.com/projects/event-espresso/tickets/8197
473
-        //$clone = clone( self::$_instance );
474
-        //self::$_instance = NULL;
475
-        do_action('AHEE__EE_Config__update_espresso_config__begin', $this);
476
-        $this->_reset_espresso_addon_config();
477
-        // hook into update_option because that happens AFTER the ( $value === $old_value ) conditional
478
-        // but BEFORE the actual update occurs
479
-        add_action('update_option', array($this, 'double_check_config_comparison'), 1, 3);
480
-        // don't want to persist legacy_shortcodes_manager, but don't want to lose it either
481
-        $legacy_shortcodes_manager = $this->legacy_shortcodes_manager;
482
-        $this->legacy_shortcodes_manager = null;
483
-        // now update "ee_config"
484
-        $saved = update_option(EE_Config::OPTION_NAME, $this);
485
-        $this->legacy_shortcodes_manager = $legacy_shortcodes_manager;
486
-        EE_Config::log(EE_Config::OPTION_NAME);
487
-        // if not saved... check if the hook we just added still exists;
488
-        // if it does, it means one of two things:
489
-        // 		that update_option bailed at the ( $value === $old_value ) conditional,
490
-        //		 or...
491
-        // 		the db update query returned 0 rows affected
492
-        // 		(probably because the data  value was the same from it's perspective)
493
-        // so the existence of the hook means that a negative result from update_option is NOT an error,
494
-        // but just means no update occurred, so don't display an error to the user.
495
-        // BUT... if update_option returns FALSE, AND the hook is missing,
496
-        // then it means that something truly went wrong
497
-        $saved = ! $saved ? has_action('update_option', array($this, 'double_check_config_comparison')) : $saved;
498
-        // remove our action since we don't want it in the system anymore
499
-        remove_action('update_option', array($this, 'double_check_config_comparison'), 1);
500
-        do_action('AHEE__EE_Config__update_espresso_config__end', $this, $saved);
501
-        //self::$_instance = $clone;
502
-        //unset( $clone );
503
-        // if config remains the same or was updated successfully
504
-        if ($saved) {
505
-            if ($add_success) {
506
-                EE_Error::add_success(
507
-                    __('The Event Espresso Configuration Settings have been successfully updated.', 'event_espresso'),
508
-                    __FILE__,
509
-                    __FUNCTION__,
510
-                    __LINE__
511
-                );
512
-            }
513
-            return true;
514
-        } else {
515
-            if ($add_error) {
516
-                EE_Error::add_error(
517
-                    __('The Event Espresso Configuration Settings were not updated.', 'event_espresso'),
518
-                    __FILE__,
519
-                    __FUNCTION__,
520
-                    __LINE__
521
-                );
522
-            }
523
-            return false;
524
-        }
525
-    }
526
-
527
-
528
-
529
-    /**
530
-     *    _verify_config_params
531
-     *
532
-     * @access    private
533
-     * @param    string         $section
534
-     * @param    string         $name
535
-     * @param    string         $config_class
536
-     * @param    EE_Config_Base $config_obj
537
-     * @param    array          $tests_to_run
538
-     * @param    bool           $display_errors
539
-     * @return    bool    TRUE on success, FALSE on fail
540
-     */
541
-    private function _verify_config_params(
542
-        $section = '',
543
-        $name = '',
544
-        $config_class = '',
545
-        $config_obj = null,
546
-        $tests_to_run = array(1, 2, 3, 4, 5, 6, 7, 8),
547
-        $display_errors = true
548
-    ) {
549
-        try {
550
-            foreach ($tests_to_run as $test) {
551
-                switch ($test) {
552
-                    // TEST #1 : check that section was set
553
-                    case 1 :
554
-                        if (empty($section)) {
555
-                            if ($display_errors) {
556
-                                throw new EE_Error(
557
-                                    sprintf(
558
-                                        __(
559
-                                            'No configuration section has been provided while attempting to save "%s".',
560
-                                            'event_espresso'
561
-                                        ),
562
-                                        $config_class
563
-                                    )
564
-                                );
565
-                            }
566
-                            return false;
567
-                        }
568
-                        break;
569
-                    // TEST #2 : check that settings section exists
570
-                    case 2 :
571
-                        if (! isset($this->{$section})) {
572
-                            if ($display_errors) {
573
-                                throw new EE_Error(
574
-                                    sprintf(
575
-                                        __('The "%s" configuration section does not exist.', 'event_espresso'),
576
-                                        $section
577
-                                    )
578
-                                );
579
-                            }
580
-                            return false;
581
-                        }
582
-                        break;
583
-                    // TEST #3 : check that section is the proper format
584
-                    case 3 :
585
-                        if (
586
-                        ! ($this->{$section} instanceof EE_Config_Base || $this->{$section} instanceof stdClass)
587
-                        ) {
588
-                            if ($display_errors) {
589
-                                throw new EE_Error(
590
-                                    sprintf(
591
-                                        __(
592
-                                            'The "%s" configuration settings have not been formatted correctly.',
593
-                                            'event_espresso'
594
-                                        ),
595
-                                        $section
596
-                                    )
597
-                                );
598
-                            }
599
-                            return false;
600
-                        }
601
-                        break;
602
-                    // TEST #4 : check that config section name has been set
603
-                    case 4 :
604
-                        if (empty($name)) {
605
-                            if ($display_errors) {
606
-                                throw new EE_Error(
607
-                                    __(
608
-                                        'No name has been provided for the specific configuration section.',
609
-                                        'event_espresso'
610
-                                    )
611
-                                );
612
-                            }
613
-                            return false;
614
-                        }
615
-                        break;
616
-                    // TEST #5 : check that a config class name has been set
617
-                    case 5 :
618
-                        if (empty($config_class)) {
619
-                            if ($display_errors) {
620
-                                throw new EE_Error(
621
-                                    __(
622
-                                        'No class name has been provided for the specific configuration section.',
623
-                                        'event_espresso'
624
-                                    )
625
-                                );
626
-                            }
627
-                            return false;
628
-                        }
629
-                        break;
630
-                    // TEST #6 : verify config class is accessible
631
-                    case 6 :
632
-                        if (! class_exists($config_class)) {
633
-                            if ($display_errors) {
634
-                                throw new EE_Error(
635
-                                    sprintf(
636
-                                        __(
637
-                                            'The "%s" class does not exist. Please ensure that an autoloader has been set for it.',
638
-                                            'event_espresso'
639
-                                        ),
640
-                                        $config_class
641
-                                    )
642
-                                );
643
-                            }
644
-                            return false;
645
-                        }
646
-                        break;
647
-                    // TEST #7 : check that config has even been set
648
-                    case 7 :
649
-                        if (! isset($this->{$section}->{$name})) {
650
-                            if ($display_errors) {
651
-                                throw new EE_Error(
652
-                                    sprintf(
653
-                                        __('No configuration has been set for "%1$s->%2$s".', 'event_espresso'),
654
-                                        $section,
655
-                                        $name
656
-                                    )
657
-                                );
658
-                            }
659
-                            return false;
660
-                        } else {
661
-                            // and make sure it's not serialized
662
-                            $this->{$section}->{$name} = maybe_unserialize($this->{$section}->{$name});
663
-                        }
664
-                        break;
665
-                    // TEST #8 : check that config is the requested type
666
-                    case 8 :
667
-                        if (! $this->{$section}->{$name} instanceof $config_class) {
668
-                            if ($display_errors) {
669
-                                throw new EE_Error(
670
-                                    sprintf(
671
-                                        __(
672
-                                            'The configuration for "%1$s->%2$s" is not of the "%3$s" class.',
673
-                                            'event_espresso'
674
-                                        ),
675
-                                        $section,
676
-                                        $name,
677
-                                        $config_class
678
-                                    )
679
-                                );
680
-                            }
681
-                            return false;
682
-                        }
683
-                        break;
684
-                    // TEST #9 : verify config object
685
-                    case 9 :
686
-                        if (! $config_obj instanceof EE_Config_Base) {
687
-                            if ($display_errors) {
688
-                                throw new EE_Error(
689
-                                    sprintf(
690
-                                        __('The "%s" class is not an instance of EE_Config_Base.', 'event_espresso'),
691
-                                        print_r($config_obj, true)
692
-                                    )
693
-                                );
694
-                            }
695
-                            return false;
696
-                        }
697
-                        break;
698
-                }
699
-            }
700
-        } catch (EE_Error $e) {
701
-            $e->get_error();
702
-        }
703
-        // you have successfully run the gauntlet
704
-        return true;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     *    _generate_config_option_name
711
-     *
712
-     * @access        protected
713
-     * @param        string $section
714
-     * @param        string $name
715
-     * @return        string
716
-     */
717
-    private function _generate_config_option_name($section = '', $name = '')
718
-    {
719
-        return 'ee_config-' . strtolower($section . '-' . str_replace(array('EE_', 'EED_'), '', $name));
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     *    _set_config_class
726
-     * ensures that a config class is set, either from a passed config class or one generated from the config name
727
-     *
728
-     * @access    private
729
-     * @param    string $config_class
730
-     * @param    string $name
731
-     * @return    string
732
-     */
733
-    private function _set_config_class($config_class = '', $name = '')
734
-    {
735
-        return ! empty($config_class)
736
-            ? $config_class
737
-            : str_replace(' ', '_', ucwords(str_replace('_', ' ', $name))) . '_Config';
738
-    }
739
-
740
-
741
-
742
-    /**
743
-     *    set_config
744
-     *
745
-     * @access    protected
746
-     * @param    string         $section
747
-     * @param    string         $name
748
-     * @param    string         $config_class
749
-     * @param    EE_Config_Base $config_obj
750
-     * @return    EE_Config_Base
751
-     */
752
-    public function set_config($section = '', $name = '', $config_class = '', EE_Config_Base $config_obj = null)
753
-    {
754
-        // ensure config class is set to something
755
-        $config_class = $this->_set_config_class($config_class, $name);
756
-        // run tests 1-4, 6, and 7 to verify all config params are set and valid
757
-        if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
758
-            return null;
759
-        }
760
-        $config_option_name = $this->_generate_config_option_name($section, $name);
761
-        // if the config option name hasn't been added yet to the list of option names we're tracking, then do so now
762
-        if (! isset($this->_addon_option_names[$config_option_name])) {
763
-            $this->_addon_option_names[$config_option_name] = $config_class;
764
-            $this->update_addon_option_names();
765
-        }
766
-        // verify the incoming config object but suppress errors
767
-        if (! $this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
768
-            $config_obj = new $config_class();
769
-        }
770
-        if (get_option($config_option_name)) {
771
-            EE_Config::log($config_option_name);
772
-            update_option($config_option_name, $config_obj);
773
-            $this->{$section}->{$name} = $config_obj;
774
-            return $this->{$section}->{$name};
775
-        } else {
776
-            // create a wp-option for this config
777
-            if (add_option($config_option_name, $config_obj, '', 'no')) {
778
-                $this->{$section}->{$name} = maybe_unserialize($config_obj);
779
-                return $this->{$section}->{$name};
780
-            } else {
781
-                EE_Error::add_error(
782
-                    sprintf(__('The "%s" could not be saved to the database.', 'event_espresso'), $config_class),
783
-                    __FILE__,
784
-                    __FUNCTION__,
785
-                    __LINE__
786
-                );
787
-                return null;
788
-            }
789
-        }
790
-    }
791
-
792
-
793
-
794
-    /**
795
-     *    update_config
796
-     * Important: the config object must ALREADY be set, otherwise this will produce an error.
797
-     *
798
-     * @access    public
799
-     * @param    string                $section
800
-     * @param    string                $name
801
-     * @param    EE_Config_Base|string $config_obj
802
-     * @param    bool                  $throw_errors
803
-     * @return    bool
804
-     */
805
-    public function update_config($section = '', $name = '', $config_obj = '', $throw_errors = true)
806
-    {
807
-        // don't allow config updates during WP heartbeats
808
-        if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
809
-            return false;
810
-        }
811
-        $config_obj = maybe_unserialize($config_obj);
812
-        // get class name of the incoming object
813
-        $config_class = get_class($config_obj);
814
-        // run tests 1-5 and 9 to verify config
815
-        if (! $this->_verify_config_params(
816
-            $section,
817
-            $name,
818
-            $config_class,
819
-            $config_obj,
820
-            array(1, 2, 3, 4, 7, 9)
821
-        )
822
-        ) {
823
-            return false;
824
-        }
825
-        $config_option_name = $this->_generate_config_option_name($section, $name);
826
-        // check if config object has been added to db by seeing if config option name is in $this->_addon_option_names array
827
-        if (! isset($this->_addon_option_names[$config_option_name])) {
828
-            // save new config to db
829
-            if ($this->set_config($section, $name, $config_class, $config_obj)) {
830
-                return true;
831
-            }
832
-        } else {
833
-            // first check if the record already exists
834
-            $existing_config = get_option($config_option_name);
835
-            $config_obj = serialize($config_obj);
836
-            // just return if db record is already up to date (NOT type safe comparison)
837
-            if ($existing_config == $config_obj) {
838
-                $this->{$section}->{$name} = $config_obj;
839
-                return true;
840
-            } else if (update_option($config_option_name, $config_obj)) {
841
-                EE_Config::log($config_option_name);
842
-                // update wp-option for this config class
843
-                $this->{$section}->{$name} = $config_obj;
844
-                return true;
845
-            } elseif ($throw_errors) {
846
-                EE_Error::add_error(
847
-                    sprintf(
848
-                        __(
849
-                            'The "%1$s" object stored at"%2$s" was not successfully updated in the database.',
850
-                            'event_espresso'
851
-                        ),
852
-                        $config_class,
853
-                        'EE_Config->' . $section . '->' . $name
854
-                    ),
855
-                    __FILE__,
856
-                    __FUNCTION__,
857
-                    __LINE__
858
-                );
859
-            }
860
-        }
861
-        return false;
862
-    }
863
-
864
-
865
-
866
-    /**
867
-     *    get_config
868
-     *
869
-     * @access    public
870
-     * @param    string $section
871
-     * @param    string $name
872
-     * @param    string $config_class
873
-     * @return    mixed EE_Config_Base | NULL
874
-     */
875
-    public function get_config($section = '', $name = '', $config_class = '')
876
-    {
877
-        // ensure config class is set to something
878
-        $config_class = $this->_set_config_class($config_class, $name);
879
-        // run tests 1-4, 6 and 7 to verify that all params have been set
880
-        if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
881
-            return null;
882
-        }
883
-        // now test if the requested config object exists, but suppress errors
884
-        if ($this->_verify_config_params($section, $name, $config_class, null, array(7, 8), false)) {
885
-            // config already exists, so pass it back
886
-            return $this->{$section}->{$name};
887
-        }
888
-        // load config option from db if it exists
889
-        $config_obj = $this->get_config_option($this->_generate_config_option_name($section, $name));
890
-        // verify the newly retrieved config object, but suppress errors
891
-        if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
892
-            // config is good, so set it and pass it back
893
-            $this->{$section}->{$name} = $config_obj;
894
-            return $this->{$section}->{$name};
895
-        }
896
-        // oops! $config_obj is not already set and does not exist in the db, so create a new one
897
-        $config_obj = $this->set_config($section, $name, $config_class);
898
-        // verify the newly created config object
899
-        if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9))) {
900
-            return $this->{$section}->{$name};
901
-        } else {
902
-            EE_Error::add_error(
903
-                sprintf(__('The "%s" could not be retrieved from the database.', 'event_espresso'), $config_class),
904
-                __FILE__,
905
-                __FUNCTION__,
906
-                __LINE__
907
-            );
908
-        }
909
-        return null;
910
-    }
911
-
912
-
913
-
914
-    /**
915
-     *    get_config_option
916
-     *
917
-     * @access    public
918
-     * @param    string $config_option_name
919
-     * @return    mixed EE_Config_Base | FALSE
920
-     */
921
-    public function get_config_option($config_option_name = '')
922
-    {
923
-        // retrieve the wp-option for this config class.
924
-        $config_option = maybe_unserialize(get_option($config_option_name, array()));
925
-        if (empty($config_option)) {
926
-            EE_Config::log($config_option_name . '-NOT-FOUND');
927
-        }
928
-        return $config_option;
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * log
935
-     *
936
-     * @param string $config_option_name
937
-     */
938
-    public static function log($config_option_name = '')
939
-    {
940
-        if (EE_Config::logging_enabled() && ! empty($config_option_name)) {
941
-            $config_log = get_option(EE_Config::LOG_NAME, array());
942
-            //copy incoming $_REQUEST and sanitize it so we can save it
943
-            $_request = $_REQUEST;
944
-            array_walk_recursive($_request, 'sanitize_text_field');
945
-            $config_log[(string)microtime(true)] = array(
946
-                'config_name' => $config_option_name,
947
-                'request'     => $_request,
948
-            );
949
-            update_option(EE_Config::LOG_NAME, $config_log);
950
-        }
951
-    }
952
-
953
-
954
-
955
-    /**
956
-     * trim_log
957
-     * reduces the size of the config log to the length specified by EE_Config::LOG_LENGTH
958
-     */
959
-    public static function trim_log()
960
-    {
961
-        if (! EE_Config::logging_enabled()) {
962
-            return;
963
-        }
964
-        $config_log = maybe_unserialize(get_option(EE_Config::LOG_NAME, array()));
965
-        $log_length = count($config_log);
966
-        if ($log_length > EE_Config::LOG_LENGTH) {
967
-            ksort($config_log);
968
-            $config_log = array_slice($config_log, $log_length - EE_Config::LOG_LENGTH, null, true);
969
-            update_option(EE_Config::LOG_NAME, $config_log);
970
-        }
971
-    }
972
-
973
-
974
-
975
-    /**
976
-     *    get_page_for_posts
977
-     *    if the wp-option "show_on_front" is set to "page", then this is the post_name for the post set in the
978
-     *    wp-option "page_for_posts", or "posts" if no page is selected
979
-     *
980
-     * @access    public
981
-     * @return    string
982
-     */
983
-    public static function get_page_for_posts()
984
-    {
985
-        $page_for_posts = get_option('page_for_posts');
986
-        if (! $page_for_posts) {
987
-            return 'posts';
988
-        }
989
-        /** @type WPDB $wpdb */
990
-        global $wpdb;
991
-        $SQL = "SELECT post_name from $wpdb->posts WHERE post_type='posts' OR post_type='page' AND post_status='publish' AND ID=%d";
992
-        return $wpdb->get_var($wpdb->prepare($SQL, $page_for_posts));
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     *    register_shortcodes_and_modules.
999
-     *    At this point, it's too early to tell if we're maintenance mode or not.
1000
-     *    In fact, this is where we give modules a chance to let core know they exist
1001
-     *    so they can help trigger maintenance mode if it's needed
1002
-     *
1003
-     * @access    public
1004
-     * @return    void
1005
-     */
1006
-    public function register_shortcodes_and_modules()
1007
-    {
1008
-        // allow modules to set hooks for the rest of the system
1009
-        EE_Registry::instance()->modules = $this->_register_modules();
1010
-    }
1011
-
1012
-
1013
-
1014
-    /**
1015
-     *    initialize_shortcodes_and_modules
1016
-     *    meaning they can start adding their hooks to get stuff done
1017
-     *
1018
-     * @access    public
1019
-     * @return    void
1020
-     */
1021
-    public function initialize_shortcodes_and_modules()
1022
-    {
1023
-        // allow modules to set hooks for the rest of the system
1024
-        $this->_initialize_modules();
1025
-    }
1026
-
1027
-
1028
-
1029
-    /**
1030
-     *    widgets_init
1031
-     *
1032
-     * @access private
1033
-     * @return void
1034
-     */
1035
-    public function widgets_init()
1036
-    {
1037
-        //only init widgets on admin pages when not in complete maintenance, and
1038
-        //on frontend when not in any maintenance mode
1039
-        if (
1040
-            ! EE_Maintenance_Mode::instance()->level()
1041
-            || (
1042
-                is_admin()
1043
-                && EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
1044
-            )
1045
-        ) {
1046
-            // grab list of installed widgets
1047
-            $widgets_to_register = glob(EE_WIDGETS . '*', GLOB_ONLYDIR);
1048
-            // filter list of modules to register
1049
-            $widgets_to_register = apply_filters(
1050
-                'FHEE__EE_Config__register_widgets__widgets_to_register',
1051
-                $widgets_to_register
1052
-            );
1053
-            if (! empty($widgets_to_register)) {
1054
-                // cycle thru widget folders
1055
-                foreach ($widgets_to_register as $widget_path) {
1056
-                    // add to list of installed widget modules
1057
-                    EE_Config::register_ee_widget($widget_path);
1058
-                }
1059
-            }
1060
-            // filter list of installed modules
1061
-            EE_Registry::instance()->widgets = apply_filters(
1062
-                'FHEE__EE_Config__register_widgets__installed_widgets',
1063
-                EE_Registry::instance()->widgets
1064
-            );
1065
-        }
1066
-    }
1067
-
1068
-
1069
-
1070
-    /**
1071
-     *    register_ee_widget - makes core aware of this widget
1072
-     *
1073
-     * @access    public
1074
-     * @param    string $widget_path - full path up to and including widget folder
1075
-     * @return    void
1076
-     */
1077
-    public static function register_ee_widget($widget_path = null)
1078
-    {
1079
-        do_action('AHEE__EE_Config__register_widget__begin', $widget_path);
1080
-        $widget_ext = '.widget.php';
1081
-        // make all separators match
1082
-        $widget_path = rtrim(str_replace('/\\', DS, $widget_path), DS);
1083
-        // does the file path INCLUDE the actual file name as part of the path ?
1084
-        if (strpos($widget_path, $widget_ext) !== false) {
1085
-            // grab and shortcode file name from directory name and break apart at dots
1086
-            $file_name = explode('.', basename($widget_path));
1087
-            // take first segment from file name pieces and remove class prefix if it exists
1088
-            $widget = strpos($file_name[0], 'EEW_') === 0 ? substr($file_name[0], 4) : $file_name[0];
1089
-            // sanitize shortcode directory name
1090
-            $widget = sanitize_key($widget);
1091
-            // now we need to rebuild the shortcode path
1092
-            $widget_path = explode(DS, $widget_path);
1093
-            // remove last segment
1094
-            array_pop($widget_path);
1095
-            // glue it back together
1096
-            $widget_path = implode(DS, $widget_path);
1097
-        } else {
1098
-            // grab and sanitize widget directory name
1099
-            $widget = sanitize_key(basename($widget_path));
1100
-        }
1101
-        // create classname from widget directory name
1102
-        $widget = str_replace(' ', '_', ucwords(str_replace('_', ' ', $widget)));
1103
-        // add class prefix
1104
-        $widget_class = 'EEW_' . $widget;
1105
-        // does the widget exist ?
1106
-        if (! is_readable($widget_path . DS . $widget_class . $widget_ext)) {
1107
-            $msg = sprintf(
1108
-                __(
1109
-                    'The requested %s widget file could not be found or is not readable due to file permissions. Please ensure the following path is correct: %s',
1110
-                    'event_espresso'
1111
-                ),
1112
-                $widget_class,
1113
-                $widget_path . DS . $widget_class . $widget_ext
1114
-            );
1115
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1116
-            return;
1117
-        }
1118
-        // load the widget class file
1119
-        require_once($widget_path . DS . $widget_class . $widget_ext);
1120
-        // verify that class exists
1121
-        if (! class_exists($widget_class)) {
1122
-            $msg = sprintf(__('The requested %s widget class does not exist.', 'event_espresso'), $widget_class);
1123
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1124
-            return;
1125
-        }
1126
-        register_widget($widget_class);
1127
-        // add to array of registered widgets
1128
-        EE_Registry::instance()->widgets->{$widget_class} = $widget_path . DS . $widget_class . $widget_ext;
1129
-    }
1130
-
1131
-
1132
-
1133
-    /**
1134
-     *        _register_modules
1135
-     *
1136
-     * @access private
1137
-     * @return array
1138
-     */
1139
-    private function _register_modules()
1140
-    {
1141
-        // grab list of installed modules
1142
-        $modules_to_register = glob(EE_MODULES . '*', GLOB_ONLYDIR);
1143
-        // filter list of modules to register
1144
-        $modules_to_register = apply_filters(
1145
-            'FHEE__EE_Config__register_modules__modules_to_register',
1146
-            $modules_to_register
1147
-        );
1148
-        if (! empty($modules_to_register)) {
1149
-            // loop through folders
1150
-            foreach ($modules_to_register as $module_path) {
1151
-                /**TEMPORARILY EXCLUDE gateways from modules for time being**/
1152
-                if (
1153
-                    $module_path !== EE_MODULES . 'zzz-copy-this-module-template'
1154
-                    && $module_path !== EE_MODULES . 'gateways'
1155
-                ) {
1156
-                    // add to list of installed modules
1157
-                    EE_Config::register_module($module_path);
1158
-                }
1159
-            }
1160
-        }
1161
-        // filter list of installed modules
1162
-        return apply_filters(
1163
-            'FHEE__EE_Config___register_modules__installed_modules',
1164
-            EE_Registry::instance()->modules
1165
-        );
1166
-    }
1167
-
1168
-
1169
-
1170
-    /**
1171
-     *    register_module - makes core aware of this module
1172
-     *
1173
-     * @access    public
1174
-     * @param    string $module_path - full path up to and including module folder
1175
-     * @return    bool
1176
-     */
1177
-    public static function register_module($module_path = null)
1178
-    {
1179
-        do_action('AHEE__EE_Config__register_module__begin', $module_path);
1180
-        $module_ext = '.module.php';
1181
-        // make all separators match
1182
-        $module_path = str_replace(array('\\', '/'), DS, $module_path);
1183
-        // does the file path INCLUDE the actual file name as part of the path ?
1184
-        if (strpos($module_path, $module_ext) !== false) {
1185
-            // grab and shortcode file name from directory name and break apart at dots
1186
-            $module_file = explode('.', basename($module_path));
1187
-            // now we need to rebuild the shortcode path
1188
-            $module_path = explode(DS, $module_path);
1189
-            // remove last segment
1190
-            array_pop($module_path);
1191
-            // glue it back together
1192
-            $module_path = implode(DS, $module_path) . DS;
1193
-            // take first segment from file name pieces and sanitize it
1194
-            $module = preg_replace('/[^a-zA-Z0-9_\-]/', '', $module_file[0]);
1195
-            // ensure class prefix is added
1196
-            $module_class = strpos($module, 'EED_') !== 0 ? 'EED_' . $module : $module;
1197
-        } else {
1198
-            // we need to generate the filename based off of the folder name
1199
-            // grab and sanitize module name
1200
-            $module = strtolower(basename($module_path));
1201
-            $module = preg_replace('/[^a-z0-9_\-]/', '', $module);
1202
-            // like trailingslashit()
1203
-            $module_path = rtrim($module_path, DS) . DS;
1204
-            // create classname from module directory name
1205
-            $module = str_replace(' ', '_', ucwords(str_replace('_', ' ', $module)));
1206
-            // add class prefix
1207
-            $module_class = 'EED_' . $module;
1208
-        }
1209
-        // does the module exist ?
1210
-        if (! is_readable($module_path . DS . $module_class . $module_ext)) {
1211
-            $msg = sprintf(
1212
-                __(
1213
-                    'The requested %s module file could not be found or is not readable due to file permissions.',
1214
-                    'event_espresso'
1215
-                ),
1216
-                $module
1217
-            );
1218
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1219
-            return false;
1220
-        }
1221
-        // load the module class file
1222
-        require_once($module_path . $module_class . $module_ext);
1223
-        // verify that class exists
1224
-        if (! class_exists($module_class)) {
1225
-            $msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
1226
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1227
-            return false;
1228
-        }
1229
-        // add to array of registered modules
1230
-        EE_Registry::instance()->modules->{$module_class} = $module_path . $module_class . $module_ext;
1231
-        do_action(
1232
-            'AHEE__EE_Config__register_module__complete',
1233
-            $module_class,
1234
-            EE_Registry::instance()->modules->{$module_class}
1235
-        );
1236
-        return true;
1237
-    }
1238
-
1239
-
1240
-
1241
-    /**
1242
-     *    _initialize_modules
1243
-     *    allow modules to set hooks for the rest of the system
1244
-     *
1245
-     * @access private
1246
-     * @return void
1247
-     */
1248
-    private function _initialize_modules()
1249
-    {
1250
-        // cycle thru shortcode folders
1251
-        foreach (EE_Registry::instance()->modules as $module_class => $module_path) {
1252
-            // fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
1253
-            // which set hooks ?
1254
-            if (is_admin()) {
1255
-                // fire immediately
1256
-                call_user_func(array($module_class, 'set_hooks_admin'));
1257
-            } else {
1258
-                // delay until other systems are online
1259
-                add_action(
1260
-                    'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
1261
-                    array($module_class, 'set_hooks')
1262
-                );
1263
-            }
1264
-        }
1265
-    }
1266
-
1267
-
1268
-
1269
-    /**
1270
-     *    register_route - adds module method routes to route_map
1271
-     *
1272
-     * @access    public
1273
-     * @param    string $route       - "pretty" public alias for module method
1274
-     * @param    string $module      - module name (classname without EED_ prefix)
1275
-     * @param    string $method_name - the actual module method to be routed to
1276
-     * @param    string $key         - url param key indicating a route is being called
1277
-     * @return    bool
1278
-     */
1279
-    public static function register_route($route = null, $module = null, $method_name = null, $key = 'ee')
1280
-    {
1281
-        do_action('AHEE__EE_Config__register_route__begin', $route, $module, $method_name);
1282
-        $module = str_replace('EED_', '', $module);
1283
-        $module_class = 'EED_' . $module;
1284
-        if (! isset(EE_Registry::instance()->modules->{$module_class})) {
1285
-            $msg = sprintf(__('The module %s has not been registered.', 'event_espresso'), $module);
1286
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1287
-            return false;
1288
-        }
1289
-        if (empty($route)) {
1290
-            $msg = sprintf(__('No route has been supplied.', 'event_espresso'), $route);
1291
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1292
-            return false;
1293
-        }
1294
-        if (! method_exists('EED_' . $module, $method_name)) {
1295
-            $msg = sprintf(
1296
-                __('A valid class method for the %s route has not been supplied.', 'event_espresso'),
1297
-                $route
1298
-            );
1299
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1300
-            return false;
1301
-        }
1302
-        EE_Config::$_module_route_map[$key][$route] = array('EED_' . $module, $method_name);
1303
-        return true;
1304
-    }
1305
-
1306
-
1307
-
1308
-    /**
1309
-     *    get_route - get module method route
1310
-     *
1311
-     * @access    public
1312
-     * @param    string $route - "pretty" public alias for module method
1313
-     * @param    string $key   - url param key indicating a route is being called
1314
-     * @return    string
1315
-     */
1316
-    public static function get_route($route = null, $key = 'ee')
1317
-    {
1318
-        do_action('AHEE__EE_Config__get_route__begin', $route);
1319
-        $route = (string)apply_filters('FHEE__EE_Config__get_route', $route);
1320
-        if (isset(EE_Config::$_module_route_map[$key][$route])) {
1321
-            return EE_Config::$_module_route_map[$key][$route];
1322
-        }
1323
-        return null;
1324
-    }
1325
-
1326
-
1327
-
1328
-    /**
1329
-     *    get_routes - get ALL module method routes
1330
-     *
1331
-     * @access    public
1332
-     * @return    array
1333
-     */
1334
-    public static function get_routes()
1335
-    {
1336
-        return EE_Config::$_module_route_map;
1337
-    }
1338
-
1339
-
1340
-
1341
-    /**
1342
-     *    register_forward - allows modules to forward request to another module for further processing
1343
-     *
1344
-     * @access    public
1345
-     * @param    string       $route   - "pretty" public alias for module method
1346
-     * @param    integer      $status  - integer value corresponding  to status constant strings set in module parent
1347
-     *                                 class, allows different forwards to be served based on status
1348
-     * @param    array|string $forward - function name or array( class, method )
1349
-     * @param    string       $key     - url param key indicating a route is being called
1350
-     * @return    bool
1351
-     */
1352
-    public static function register_forward($route = null, $status = 0, $forward = null, $key = 'ee')
1353
-    {
1354
-        do_action('AHEE__EE_Config__register_forward', $route, $status, $forward);
1355
-        if (! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1356
-            $msg = sprintf(
1357
-                __('The module route %s for this forward has not been registered.', 'event_espresso'),
1358
-                $route
1359
-            );
1360
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1361
-            return false;
1362
-        }
1363
-        if (empty($forward)) {
1364
-            $msg = sprintf(__('No forwarding route has been supplied.', 'event_espresso'), $route);
1365
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1366
-            return false;
1367
-        }
1368
-        if (is_array($forward)) {
1369
-            if (! isset($forward[1])) {
1370
-                $msg = sprintf(
1371
-                    __('A class method for the %s forwarding route has not been supplied.', 'event_espresso'),
1372
-                    $route
1373
-                );
1374
-                EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1375
-                return false;
1376
-            }
1377
-            if (! method_exists($forward[0], $forward[1])) {
1378
-                $msg = sprintf(
1379
-                    __('The class method %s for the %s forwarding route is in invalid.', 'event_espresso'),
1380
-                    $forward[1],
1381
-                    $route
1382
-                );
1383
-                EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1384
-                return false;
1385
-            }
1386
-        } else if (! function_exists($forward)) {
1387
-            $msg = sprintf(
1388
-                __('The function %s for the %s forwarding route is in invalid.', 'event_espresso'),
1389
-                $forward,
1390
-                $route
1391
-            );
1392
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1393
-            return false;
1394
-        }
1395
-        EE_Config::$_module_forward_map[$key][$route][absint($status)] = $forward;
1396
-        return true;
1397
-    }
1398
-
1399
-
1400
-
1401
-    /**
1402
-     *    get_forward - get forwarding route
1403
-     *
1404
-     * @access    public
1405
-     * @param    string  $route  - "pretty" public alias for module method
1406
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1407
-     *                           allows different forwards to be served based on status
1408
-     * @param    string  $key    - url param key indicating a route is being called
1409
-     * @return    string
1410
-     */
1411
-    public static function get_forward($route = null, $status = 0, $key = 'ee')
1412
-    {
1413
-        do_action('AHEE__EE_Config__get_forward__begin', $route, $status);
1414
-        if (isset(EE_Config::$_module_forward_map[$key][$route][$status])) {
1415
-            return apply_filters(
1416
-                'FHEE__EE_Config__get_forward',
1417
-                EE_Config::$_module_forward_map[$key][$route][$status],
1418
-                $route,
1419
-                $status
1420
-            );
1421
-        }
1422
-        return null;
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     *    register_forward - allows modules to specify different view templates for different method routes and status
1429
-     *    results
1430
-     *
1431
-     * @access    public
1432
-     * @param    string  $route  - "pretty" public alias for module method
1433
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1434
-     *                           allows different views to be served based on status
1435
-     * @param    string  $view
1436
-     * @param    string  $key    - url param key indicating a route is being called
1437
-     * @return    bool
1438
-     */
1439
-    public static function register_view($route = null, $status = 0, $view = null, $key = 'ee')
1440
-    {
1441
-        do_action('AHEE__EE_Config__register_view__begin', $route, $status, $view);
1442
-        if (! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1443
-            $msg = sprintf(
1444
-                __('The module route %s for this view has not been registered.', 'event_espresso'),
1445
-                $route
1446
-            );
1447
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1448
-            return false;
1449
-        }
1450
-        if (! is_readable($view)) {
1451
-            $msg = sprintf(
1452
-                __(
1453
-                    'The %s view file could not be found or is not readable due to file permissions.',
1454
-                    'event_espresso'
1455
-                ),
1456
-                $view
1457
-            );
1458
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1459
-            return false;
1460
-        }
1461
-        EE_Config::$_module_view_map[$key][$route][absint($status)] = $view;
1462
-        return true;
1463
-    }
1464
-
1465
-
1466
-
1467
-    /**
1468
-     *    get_view - get view for route and status
1469
-     *
1470
-     * @access    public
1471
-     * @param    string  $route  - "pretty" public alias for module method
1472
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1473
-     *                           allows different views to be served based on status
1474
-     * @param    string  $key    - url param key indicating a route is being called
1475
-     * @return    string
1476
-     */
1477
-    public static function get_view($route = null, $status = 0, $key = 'ee')
1478
-    {
1479
-        do_action('AHEE__EE_Config__get_view__begin', $route, $status);
1480
-        if (isset(EE_Config::$_module_view_map[$key][$route][$status])) {
1481
-            return apply_filters(
1482
-                'FHEE__EE_Config__get_view',
1483
-                EE_Config::$_module_view_map[$key][$route][$status],
1484
-                $route,
1485
-                $status
1486
-            );
1487
-        }
1488
-        return null;
1489
-    }
1490
-
1491
-
1492
-
1493
-    public function update_addon_option_names()
1494
-    {
1495
-        update_option(EE_Config::ADDON_OPTION_NAMES, $this->_addon_option_names);
1496
-    }
1497
-
1498
-
1499
-
1500
-    public function shutdown()
1501
-    {
1502
-        $this->update_addon_option_names();
1503
-    }
1504
-
1505
-
1506
-
1507
-    /**
1508
-     * @return LegacyShortcodesManager
1509
-     */
1510
-    public static function getLegacyShortcodesManager()
1511
-    {
1512
-
1513
-        if ( ! EE_Config::instance()->legacy_shortcodes_manager instanceof LegacyShortcodesManager) {
1514
-            EE_Config::instance()->legacy_shortcodes_manager = new LegacyShortcodesManager(
1515
-                EE_Registry::instance()
1516
-            );
1517
-        }
1518
-        return EE_Config::instance()->legacy_shortcodes_manager;
1519
-    }
1520
-
1521
-
1522
-
1523
-    /**
1524
-     * register_shortcode - makes core aware of this shortcode
1525
-     *
1526
-     * @deprecated 4.9.26
1527
-     * @param    string $shortcode_path - full path up to and including shortcode folder
1528
-     * @return    bool
1529
-     */
1530
-    public static function register_shortcode($shortcode_path = null)
1531
-    {
1532
-        EE_Error::doing_it_wrong(
1533
-            __METHOD__,
1534
-            __(
1535
-                'Usage is deprecated. Use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::registerShortcode() as direct replacement, or better yet, please see the new \EventEspresso\core\services\shortcodes\ShortcodesManager class.',
1536
-                'event_espresso'
1537
-            ),
1538
-            '4.9.26'
1539
-        );
1540
-        return EE_Config::instance()->getLegacyShortcodesManager()->registerShortcode($shortcode_path);
1541
-    }
1542
-
1543
-
1544
-
1545
-}
1546
-
1547
-
1548
-
1549
-/**
1550
- * Base class used for config classes. These classes should generally not have
1551
- * magic functions in use, except we'll allow them to magically set and get stuff...
1552
- * basically, they should just be well-defined stdClasses
1553
- */
1554
-class EE_Config_Base
1555
-{
1556
-
1557
-    /**
1558
-     * Utility function for escaping the value of a property and returning.
1559
-     *
1560
-     * @param string $property property name (checks to see if exists).
1561
-     * @return mixed if a detected type found return the escaped value, otherwise just the raw value is returned.
1562
-     * @throws \EE_Error
1563
-     */
1564
-    public function get_pretty($property)
1565
-    {
1566
-        if (! property_exists($this, $property)) {
1567
-            throw new EE_Error(
1568
-                sprintf(
1569
-                    __(
1570
-                        '%1$s::get_pretty() has been called with the property %2$s which does not exist on the %1$s config class.',
1571
-                        'event_espresso'
1572
-                    ),
1573
-                    get_class($this),
1574
-                    $property
1575
-                )
1576
-            );
1577
-        }
1578
-        //just handling escaping of strings for now.
1579
-        if (is_string($this->{$property})) {
1580
-            return stripslashes($this->{$property});
1581
-        }
1582
-        return $this->{$property};
1583
-    }
1584
-
1585
-
1586
-
1587
-    public function populate()
1588
-    {
1589
-        //grab defaults via a new instance of this class.
1590
-        $class_name = get_class($this);
1591
-        $defaults = new $class_name;
1592
-        //loop through the properties for this class and see if they are set.  If they are NOT, then grab the
1593
-        //default from our $defaults object.
1594
-        foreach (get_object_vars($defaults) as $property => $value) {
1595
-            if ($this->{$property} === null) {
1596
-                $this->{$property} = $value;
1597
-            }
1598
-        }
1599
-        //cleanup
1600
-        unset($defaults);
1601
-    }
1602
-
1603
-
1604
-
1605
-    /**
1606
-     *        __isset
1607
-     *
1608
-     * @param $a
1609
-     * @return bool
1610
-     */
1611
-    public function __isset($a)
1612
-    {
1613
-        return false;
1614
-    }
1615
-
1616
-
1617
-
1618
-    /**
1619
-     *        __unset
1620
-     *
1621
-     * @param $a
1622
-     * @return bool
1623
-     */
1624
-    public function __unset($a)
1625
-    {
1626
-        return false;
1627
-    }
1628
-
1629
-
1630
-
1631
-    /**
1632
-     *        __clone
1633
-     */
1634
-    public function __clone()
1635
-    {
1636
-    }
1637
-
1638
-
1639
-
1640
-    /**
1641
-     *        __wakeup
1642
-     */
1643
-    public function __wakeup()
1644
-    {
1645
-    }
1646
-
1647
-
1648
-
1649
-    /**
1650
-     *        __destruct
1651
-     */
1652
-    public function __destruct()
1653
-    {
1654
-    }
1655
-}
1656
-
1657
-
1658
-
1659
-/**
1660
- * Class for defining what's in the EE_Config relating to registration settings
1661
- */
1662
-class EE_Core_Config extends EE_Config_Base
1663
-{
1664
-
1665
-    public $current_blog_id;
1666
-
1667
-    public $ee_ueip_optin;
1668
-
1669
-    public $ee_ueip_has_notified;
1670
-
1671
-    /**
1672
-     * Not to be confused with the 4 critical page variables (See
1673
-     * get_critical_pages_array()), this is just an array of wp posts that have EE
1674
-     * shortcodes in them. Keys are slugs, values are arrays with only 1 element: where the key is the shortcode
1675
-     * in the page, and the value is the page's ID. The key 'posts' is basically a duplicate of this same array.
1676
-     *
1677
-     * @var array
1678
-     */
1679
-    public $post_shortcodes;
1680
-
1681
-    public $module_route_map;
1682
-
1683
-    public $module_forward_map;
1684
-
1685
-    public $module_view_map;
1686
-
1687
-    /**
1688
-     * The next 4 vars are the IDs of critical EE pages.
1689
-     *
1690
-     * @var int
1691
-     */
1692
-    public $reg_page_id;
1693
-
1694
-    public $txn_page_id;
1695
-
1696
-    public $thank_you_page_id;
1697
-
1698
-    public $cancel_page_id;
1699
-
1700
-    /**
1701
-     * The next 4 vars are the URLs of critical EE pages.
1702
-     *
1703
-     * @var int
1704
-     */
1705
-    public $reg_page_url;
1706
-
1707
-    public $txn_page_url;
1708
-
1709
-    public $thank_you_page_url;
1710
-
1711
-    public $cancel_page_url;
1712
-
1713
-    /**
1714
-     * The next vars relate to the custom slugs for EE CPT routes
1715
-     */
1716
-    public $event_cpt_slug;
1717
-
1718
-
1719
-    /**
1720
-     * This caches the _ee_ueip_option in case this config is reset in the same
1721
-     * request across blog switches in a multisite context.
1722
-     * Avoids extra queries to the db for this option.
1723
-     *
1724
-     * @var bool
1725
-     */
1726
-    public static $ee_ueip_option;
1727
-
1728
-
1729
-
1730
-    /**
1731
-     *    class constructor
1732
-     *
1733
-     * @access    public
1734
-     */
1735
-    public function __construct()
1736
-    {
1737
-        // set default organization settings
1738
-        $this->current_blog_id = get_current_blog_id();
1739
-        $this->current_blog_id = $this->current_blog_id === null ? 1 : $this->current_blog_id;
1740
-        $this->ee_ueip_optin = $this->_get_main_ee_ueip_optin();
1741
-        $this->ee_ueip_has_notified = is_main_site() ? get_option('ee_ueip_has_notified', false) : true;
1742
-        $this->post_shortcodes = array();
1743
-        $this->module_route_map = array();
1744
-        $this->module_forward_map = array();
1745
-        $this->module_view_map = array();
1746
-        // critical EE page IDs
1747
-        $this->reg_page_id = 0;
1748
-        $this->txn_page_id = 0;
1749
-        $this->thank_you_page_id = 0;
1750
-        $this->cancel_page_id = 0;
1751
-        // critical EE page URLs
1752
-        $this->reg_page_url = '';
1753
-        $this->txn_page_url = '';
1754
-        $this->thank_you_page_url = '';
1755
-        $this->cancel_page_url = '';
1756
-        //cpt slugs
1757
-        $this->event_cpt_slug = __('events', 'event_espresso');
1758
-        //ueip constant check
1759
-        if (defined('EE_DISABLE_UXIP') && EE_DISABLE_UXIP) {
1760
-            $this->ee_ueip_optin = false;
1761
-            $this->ee_ueip_has_notified = true;
1762
-        }
1763
-    }
1764
-
1765
-
1766
-
1767
-    /**
1768
-     * @return array
1769
-     */
1770
-    public function get_critical_pages_array()
1771
-    {
1772
-        return array(
1773
-            $this->reg_page_id,
1774
-            $this->txn_page_id,
1775
-            $this->thank_you_page_id,
1776
-            $this->cancel_page_id,
1777
-        );
1778
-    }
1779
-
1780
-
1781
-
1782
-    /**
1783
-     * @return array
1784
-     */
1785
-    public function get_critical_pages_shortcodes_array()
1786
-    {
1787
-        return array(
1788
-            $this->reg_page_id       => 'ESPRESSO_CHECKOUT',
1789
-            $this->txn_page_id       => 'ESPRESSO_TXN_PAGE',
1790
-            $this->thank_you_page_id => 'ESPRESSO_THANK_YOU',
1791
-            $this->cancel_page_id    => 'ESPRESSO_CANCELLED',
1792
-        );
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     *  gets/returns URL for EE reg_page
1799
-     *
1800
-     * @access    public
1801
-     * @return    string
1802
-     */
1803
-    public function reg_page_url()
1804
-    {
1805
-        if (! $this->reg_page_url) {
1806
-            $this->reg_page_url = add_query_arg(
1807
-                                      array('uts' => time()),
1808
-                                      get_permalink($this->reg_page_id)
1809
-                                  ) . '#checkout';
1810
-        }
1811
-        return $this->reg_page_url;
1812
-    }
1813
-
1814
-
1815
-
1816
-    /**
1817
-     *  gets/returns URL for EE txn_page
1818
-     *
1819
-     * @param array $query_args like what gets passed to
1820
-     *                          add_query_arg() as the first argument
1821
-     * @access    public
1822
-     * @return    string
1823
-     */
1824
-    public function txn_page_url($query_args = array())
1825
-    {
1826
-        if (! $this->txn_page_url) {
1827
-            $this->txn_page_url = get_permalink($this->txn_page_id);
1828
-        }
1829
-        if ($query_args) {
1830
-            return add_query_arg($query_args, $this->txn_page_url);
1831
-        } else {
1832
-            return $this->txn_page_url;
1833
-        }
1834
-    }
1835
-
1836
-
1837
-
1838
-    /**
1839
-     *  gets/returns URL for EE thank_you_page
1840
-     *
1841
-     * @param array $query_args like what gets passed to
1842
-     *                          add_query_arg() as the first argument
1843
-     * @access    public
1844
-     * @return    string
1845
-     */
1846
-    public function thank_you_page_url($query_args = array())
1847
-    {
1848
-        if (! $this->thank_you_page_url) {
1849
-            $this->thank_you_page_url = get_permalink($this->thank_you_page_id);
1850
-        }
1851
-        if ($query_args) {
1852
-            return add_query_arg($query_args, $this->thank_you_page_url);
1853
-        } else {
1854
-            return $this->thank_you_page_url;
1855
-        }
1856
-    }
1857
-
1858
-
1859
-
1860
-    /**
1861
-     *  gets/returns URL for EE cancel_page
1862
-     *
1863
-     * @access    public
1864
-     * @return    string
1865
-     */
1866
-    public function cancel_page_url()
1867
-    {
1868
-        if (! $this->cancel_page_url) {
1869
-            $this->cancel_page_url = get_permalink($this->cancel_page_id);
1870
-        }
1871
-        return $this->cancel_page_url;
1872
-    }
1873
-
1874
-
1875
-
1876
-    /**
1877
-     * Resets all critical page urls to their original state.  Used primarily by the __sleep() magic method currently.
1878
-     *
1879
-     * @since 4.7.5
1880
-     */
1881
-    protected function _reset_urls()
1882
-    {
1883
-        $this->reg_page_url = '';
1884
-        $this->txn_page_url = '';
1885
-        $this->cancel_page_url = '';
1886
-        $this->thank_you_page_url = '';
1887
-    }
1888
-
1889
-
1890
-
1891
-    /**
1892
-     * Used to return what the optin value is set for the EE User Experience Program.
1893
-     * This accounts for multisite and this value being requested for a subsite.  In multisite, the value is set
1894
-     * on the main site only.
1895
-     *
1896
-     * @return mixed|void
1897
-     */
1898
-    protected function _get_main_ee_ueip_optin()
1899
-    {
1900
-        //if this is the main site then we can just bypass our direct query.
1901
-        if (is_main_site()) {
1902
-            return get_option('ee_ueip_optin', false);
1903
-        }
1904
-        //is this already cached for this request?  If so use it.
1905
-        if ( ! empty(EE_Core_Config::$ee_ueip_option)) {
1906
-            return EE_Core_Config::$ee_ueip_option;
1907
-        }
1908
-        global $wpdb;
1909
-        $current_network_main_site = is_multisite() ? get_current_site() : null;
1910
-        $current_main_site_id = ! empty($current_network_main_site) ? $current_network_main_site->blog_id : 1;
1911
-        $option = 'ee_ueip_optin';
1912
-        //set correct table for query
1913
-        $table_name = $wpdb->get_blog_prefix($current_main_site_id) . 'options';
1914
-        //rather than getting blog option for the $current_main_site_id, we do a direct $wpdb query because
1915
-        //get_blog_option() does a switch_to_blog an that could cause infinite recursion because EE_Core_Config might be
1916
-        //re-constructed on the blog switch.  Note, we are still executing any core wp filters on this option retrieval.
1917
-        //this bit of code is basically a direct copy of get_option without any caching because we are NOT switched to the blog
1918
-        //for the purpose of caching.
1919
-        $pre = apply_filters('pre_option_' . $option, false, $option);
1920
-        if (false !== $pre) {
1921
-            EE_Core_Config::$ee_ueip_option = $pre;
1922
-            return EE_Core_Config::$ee_ueip_option;
1923
-        }
1924
-        $row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $table_name WHERE option_name = %s LIMIT 1",
1925
-            $option));
1926
-        if (is_object($row)) {
1927
-            $value = $row->option_value;
1928
-        } else { //option does not exist so use default.
1929
-            return apply_filters('default_option_' . $option, false, $option);
1930
-        }
1931
-        EE_Core_Config::$ee_ueip_option = apply_filters('option_' . $option, maybe_unserialize($value), $option);
1932
-        return EE_Core_Config::$ee_ueip_option;
1933
-    }
1934
-
1935
-
1936
-
1937
-    /**
1938
-     * Currently used to ensure critical page urls have initial values saved to the db instead of any current set values
1939
-     * on the object.
1940
-     *
1941
-     * @return array
1942
-     */
1943
-    public function __sleep()
1944
-    {
1945
-        //reset all url properties
1946
-        $this->_reset_urls();
1947
-        //return what to save to db
1948
-        return array_keys(get_object_vars($this));
1949
-    }
1950
-
1951
-}
1952
-
1953
-
1954
-
1955
-/**
1956
- * Config class for storing info on the Organization
1957
- */
1958
-class EE_Organization_Config extends EE_Config_Base
1959
-{
1960
-
1961
-    /**
1962
-     * @var string $name
1963
-     * eg EE4.1
1964
-     */
1965
-    public $name;
1966
-
1967
-    /**
1968
-     * @var string $address_1
1969
-     * eg 123 Onna Road
1970
-     */
1971
-    public $address_1;
1972
-
1973
-    /**
1974
-     * @var string $address_2
1975
-     * eg PO Box 123
1976
-     */
1977
-    public $address_2;
1978
-
1979
-    /**
1980
-     * @var string $city
1981
-     * eg Inna City
1982
-     */
1983
-    public $city;
1984
-
1985
-    /**
1986
-     * @var int $STA_ID
1987
-     * eg 4
1988
-     */
1989
-    public $STA_ID;
1990
-
1991
-    /**
1992
-     * @var string $CNT_ISO
1993
-     * eg US
1994
-     */
1995
-    public $CNT_ISO;
1996
-
1997
-    /**
1998
-     * @var string $zip
1999
-     * eg 12345  or V1A 2B3
2000
-     */
2001
-    public $zip;
2002
-
2003
-    /**
2004
-     * @var string $email
2005
-     * eg [email protected]
2006
-     */
2007
-    public $email;
2008
-
2009
-
2010
-    /**
2011
-     * @var string $phone
2012
-     * eg. 111-111-1111
2013
-     */
2014
-    public $phone;
2015
-
2016
-
2017
-    /**
2018
-     * @var string $vat
2019
-     * VAT/Tax Number
2020
-     */
2021
-    public $vat;
2022
-
2023
-    /**
2024
-     * @var string $logo_url
2025
-     * eg http://www.somedomain.com/wp-content/uploads/kittehs.jpg
2026
-     */
2027
-    public $logo_url;
2028
-
2029
-
2030
-    /**
2031
-     * The below are all various properties for holding links to organization social network profiles
2032
-     *
2033
-     * @var string
2034
-     */
2035
-    /**
2036
-     * facebook (facebook.com/profile.name)
2037
-     *
2038
-     * @var string
2039
-     */
2040
-    public $facebook;
2041
-
2042
-
2043
-    /**
2044
-     * twitter (twitter.com/twitter_handle)
2045
-     *
2046
-     * @var string
2047
-     */
2048
-    public $twitter;
2049
-
2050
-
2051
-    /**
2052
-     * linkedin (linkedin.com/in/profile_name)
2053
-     *
2054
-     * @var string
2055
-     */
2056
-    public $linkedin;
2057
-
2058
-
2059
-    /**
2060
-     * pinterest (www.pinterest.com/profile_name)
2061
-     *
2062
-     * @var string
2063
-     */
2064
-    public $pinterest;
2065
-
2066
-
2067
-    /**
2068
-     * google+ (google.com/+profileName)
2069
-     *
2070
-     * @var string
2071
-     */
2072
-    public $google;
2073
-
2074
-
2075
-    /**
2076
-     * instagram (instagram.com/handle)
2077
-     *
2078
-     * @var string
2079
-     */
2080
-    public $instagram;
2081
-
2082
-
2083
-
2084
-    /**
2085
-     *    class constructor
2086
-     *
2087
-     * @access    public
2088
-     */
2089
-    public function __construct()
2090
-    {
2091
-        // set default organization settings
2092
-        $this->name = get_bloginfo('name');
2093
-        $this->address_1 = '123 Onna Road';
2094
-        $this->address_2 = 'PO Box 123';
2095
-        $this->city = 'Inna City';
2096
-        $this->STA_ID = 4;
2097
-        $this->CNT_ISO = 'US';
2098
-        $this->zip = '12345';
2099
-        $this->email = get_bloginfo('admin_email');
2100
-        $this->phone = '';
2101
-        $this->vat = '123456789';
2102
-        $this->logo_url = '';
2103
-        $this->facebook = '';
2104
-        $this->twitter = '';
2105
-        $this->linkedin = '';
2106
-        $this->pinterest = '';
2107
-        $this->google = '';
2108
-        $this->instagram = '';
2109
-    }
2110
-
2111
-}
2112
-
2113
-
2114
-
2115
-/**
2116
- * Class for defining what's in the EE_Config relating to currency
2117
- */
2118
-class EE_Currency_Config extends EE_Config_Base
2119
-{
2120
-
2121
-    /**
2122
-     * @var string $code
2123
-     * eg 'US'
2124
-     */
2125
-    public $code;
2126
-
2127
-    /**
2128
-     * @var string $name
2129
-     * eg 'Dollar'
2130
-     */
2131
-    public $name;
2132
-
2133
-    /**
2134
-     * plural name
2135
-     *
2136
-     * @var string $plural
2137
-     * eg 'Dollars'
2138
-     */
2139
-    public $plural;
2140
-
2141
-    /**
2142
-     * currency sign
2143
-     *
2144
-     * @var string $sign
2145
-     * eg '$'
2146
-     */
2147
-    public $sign;
2148
-
2149
-    /**
2150
-     * Whether the currency sign should come before the number or not
2151
-     *
2152
-     * @var boolean $sign_b4
2153
-     */
2154
-    public $sign_b4;
2155
-
2156
-    /**
2157
-     * How many digits should come after the decimal place
2158
-     *
2159
-     * @var int $dec_plc
2160
-     */
2161
-    public $dec_plc;
2162
-
2163
-    /**
2164
-     * Symbol to use for decimal mark
2165
-     *
2166
-     * @var string $dec_mrk
2167
-     * eg '.'
2168
-     */
2169
-    public $dec_mrk;
2170
-
2171
-    /**
2172
-     * Symbol to use for thousands
2173
-     *
2174
-     * @var string $thsnds
2175
-     * eg ','
2176
-     */
2177
-    public $thsnds;
2178
-
2179
-
2180
-
2181
-    /**
2182
-     *    class constructor
2183
-     *
2184
-     * @access    public
2185
-     * @param string $CNT_ISO
2186
-     * @throws \EE_Error
2187
-     */
2188
-    public function __construct($CNT_ISO = '')
2189
-    {
2190
-        /** @var \EventEspresso\core\services\database\TableAnalysis $table_analysis */
2191
-        $table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
2192
-        // get country code from organization settings or use default
2193
-        $ORG_CNT = isset(EE_Registry::instance()->CFG->organization)
2194
-                   && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
2195
-            ? EE_Registry::instance()->CFG->organization->CNT_ISO
2196
-            : '';
2197
-        // but override if requested
2198
-        $CNT_ISO = ! empty($CNT_ISO) ? $CNT_ISO : $ORG_CNT;
2199
-        // so if that all went well, and we are not in M-Mode (cuz you can't query the db in M-Mode) and double-check the countries table exists
2200
-        if (
2201
-            ! empty($CNT_ISO)
2202
-            && EE_Maintenance_Mode::instance()->models_can_query()
2203
-            && $table_analysis->tableExists(EE_Registry::instance()->load_model('Country')->table())
2204
-        ) {
2205
-            // retrieve the country settings from the db, just in case they have been customized
2206
-            $country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($CNT_ISO);
2207
-            if ($country instanceof EE_Country) {
2208
-                $this->code = $country->currency_code();    // currency code: USD, CAD, EUR
2209
-                $this->name = $country->currency_name_single();    // Dollar
2210
-                $this->plural = $country->currency_name_plural();    // Dollars
2211
-                $this->sign = $country->currency_sign();            // currency sign: $
2212
-                $this->sign_b4 = $country->currency_sign_before();        // currency sign before or after: $TRUE  or  FALSE$
2213
-                $this->dec_plc = $country->currency_decimal_places();    // decimal places: 2 = 0.00  3 = 0.000
2214
-                $this->dec_mrk = $country->currency_decimal_mark();    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2215
-                $this->thsnds = $country->currency_thousands_separator();    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2216
-            }
2217
-        }
2218
-        // fallback to hardcoded defaults, in case the above failed
2219
-        if (empty($this->code)) {
2220
-            // set default currency settings
2221
-            $this->code = 'USD';    // currency code: USD, CAD, EUR
2222
-            $this->name = __('Dollar', 'event_espresso');    // Dollar
2223
-            $this->plural = __('Dollars', 'event_espresso');    // Dollars
2224
-            $this->sign = '$';    // currency sign: $
2225
-            $this->sign_b4 = true;    // currency sign before or after: $TRUE  or  FALSE$
2226
-            $this->dec_plc = 2;    // decimal places: 2 = 0.00  3 = 0.000
2227
-            $this->dec_mrk = '.';    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2228
-            $this->thsnds = ',';    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2229
-        }
2230
-    }
2231
-}
2232
-
2233
-
2234
-
2235
-/**
2236
- * Class for defining what's in the EE_Config relating to registration settings
2237
- */
2238
-class EE_Registration_Config extends EE_Config_Base
2239
-{
2240
-
2241
-    /**
2242
-     * Default registration status
2243
-     *
2244
-     * @var string $default_STS_ID
2245
-     * eg 'RPP'
2246
-     */
2247
-    public $default_STS_ID;
2248
-
2249
-
2250
-    /**
2251
-     * For new events, this will be the default value for the maximum number of tickets (equivalent to maximum number of
2252
-     * registrations)
2253
-     * @var int
2254
-     */
2255
-    public $default_maximum_number_of_tickets;
2256
-
2257
-
2258
-    /**
2259
-     * level of validation to apply to email addresses
2260
-     *
2261
-     * @var string $email_validation_level
2262
-     * options: 'basic', 'wp_default', 'i18n', 'i18n_dns'
2263
-     */
2264
-    public $email_validation_level;
2265
-
2266
-    /**
2267
-     *    whether or not to show alternate payment options during the reg process if payment status is pending
2268
-     *
2269
-     * @var boolean $show_pending_payment_options
2270
-     */
2271
-    public $show_pending_payment_options;
2272
-
2273
-    /**
2274
-     * Whether to skip the registration confirmation page
2275
-     *
2276
-     * @var boolean $skip_reg_confirmation
2277
-     */
2278
-    public $skip_reg_confirmation;
2279
-
2280
-    /**
2281
-     * an array of SPCO reg steps where:
2282
-     *        the keys denotes the reg step order
2283
-     *        each element consists of an array with the following elements:
2284
-     *            "file_path" => the file path to the EE_SPCO_Reg_Step class
2285
-     *            "class_name" => the specific EE_SPCO_Reg_Step child class name
2286
-     *            "slug" => the URL param used to trigger the reg step
2287
-     *
2288
-     * @var array $reg_steps
2289
-     */
2290
-    public $reg_steps;
2291
-
2292
-    /**
2293
-     * Whether registration confirmation should be the last page of SPCO
2294
-     *
2295
-     * @var boolean $reg_confirmation_last
2296
-     */
2297
-    public $reg_confirmation_last;
2298
-
2299
-    /**
2300
-     * Whether or not to enable the EE Bot Trap
2301
-     *
2302
-     * @var boolean $use_bot_trap
2303
-     */
2304
-    public $use_bot_trap;
2305
-
2306
-    /**
2307
-     * Whether or not to encrypt some data sent by the EE Bot Trap
2308
-     *
2309
-     * @var boolean $use_encryption
2310
-     */
2311
-    public $use_encryption;
1545
+}
2312 1546
 
2313
-    /**
2314
-     * Whether or not to use ReCaptcha
2315
-     *
2316
-     * @var boolean $use_captcha
2317
-     */
2318
-    public $use_captcha;
2319 1547
 
2320
-    /**
2321
-     * ReCaptcha Theme
2322
-     *
2323
-     * @var string $recaptcha_theme
2324
-     *    options: 'dark    ', 'light'
2325
-     */
2326
-    public $recaptcha_theme;
2327 1548
 
2328
-    /**
2329
-     * ReCaptcha Type
2330
-     *
2331
-     * @var string $recaptcha_type
2332
-     *    options: 'audio', 'image'
2333
-     */
2334
-    public $recaptcha_type;
1549
+/**
1550
+ * Base class used for config classes. These classes should generally not have
1551
+ * magic functions in use, except we'll allow them to magically set and get stuff...
1552
+ * basically, they should just be well-defined stdClasses
1553
+ */
1554
+class EE_Config_Base
1555
+{
2335 1556
 
2336
-    /**
2337
-     * ReCaptcha language
2338
-     *
2339
-     * @var string $recaptcha_language
2340
-     * eg 'en'
2341
-     */
2342
-    public $recaptcha_language;
1557
+	/**
1558
+	 * Utility function for escaping the value of a property and returning.
1559
+	 *
1560
+	 * @param string $property property name (checks to see if exists).
1561
+	 * @return mixed if a detected type found return the escaped value, otherwise just the raw value is returned.
1562
+	 * @throws \EE_Error
1563
+	 */
1564
+	public function get_pretty($property)
1565
+	{
1566
+		if (! property_exists($this, $property)) {
1567
+			throw new EE_Error(
1568
+				sprintf(
1569
+					__(
1570
+						'%1$s::get_pretty() has been called with the property %2$s which does not exist on the %1$s config class.',
1571
+						'event_espresso'
1572
+					),
1573
+					get_class($this),
1574
+					$property
1575
+				)
1576
+			);
1577
+		}
1578
+		//just handling escaping of strings for now.
1579
+		if (is_string($this->{$property})) {
1580
+			return stripslashes($this->{$property});
1581
+		}
1582
+		return $this->{$property};
1583
+	}
1584
+
1585
+
1586
+
1587
+	public function populate()
1588
+	{
1589
+		//grab defaults via a new instance of this class.
1590
+		$class_name = get_class($this);
1591
+		$defaults = new $class_name;
1592
+		//loop through the properties for this class and see if they are set.  If they are NOT, then grab the
1593
+		//default from our $defaults object.
1594
+		foreach (get_object_vars($defaults) as $property => $value) {
1595
+			if ($this->{$property} === null) {
1596
+				$this->{$property} = $value;
1597
+			}
1598
+		}
1599
+		//cleanup
1600
+		unset($defaults);
1601
+	}
1602
+
1603
+
1604
+
1605
+	/**
1606
+	 *        __isset
1607
+	 *
1608
+	 * @param $a
1609
+	 * @return bool
1610
+	 */
1611
+	public function __isset($a)
1612
+	{
1613
+		return false;
1614
+	}
1615
+
1616
+
1617
+
1618
+	/**
1619
+	 *        __unset
1620
+	 *
1621
+	 * @param $a
1622
+	 * @return bool
1623
+	 */
1624
+	public function __unset($a)
1625
+	{
1626
+		return false;
1627
+	}
1628
+
1629
+
1630
+
1631
+	/**
1632
+	 *        __clone
1633
+	 */
1634
+	public function __clone()
1635
+	{
1636
+	}
1637
+
1638
+
1639
+
1640
+	/**
1641
+	 *        __wakeup
1642
+	 */
1643
+	public function __wakeup()
1644
+	{
1645
+	}
1646
+
1647
+
1648
+
1649
+	/**
1650
+	 *        __destruct
1651
+	 */
1652
+	public function __destruct()
1653
+	{
1654
+	}
1655
+}
2343 1656
 
2344
-    /**
2345
-     * ReCaptcha public key
2346
-     *
2347
-     * @var string $recaptcha_publickey
2348
-     */
2349
-    public $recaptcha_publickey;
2350 1657
 
2351
-    /**
2352
-     * ReCaptcha private key
2353
-     *
2354
-     * @var string $recaptcha_privatekey
2355
-     */
2356
-    public $recaptcha_privatekey;
2357 1658
 
2358
-    /**
2359
-     * ReCaptcha width
2360
-     *
2361
-     * @var int $recaptcha_width
2362
-     * @deprecated
2363
-     */
2364
-    public $recaptcha_width;
1659
+/**
1660
+ * Class for defining what's in the EE_Config relating to registration settings
1661
+ */
1662
+class EE_Core_Config extends EE_Config_Base
1663
+{
2365 1664
 
2366
-    /**
2367
-     * Whether or not invalid attempts to directly access the registration checkout page should be tracked.
2368
-     *
2369
-     * @var boolean $track_invalid_checkout_access
2370
-     */
2371
-    protected $track_invalid_checkout_access = true;
1665
+	public $current_blog_id;
1666
+
1667
+	public $ee_ueip_optin;
1668
+
1669
+	public $ee_ueip_has_notified;
1670
+
1671
+	/**
1672
+	 * Not to be confused with the 4 critical page variables (See
1673
+	 * get_critical_pages_array()), this is just an array of wp posts that have EE
1674
+	 * shortcodes in them. Keys are slugs, values are arrays with only 1 element: where the key is the shortcode
1675
+	 * in the page, and the value is the page's ID. The key 'posts' is basically a duplicate of this same array.
1676
+	 *
1677
+	 * @var array
1678
+	 */
1679
+	public $post_shortcodes;
1680
+
1681
+	public $module_route_map;
1682
+
1683
+	public $module_forward_map;
1684
+
1685
+	public $module_view_map;
1686
+
1687
+	/**
1688
+	 * The next 4 vars are the IDs of critical EE pages.
1689
+	 *
1690
+	 * @var int
1691
+	 */
1692
+	public $reg_page_id;
1693
+
1694
+	public $txn_page_id;
1695
+
1696
+	public $thank_you_page_id;
1697
+
1698
+	public $cancel_page_id;
1699
+
1700
+	/**
1701
+	 * The next 4 vars are the URLs of critical EE pages.
1702
+	 *
1703
+	 * @var int
1704
+	 */
1705
+	public $reg_page_url;
1706
+
1707
+	public $txn_page_url;
1708
+
1709
+	public $thank_you_page_url;
1710
+
1711
+	public $cancel_page_url;
1712
+
1713
+	/**
1714
+	 * The next vars relate to the custom slugs for EE CPT routes
1715
+	 */
1716
+	public $event_cpt_slug;
1717
+
1718
+
1719
+	/**
1720
+	 * This caches the _ee_ueip_option in case this config is reset in the same
1721
+	 * request across blog switches in a multisite context.
1722
+	 * Avoids extra queries to the db for this option.
1723
+	 *
1724
+	 * @var bool
1725
+	 */
1726
+	public static $ee_ueip_option;
1727
+
1728
+
1729
+
1730
+	/**
1731
+	 *    class constructor
1732
+	 *
1733
+	 * @access    public
1734
+	 */
1735
+	public function __construct()
1736
+	{
1737
+		// set default organization settings
1738
+		$this->current_blog_id = get_current_blog_id();
1739
+		$this->current_blog_id = $this->current_blog_id === null ? 1 : $this->current_blog_id;
1740
+		$this->ee_ueip_optin = $this->_get_main_ee_ueip_optin();
1741
+		$this->ee_ueip_has_notified = is_main_site() ? get_option('ee_ueip_has_notified', false) : true;
1742
+		$this->post_shortcodes = array();
1743
+		$this->module_route_map = array();
1744
+		$this->module_forward_map = array();
1745
+		$this->module_view_map = array();
1746
+		// critical EE page IDs
1747
+		$this->reg_page_id = 0;
1748
+		$this->txn_page_id = 0;
1749
+		$this->thank_you_page_id = 0;
1750
+		$this->cancel_page_id = 0;
1751
+		// critical EE page URLs
1752
+		$this->reg_page_url = '';
1753
+		$this->txn_page_url = '';
1754
+		$this->thank_you_page_url = '';
1755
+		$this->cancel_page_url = '';
1756
+		//cpt slugs
1757
+		$this->event_cpt_slug = __('events', 'event_espresso');
1758
+		//ueip constant check
1759
+		if (defined('EE_DISABLE_UXIP') && EE_DISABLE_UXIP) {
1760
+			$this->ee_ueip_optin = false;
1761
+			$this->ee_ueip_has_notified = true;
1762
+		}
1763
+	}
1764
+
1765
+
1766
+
1767
+	/**
1768
+	 * @return array
1769
+	 */
1770
+	public function get_critical_pages_array()
1771
+	{
1772
+		return array(
1773
+			$this->reg_page_id,
1774
+			$this->txn_page_id,
1775
+			$this->thank_you_page_id,
1776
+			$this->cancel_page_id,
1777
+		);
1778
+	}
1779
+
1780
+
1781
+
1782
+	/**
1783
+	 * @return array
1784
+	 */
1785
+	public function get_critical_pages_shortcodes_array()
1786
+	{
1787
+		return array(
1788
+			$this->reg_page_id       => 'ESPRESSO_CHECKOUT',
1789
+			$this->txn_page_id       => 'ESPRESSO_TXN_PAGE',
1790
+			$this->thank_you_page_id => 'ESPRESSO_THANK_YOU',
1791
+			$this->cancel_page_id    => 'ESPRESSO_CANCELLED',
1792
+		);
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 *  gets/returns URL for EE reg_page
1799
+	 *
1800
+	 * @access    public
1801
+	 * @return    string
1802
+	 */
1803
+	public function reg_page_url()
1804
+	{
1805
+		if (! $this->reg_page_url) {
1806
+			$this->reg_page_url = add_query_arg(
1807
+									  array('uts' => time()),
1808
+									  get_permalink($this->reg_page_id)
1809
+								  ) . '#checkout';
1810
+		}
1811
+		return $this->reg_page_url;
1812
+	}
1813
+
1814
+
1815
+
1816
+	/**
1817
+	 *  gets/returns URL for EE txn_page
1818
+	 *
1819
+	 * @param array $query_args like what gets passed to
1820
+	 *                          add_query_arg() as the first argument
1821
+	 * @access    public
1822
+	 * @return    string
1823
+	 */
1824
+	public function txn_page_url($query_args = array())
1825
+	{
1826
+		if (! $this->txn_page_url) {
1827
+			$this->txn_page_url = get_permalink($this->txn_page_id);
1828
+		}
1829
+		if ($query_args) {
1830
+			return add_query_arg($query_args, $this->txn_page_url);
1831
+		} else {
1832
+			return $this->txn_page_url;
1833
+		}
1834
+	}
1835
+
1836
+
1837
+
1838
+	/**
1839
+	 *  gets/returns URL for EE thank_you_page
1840
+	 *
1841
+	 * @param array $query_args like what gets passed to
1842
+	 *                          add_query_arg() as the first argument
1843
+	 * @access    public
1844
+	 * @return    string
1845
+	 */
1846
+	public function thank_you_page_url($query_args = array())
1847
+	{
1848
+		if (! $this->thank_you_page_url) {
1849
+			$this->thank_you_page_url = get_permalink($this->thank_you_page_id);
1850
+		}
1851
+		if ($query_args) {
1852
+			return add_query_arg($query_args, $this->thank_you_page_url);
1853
+		} else {
1854
+			return $this->thank_you_page_url;
1855
+		}
1856
+	}
1857
+
1858
+
1859
+
1860
+	/**
1861
+	 *  gets/returns URL for EE cancel_page
1862
+	 *
1863
+	 * @access    public
1864
+	 * @return    string
1865
+	 */
1866
+	public function cancel_page_url()
1867
+	{
1868
+		if (! $this->cancel_page_url) {
1869
+			$this->cancel_page_url = get_permalink($this->cancel_page_id);
1870
+		}
1871
+		return $this->cancel_page_url;
1872
+	}
1873
+
1874
+
1875
+
1876
+	/**
1877
+	 * Resets all critical page urls to their original state.  Used primarily by the __sleep() magic method currently.
1878
+	 *
1879
+	 * @since 4.7.5
1880
+	 */
1881
+	protected function _reset_urls()
1882
+	{
1883
+		$this->reg_page_url = '';
1884
+		$this->txn_page_url = '';
1885
+		$this->cancel_page_url = '';
1886
+		$this->thank_you_page_url = '';
1887
+	}
1888
+
1889
+
1890
+
1891
+	/**
1892
+	 * Used to return what the optin value is set for the EE User Experience Program.
1893
+	 * This accounts for multisite and this value being requested for a subsite.  In multisite, the value is set
1894
+	 * on the main site only.
1895
+	 *
1896
+	 * @return mixed|void
1897
+	 */
1898
+	protected function _get_main_ee_ueip_optin()
1899
+	{
1900
+		//if this is the main site then we can just bypass our direct query.
1901
+		if (is_main_site()) {
1902
+			return get_option('ee_ueip_optin', false);
1903
+		}
1904
+		//is this already cached for this request?  If so use it.
1905
+		if ( ! empty(EE_Core_Config::$ee_ueip_option)) {
1906
+			return EE_Core_Config::$ee_ueip_option;
1907
+		}
1908
+		global $wpdb;
1909
+		$current_network_main_site = is_multisite() ? get_current_site() : null;
1910
+		$current_main_site_id = ! empty($current_network_main_site) ? $current_network_main_site->blog_id : 1;
1911
+		$option = 'ee_ueip_optin';
1912
+		//set correct table for query
1913
+		$table_name = $wpdb->get_blog_prefix($current_main_site_id) . 'options';
1914
+		//rather than getting blog option for the $current_main_site_id, we do a direct $wpdb query because
1915
+		//get_blog_option() does a switch_to_blog an that could cause infinite recursion because EE_Core_Config might be
1916
+		//re-constructed on the blog switch.  Note, we are still executing any core wp filters on this option retrieval.
1917
+		//this bit of code is basically a direct copy of get_option without any caching because we are NOT switched to the blog
1918
+		//for the purpose of caching.
1919
+		$pre = apply_filters('pre_option_' . $option, false, $option);
1920
+		if (false !== $pre) {
1921
+			EE_Core_Config::$ee_ueip_option = $pre;
1922
+			return EE_Core_Config::$ee_ueip_option;
1923
+		}
1924
+		$row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $table_name WHERE option_name = %s LIMIT 1",
1925
+			$option));
1926
+		if (is_object($row)) {
1927
+			$value = $row->option_value;
1928
+		} else { //option does not exist so use default.
1929
+			return apply_filters('default_option_' . $option, false, $option);
1930
+		}
1931
+		EE_Core_Config::$ee_ueip_option = apply_filters('option_' . $option, maybe_unserialize($value), $option);
1932
+		return EE_Core_Config::$ee_ueip_option;
1933
+	}
1934
+
1935
+
1936
+
1937
+	/**
1938
+	 * Currently used to ensure critical page urls have initial values saved to the db instead of any current set values
1939
+	 * on the object.
1940
+	 *
1941
+	 * @return array
1942
+	 */
1943
+	public function __sleep()
1944
+	{
1945
+		//reset all url properties
1946
+		$this->_reset_urls();
1947
+		//return what to save to db
1948
+		return array_keys(get_object_vars($this));
1949
+	}
2372 1950
 
1951
+}
2373 1952
 
2374 1953
 
2375
-    /**
2376
-     *    class constructor
2377
-     *
2378
-     * @access    public
2379
-     */
2380
-    public function __construct()
2381
-    {
2382
-        // set default registration settings
2383
-        $this->default_STS_ID = EEM_Registration::status_id_pending_payment;
2384
-        $this->email_validation_level = 'wp_default';
2385
-        $this->show_pending_payment_options = true;
2386
-        $this->skip_reg_confirmation = false;
2387
-        $this->reg_steps = array();
2388
-        $this->reg_confirmation_last = false;
2389
-        $this->use_bot_trap = true;
2390
-        $this->use_encryption = true;
2391
-        $this->use_captcha = false;
2392
-        $this->recaptcha_theme = 'light';
2393
-        $this->recaptcha_type = 'image';
2394
-        $this->recaptcha_language = 'en';
2395
-        $this->recaptcha_publickey = null;
2396
-        $this->recaptcha_privatekey = null;
2397
-        $this->recaptcha_width = 500;
2398
-        $this->default_maximum_number_of_tickets = 10;
2399
-    }
2400
-
2401
-
2402
-
2403
-    /**
2404
-     * This is called by the config loader and hooks are initialized AFTER the config has been populated.
2405
-     *
2406
-     * @since 4.8.8.rc.019
2407
-     */
2408
-    public function do_hooks()
2409
-    {
2410
-        add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_reg_status_on_EEM_Event'));
2411
-        add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_max_ticket_on_EEM_Event'));
2412
-    }
2413 1954
 
1955
+/**
1956
+ * Config class for storing info on the Organization
1957
+ */
1958
+class EE_Organization_Config extends EE_Config_Base
1959
+{
2414 1960
 
1961
+	/**
1962
+	 * @var string $name
1963
+	 * eg EE4.1
1964
+	 */
1965
+	public $name;
1966
+
1967
+	/**
1968
+	 * @var string $address_1
1969
+	 * eg 123 Onna Road
1970
+	 */
1971
+	public $address_1;
1972
+
1973
+	/**
1974
+	 * @var string $address_2
1975
+	 * eg PO Box 123
1976
+	 */
1977
+	public $address_2;
1978
+
1979
+	/**
1980
+	 * @var string $city
1981
+	 * eg Inna City
1982
+	 */
1983
+	public $city;
1984
+
1985
+	/**
1986
+	 * @var int $STA_ID
1987
+	 * eg 4
1988
+	 */
1989
+	public $STA_ID;
1990
+
1991
+	/**
1992
+	 * @var string $CNT_ISO
1993
+	 * eg US
1994
+	 */
1995
+	public $CNT_ISO;
1996
+
1997
+	/**
1998
+	 * @var string $zip
1999
+	 * eg 12345  or V1A 2B3
2000
+	 */
2001
+	public $zip;
2002
+
2003
+	/**
2004
+	 * @var string $email
2005
+	 * eg [email protected]
2006
+	 */
2007
+	public $email;
2008
+
2009
+
2010
+	/**
2011
+	 * @var string $phone
2012
+	 * eg. 111-111-1111
2013
+	 */
2014
+	public $phone;
2015
+
2016
+
2017
+	/**
2018
+	 * @var string $vat
2019
+	 * VAT/Tax Number
2020
+	 */
2021
+	public $vat;
2022
+
2023
+	/**
2024
+	 * @var string $logo_url
2025
+	 * eg http://www.somedomain.com/wp-content/uploads/kittehs.jpg
2026
+	 */
2027
+	public $logo_url;
2028
+
2029
+
2030
+	/**
2031
+	 * The below are all various properties for holding links to organization social network profiles
2032
+	 *
2033
+	 * @var string
2034
+	 */
2035
+	/**
2036
+	 * facebook (facebook.com/profile.name)
2037
+	 *
2038
+	 * @var string
2039
+	 */
2040
+	public $facebook;
2041
+
2042
+
2043
+	/**
2044
+	 * twitter (twitter.com/twitter_handle)
2045
+	 *
2046
+	 * @var string
2047
+	 */
2048
+	public $twitter;
2049
+
2050
+
2051
+	/**
2052
+	 * linkedin (linkedin.com/in/profile_name)
2053
+	 *
2054
+	 * @var string
2055
+	 */
2056
+	public $linkedin;
2057
+
2058
+
2059
+	/**
2060
+	 * pinterest (www.pinterest.com/profile_name)
2061
+	 *
2062
+	 * @var string
2063
+	 */
2064
+	public $pinterest;
2065
+
2066
+
2067
+	/**
2068
+	 * google+ (google.com/+profileName)
2069
+	 *
2070
+	 * @var string
2071
+	 */
2072
+	public $google;
2073
+
2074
+
2075
+	/**
2076
+	 * instagram (instagram.com/handle)
2077
+	 *
2078
+	 * @var string
2079
+	 */
2080
+	public $instagram;
2081
+
2082
+
2083
+
2084
+	/**
2085
+	 *    class constructor
2086
+	 *
2087
+	 * @access    public
2088
+	 */
2089
+	public function __construct()
2090
+	{
2091
+		// set default organization settings
2092
+		$this->name = get_bloginfo('name');
2093
+		$this->address_1 = '123 Onna Road';
2094
+		$this->address_2 = 'PO Box 123';
2095
+		$this->city = 'Inna City';
2096
+		$this->STA_ID = 4;
2097
+		$this->CNT_ISO = 'US';
2098
+		$this->zip = '12345';
2099
+		$this->email = get_bloginfo('admin_email');
2100
+		$this->phone = '';
2101
+		$this->vat = '123456789';
2102
+		$this->logo_url = '';
2103
+		$this->facebook = '';
2104
+		$this->twitter = '';
2105
+		$this->linkedin = '';
2106
+		$this->pinterest = '';
2107
+		$this->google = '';
2108
+		$this->instagram = '';
2109
+	}
2415 2110
 
2416
-    /**
2417
-     * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_default_registration_status
2418
-     * field matches the config setting for default_STS_ID.
2419
-     */
2420
-    public function set_default_reg_status_on_EEM_Event()
2421
-    {
2422
-        EEM_Event::set_default_reg_status($this->default_STS_ID);
2423
-    }
2111
+}
2424 2112
 
2425 2113
 
2426
-    /**
2427
-     * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_additional_limit field
2428
-     * for Events matches the config setting for default_maximum_number_of_tickets
2429
-     */
2430
-    public function set_default_max_ticket_on_EEM_Event()
2431
-    {
2432
-        EEM_Event::set_default_additional_limit($this->default_maximum_number_of_tickets);
2433
-    }
2434 2114
 
2115
+/**
2116
+ * Class for defining what's in the EE_Config relating to currency
2117
+ */
2118
+class EE_Currency_Config extends EE_Config_Base
2119
+{
2435 2120
 
2121
+	/**
2122
+	 * @var string $code
2123
+	 * eg 'US'
2124
+	 */
2125
+	public $code;
2126
+
2127
+	/**
2128
+	 * @var string $name
2129
+	 * eg 'Dollar'
2130
+	 */
2131
+	public $name;
2132
+
2133
+	/**
2134
+	 * plural name
2135
+	 *
2136
+	 * @var string $plural
2137
+	 * eg 'Dollars'
2138
+	 */
2139
+	public $plural;
2140
+
2141
+	/**
2142
+	 * currency sign
2143
+	 *
2144
+	 * @var string $sign
2145
+	 * eg '$'
2146
+	 */
2147
+	public $sign;
2148
+
2149
+	/**
2150
+	 * Whether the currency sign should come before the number or not
2151
+	 *
2152
+	 * @var boolean $sign_b4
2153
+	 */
2154
+	public $sign_b4;
2155
+
2156
+	/**
2157
+	 * How many digits should come after the decimal place
2158
+	 *
2159
+	 * @var int $dec_plc
2160
+	 */
2161
+	public $dec_plc;
2162
+
2163
+	/**
2164
+	 * Symbol to use for decimal mark
2165
+	 *
2166
+	 * @var string $dec_mrk
2167
+	 * eg '.'
2168
+	 */
2169
+	public $dec_mrk;
2170
+
2171
+	/**
2172
+	 * Symbol to use for thousands
2173
+	 *
2174
+	 * @var string $thsnds
2175
+	 * eg ','
2176
+	 */
2177
+	public $thsnds;
2178
+
2179
+
2180
+
2181
+	/**
2182
+	 *    class constructor
2183
+	 *
2184
+	 * @access    public
2185
+	 * @param string $CNT_ISO
2186
+	 * @throws \EE_Error
2187
+	 */
2188
+	public function __construct($CNT_ISO = '')
2189
+	{
2190
+		/** @var \EventEspresso\core\services\database\TableAnalysis $table_analysis */
2191
+		$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
2192
+		// get country code from organization settings or use default
2193
+		$ORG_CNT = isset(EE_Registry::instance()->CFG->organization)
2194
+				   && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
2195
+			? EE_Registry::instance()->CFG->organization->CNT_ISO
2196
+			: '';
2197
+		// but override if requested
2198
+		$CNT_ISO = ! empty($CNT_ISO) ? $CNT_ISO : $ORG_CNT;
2199
+		// so if that all went well, and we are not in M-Mode (cuz you can't query the db in M-Mode) and double-check the countries table exists
2200
+		if (
2201
+			! empty($CNT_ISO)
2202
+			&& EE_Maintenance_Mode::instance()->models_can_query()
2203
+			&& $table_analysis->tableExists(EE_Registry::instance()->load_model('Country')->table())
2204
+		) {
2205
+			// retrieve the country settings from the db, just in case they have been customized
2206
+			$country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($CNT_ISO);
2207
+			if ($country instanceof EE_Country) {
2208
+				$this->code = $country->currency_code();    // currency code: USD, CAD, EUR
2209
+				$this->name = $country->currency_name_single();    // Dollar
2210
+				$this->plural = $country->currency_name_plural();    // Dollars
2211
+				$this->sign = $country->currency_sign();            // currency sign: $
2212
+				$this->sign_b4 = $country->currency_sign_before();        // currency sign before or after: $TRUE  or  FALSE$
2213
+				$this->dec_plc = $country->currency_decimal_places();    // decimal places: 2 = 0.00  3 = 0.000
2214
+				$this->dec_mrk = $country->currency_decimal_mark();    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2215
+				$this->thsnds = $country->currency_thousands_separator();    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2216
+			}
2217
+		}
2218
+		// fallback to hardcoded defaults, in case the above failed
2219
+		if (empty($this->code)) {
2220
+			// set default currency settings
2221
+			$this->code = 'USD';    // currency code: USD, CAD, EUR
2222
+			$this->name = __('Dollar', 'event_espresso');    // Dollar
2223
+			$this->plural = __('Dollars', 'event_espresso');    // Dollars
2224
+			$this->sign = '$';    // currency sign: $
2225
+			$this->sign_b4 = true;    // currency sign before or after: $TRUE  or  FALSE$
2226
+			$this->dec_plc = 2;    // decimal places: 2 = 0.00  3 = 0.000
2227
+			$this->dec_mrk = '.';    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2228
+			$this->thsnds = ',';    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2229
+		}
2230
+	}
2231
+}
2436 2232
 
2437
-    /**
2438
-     * @return boolean
2439
-     */
2440
-    public function track_invalid_checkout_access()
2441
-    {
2442
-        return $this->track_invalid_checkout_access;
2443
-    }
2444 2233
 
2445 2234
 
2235
+/**
2236
+ * Class for defining what's in the EE_Config relating to registration settings
2237
+ */
2238
+class EE_Registration_Config extends EE_Config_Base
2239
+{
2446 2240
 
2447
-    /**
2448
-     * @param boolean $track_invalid_checkout_access
2449
-     */
2450
-    public function set_track_invalid_checkout_access($track_invalid_checkout_access)
2451
-    {
2452
-        $this->track_invalid_checkout_access = filter_var(
2453
-            $track_invalid_checkout_access,
2454
-            FILTER_VALIDATE_BOOLEAN
2455
-        );
2456
-    }
2241
+	/**
2242
+	 * Default registration status
2243
+	 *
2244
+	 * @var string $default_STS_ID
2245
+	 * eg 'RPP'
2246
+	 */
2247
+	public $default_STS_ID;
2248
+
2249
+
2250
+	/**
2251
+	 * For new events, this will be the default value for the maximum number of tickets (equivalent to maximum number of
2252
+	 * registrations)
2253
+	 * @var int
2254
+	 */
2255
+	public $default_maximum_number_of_tickets;
2256
+
2257
+
2258
+	/**
2259
+	 * level of validation to apply to email addresses
2260
+	 *
2261
+	 * @var string $email_validation_level
2262
+	 * options: 'basic', 'wp_default', 'i18n', 'i18n_dns'
2263
+	 */
2264
+	public $email_validation_level;
2265
+
2266
+	/**
2267
+	 *    whether or not to show alternate payment options during the reg process if payment status is pending
2268
+	 *
2269
+	 * @var boolean $show_pending_payment_options
2270
+	 */
2271
+	public $show_pending_payment_options;
2272
+
2273
+	/**
2274
+	 * Whether to skip the registration confirmation page
2275
+	 *
2276
+	 * @var boolean $skip_reg_confirmation
2277
+	 */
2278
+	public $skip_reg_confirmation;
2279
+
2280
+	/**
2281
+	 * an array of SPCO reg steps where:
2282
+	 *        the keys denotes the reg step order
2283
+	 *        each element consists of an array with the following elements:
2284
+	 *            "file_path" => the file path to the EE_SPCO_Reg_Step class
2285
+	 *            "class_name" => the specific EE_SPCO_Reg_Step child class name
2286
+	 *            "slug" => the URL param used to trigger the reg step
2287
+	 *
2288
+	 * @var array $reg_steps
2289
+	 */
2290
+	public $reg_steps;
2291
+
2292
+	/**
2293
+	 * Whether registration confirmation should be the last page of SPCO
2294
+	 *
2295
+	 * @var boolean $reg_confirmation_last
2296
+	 */
2297
+	public $reg_confirmation_last;
2298
+
2299
+	/**
2300
+	 * Whether or not to enable the EE Bot Trap
2301
+	 *
2302
+	 * @var boolean $use_bot_trap
2303
+	 */
2304
+	public $use_bot_trap;
2305
+
2306
+	/**
2307
+	 * Whether or not to encrypt some data sent by the EE Bot Trap
2308
+	 *
2309
+	 * @var boolean $use_encryption
2310
+	 */
2311
+	public $use_encryption;
2312
+
2313
+	/**
2314
+	 * Whether or not to use ReCaptcha
2315
+	 *
2316
+	 * @var boolean $use_captcha
2317
+	 */
2318
+	public $use_captcha;
2319
+
2320
+	/**
2321
+	 * ReCaptcha Theme
2322
+	 *
2323
+	 * @var string $recaptcha_theme
2324
+	 *    options: 'dark    ', 'light'
2325
+	 */
2326
+	public $recaptcha_theme;
2327
+
2328
+	/**
2329
+	 * ReCaptcha Type
2330
+	 *
2331
+	 * @var string $recaptcha_type
2332
+	 *    options: 'audio', 'image'
2333
+	 */
2334
+	public $recaptcha_type;
2335
+
2336
+	/**
2337
+	 * ReCaptcha language
2338
+	 *
2339
+	 * @var string $recaptcha_language
2340
+	 * eg 'en'
2341
+	 */
2342
+	public $recaptcha_language;
2343
+
2344
+	/**
2345
+	 * ReCaptcha public key
2346
+	 *
2347
+	 * @var string $recaptcha_publickey
2348
+	 */
2349
+	public $recaptcha_publickey;
2350
+
2351
+	/**
2352
+	 * ReCaptcha private key
2353
+	 *
2354
+	 * @var string $recaptcha_privatekey
2355
+	 */
2356
+	public $recaptcha_privatekey;
2357
+
2358
+	/**
2359
+	 * ReCaptcha width
2360
+	 *
2361
+	 * @var int $recaptcha_width
2362
+	 * @deprecated
2363
+	 */
2364
+	public $recaptcha_width;
2365
+
2366
+	/**
2367
+	 * Whether or not invalid attempts to directly access the registration checkout page should be tracked.
2368
+	 *
2369
+	 * @var boolean $track_invalid_checkout_access
2370
+	 */
2371
+	protected $track_invalid_checkout_access = true;
2372
+
2373
+
2374
+
2375
+	/**
2376
+	 *    class constructor
2377
+	 *
2378
+	 * @access    public
2379
+	 */
2380
+	public function __construct()
2381
+	{
2382
+		// set default registration settings
2383
+		$this->default_STS_ID = EEM_Registration::status_id_pending_payment;
2384
+		$this->email_validation_level = 'wp_default';
2385
+		$this->show_pending_payment_options = true;
2386
+		$this->skip_reg_confirmation = false;
2387
+		$this->reg_steps = array();
2388
+		$this->reg_confirmation_last = false;
2389
+		$this->use_bot_trap = true;
2390
+		$this->use_encryption = true;
2391
+		$this->use_captcha = false;
2392
+		$this->recaptcha_theme = 'light';
2393
+		$this->recaptcha_type = 'image';
2394
+		$this->recaptcha_language = 'en';
2395
+		$this->recaptcha_publickey = null;
2396
+		$this->recaptcha_privatekey = null;
2397
+		$this->recaptcha_width = 500;
2398
+		$this->default_maximum_number_of_tickets = 10;
2399
+	}
2400
+
2401
+
2402
+
2403
+	/**
2404
+	 * This is called by the config loader and hooks are initialized AFTER the config has been populated.
2405
+	 *
2406
+	 * @since 4.8.8.rc.019
2407
+	 */
2408
+	public function do_hooks()
2409
+	{
2410
+		add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_reg_status_on_EEM_Event'));
2411
+		add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_max_ticket_on_EEM_Event'));
2412
+	}
2413
+
2414
+
2415
+
2416
+	/**
2417
+	 * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_default_registration_status
2418
+	 * field matches the config setting for default_STS_ID.
2419
+	 */
2420
+	public function set_default_reg_status_on_EEM_Event()
2421
+	{
2422
+		EEM_Event::set_default_reg_status($this->default_STS_ID);
2423
+	}
2424
+
2425
+
2426
+	/**
2427
+	 * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_additional_limit field
2428
+	 * for Events matches the config setting for default_maximum_number_of_tickets
2429
+	 */
2430
+	public function set_default_max_ticket_on_EEM_Event()
2431
+	{
2432
+		EEM_Event::set_default_additional_limit($this->default_maximum_number_of_tickets);
2433
+	}
2434
+
2435
+
2436
+
2437
+	/**
2438
+	 * @return boolean
2439
+	 */
2440
+	public function track_invalid_checkout_access()
2441
+	{
2442
+		return $this->track_invalid_checkout_access;
2443
+	}
2444
+
2445
+
2446
+
2447
+	/**
2448
+	 * @param boolean $track_invalid_checkout_access
2449
+	 */
2450
+	public function set_track_invalid_checkout_access($track_invalid_checkout_access)
2451
+	{
2452
+		$this->track_invalid_checkout_access = filter_var(
2453
+			$track_invalid_checkout_access,
2454
+			FILTER_VALIDATE_BOOLEAN
2455
+		);
2456
+	}
2457 2457
 
2458 2458
 
2459 2459
 
@@ -2467,160 +2467,160 @@  discard block
 block discarded – undo
2467 2467
 class EE_Admin_Config extends EE_Config_Base
2468 2468
 {
2469 2469
 
2470
-    /**
2471
-     * @var boolean $use_personnel_manager
2472
-     */
2473
-    public $use_personnel_manager;
2474
-
2475
-    /**
2476
-     * @var boolean $use_dashboard_widget
2477
-     */
2478
-    public $use_dashboard_widget;
2479
-
2480
-    /**
2481
-     * @var int $events_in_dashboard
2482
-     */
2483
-    public $events_in_dashboard;
2484
-
2485
-    /**
2486
-     * @var boolean $use_event_timezones
2487
-     */
2488
-    public $use_event_timezones;
2489
-
2490
-    /**
2491
-     * @var boolean $use_full_logging
2492
-     */
2493
-    public $use_full_logging;
2494
-
2495
-    /**
2496
-     * @var string $log_file_name
2497
-     */
2498
-    public $log_file_name;
2499
-
2500
-    /**
2501
-     * @var string $debug_file_name
2502
-     */
2503
-    public $debug_file_name;
2504
-
2505
-    /**
2506
-     * @var boolean $use_remote_logging
2507
-     */
2508
-    public $use_remote_logging;
2509
-
2510
-    /**
2511
-     * @var string $remote_logging_url
2512
-     */
2513
-    public $remote_logging_url;
2514
-
2515
-    /**
2516
-     * @var boolean $show_reg_footer
2517
-     */
2518
-    public $show_reg_footer;
2519
-
2520
-    /**
2521
-     * @var string $affiliate_id
2522
-     */
2523
-    public $affiliate_id;
2524
-
2525
-    /**
2526
-     * help tours on or off (global setting)
2527
-     *
2528
-     * @var boolean
2529
-     */
2530
-    public $help_tour_activation;
2531
-
2532
-    /**
2533
-     * adds extra layer of encoding to session data to prevent serialization errors
2534
-     * but is incompatible with some server configuration errors
2535
-     * if you get "500 internal server errors" during registration, try turning this on
2536
-     * if you get PHP fatal errors regarding base 64 methods not defined, then turn this off
2537
-     *
2538
-     * @var boolean $encode_session_data
2539
-     */
2540
-    private $encode_session_data = false;
2541
-
2542
-
2543
-
2544
-    /**
2545
-     *    class constructor
2546
-     *
2547
-     * @access    public
2548
-     */
2549
-    public function __construct()
2550
-    {
2551
-        // set default general admin settings
2552
-        $this->use_personnel_manager = true;
2553
-        $this->use_dashboard_widget = true;
2554
-        $this->events_in_dashboard = 30;
2555
-        $this->use_event_timezones = false;
2556
-        $this->use_full_logging = false;
2557
-        $this->use_remote_logging = false;
2558
-        $this->remote_logging_url = null;
2559
-        $this->show_reg_footer = true;
2560
-        $this->affiliate_id = 'default';
2561
-        $this->help_tour_activation = true;
2562
-        $this->encode_session_data = false;
2563
-    }
2564
-
2565
-
2566
-
2567
-    /**
2568
-     * @param bool $reset
2569
-     * @return string
2570
-     */
2571
-    public function log_file_name($reset = false)
2572
-    {
2573
-        if (empty($this->log_file_name) || $reset) {
2574
-            $this->log_file_name = sanitize_key('espresso_log_' . md5(uniqid('', true))) . '.txt';
2575
-            EE_Config::instance()->update_espresso_config(false, false);
2576
-        }
2577
-        return $this->log_file_name;
2578
-    }
2579
-
2580
-
2581
-
2582
-    /**
2583
-     * @param bool $reset
2584
-     * @return string
2585
-     */
2586
-    public function debug_file_name($reset = false)
2587
-    {
2588
-        if (empty($this->debug_file_name) || $reset) {
2589
-            $this->debug_file_name = sanitize_key('espresso_debug_' . md5(uniqid('', true))) . '.txt';
2590
-            EE_Config::instance()->update_espresso_config(false, false);
2591
-        }
2592
-        return $this->debug_file_name;
2593
-    }
2594
-
2595
-
2596
-
2597
-    /**
2598
-     * @return string
2599
-     */
2600
-    public function affiliate_id()
2601
-    {
2602
-        return ! empty($this->affiliate_id) ? $this->affiliate_id : 'default';
2603
-    }
2604
-
2605
-
2606
-
2607
-    /**
2608
-     * @return boolean
2609
-     */
2610
-    public function encode_session_data()
2611
-    {
2612
-        return filter_var($this->encode_session_data, FILTER_VALIDATE_BOOLEAN);
2613
-    }
2614
-
2615
-
2616
-
2617
-    /**
2618
-     * @param boolean $encode_session_data
2619
-     */
2620
-    public function set_encode_session_data($encode_session_data)
2621
-    {
2622
-        $this->encode_session_data = filter_var($encode_session_data, FILTER_VALIDATE_BOOLEAN);
2623
-    }
2470
+	/**
2471
+	 * @var boolean $use_personnel_manager
2472
+	 */
2473
+	public $use_personnel_manager;
2474
+
2475
+	/**
2476
+	 * @var boolean $use_dashboard_widget
2477
+	 */
2478
+	public $use_dashboard_widget;
2479
+
2480
+	/**
2481
+	 * @var int $events_in_dashboard
2482
+	 */
2483
+	public $events_in_dashboard;
2484
+
2485
+	/**
2486
+	 * @var boolean $use_event_timezones
2487
+	 */
2488
+	public $use_event_timezones;
2489
+
2490
+	/**
2491
+	 * @var boolean $use_full_logging
2492
+	 */
2493
+	public $use_full_logging;
2494
+
2495
+	/**
2496
+	 * @var string $log_file_name
2497
+	 */
2498
+	public $log_file_name;
2499
+
2500
+	/**
2501
+	 * @var string $debug_file_name
2502
+	 */
2503
+	public $debug_file_name;
2504
+
2505
+	/**
2506
+	 * @var boolean $use_remote_logging
2507
+	 */
2508
+	public $use_remote_logging;
2509
+
2510
+	/**
2511
+	 * @var string $remote_logging_url
2512
+	 */
2513
+	public $remote_logging_url;
2514
+
2515
+	/**
2516
+	 * @var boolean $show_reg_footer
2517
+	 */
2518
+	public $show_reg_footer;
2519
+
2520
+	/**
2521
+	 * @var string $affiliate_id
2522
+	 */
2523
+	public $affiliate_id;
2524
+
2525
+	/**
2526
+	 * help tours on or off (global setting)
2527
+	 *
2528
+	 * @var boolean
2529
+	 */
2530
+	public $help_tour_activation;
2531
+
2532
+	/**
2533
+	 * adds extra layer of encoding to session data to prevent serialization errors
2534
+	 * but is incompatible with some server configuration errors
2535
+	 * if you get "500 internal server errors" during registration, try turning this on
2536
+	 * if you get PHP fatal errors regarding base 64 methods not defined, then turn this off
2537
+	 *
2538
+	 * @var boolean $encode_session_data
2539
+	 */
2540
+	private $encode_session_data = false;
2541
+
2542
+
2543
+
2544
+	/**
2545
+	 *    class constructor
2546
+	 *
2547
+	 * @access    public
2548
+	 */
2549
+	public function __construct()
2550
+	{
2551
+		// set default general admin settings
2552
+		$this->use_personnel_manager = true;
2553
+		$this->use_dashboard_widget = true;
2554
+		$this->events_in_dashboard = 30;
2555
+		$this->use_event_timezones = false;
2556
+		$this->use_full_logging = false;
2557
+		$this->use_remote_logging = false;
2558
+		$this->remote_logging_url = null;
2559
+		$this->show_reg_footer = true;
2560
+		$this->affiliate_id = 'default';
2561
+		$this->help_tour_activation = true;
2562
+		$this->encode_session_data = false;
2563
+	}
2564
+
2565
+
2566
+
2567
+	/**
2568
+	 * @param bool $reset
2569
+	 * @return string
2570
+	 */
2571
+	public function log_file_name($reset = false)
2572
+	{
2573
+		if (empty($this->log_file_name) || $reset) {
2574
+			$this->log_file_name = sanitize_key('espresso_log_' . md5(uniqid('', true))) . '.txt';
2575
+			EE_Config::instance()->update_espresso_config(false, false);
2576
+		}
2577
+		return $this->log_file_name;
2578
+	}
2579
+
2580
+
2581
+
2582
+	/**
2583
+	 * @param bool $reset
2584
+	 * @return string
2585
+	 */
2586
+	public function debug_file_name($reset = false)
2587
+	{
2588
+		if (empty($this->debug_file_name) || $reset) {
2589
+			$this->debug_file_name = sanitize_key('espresso_debug_' . md5(uniqid('', true))) . '.txt';
2590
+			EE_Config::instance()->update_espresso_config(false, false);
2591
+		}
2592
+		return $this->debug_file_name;
2593
+	}
2594
+
2595
+
2596
+
2597
+	/**
2598
+	 * @return string
2599
+	 */
2600
+	public function affiliate_id()
2601
+	{
2602
+		return ! empty($this->affiliate_id) ? $this->affiliate_id : 'default';
2603
+	}
2604
+
2605
+
2606
+
2607
+	/**
2608
+	 * @return boolean
2609
+	 */
2610
+	public function encode_session_data()
2611
+	{
2612
+		return filter_var($this->encode_session_data, FILTER_VALIDATE_BOOLEAN);
2613
+	}
2614
+
2615
+
2616
+
2617
+	/**
2618
+	 * @param boolean $encode_session_data
2619
+	 */
2620
+	public function set_encode_session_data($encode_session_data)
2621
+	{
2622
+		$this->encode_session_data = filter_var($encode_session_data, FILTER_VALIDATE_BOOLEAN);
2623
+	}
2624 2624
 
2625 2625
 
2626 2626
 
@@ -2634,71 +2634,71 @@  discard block
 block discarded – undo
2634 2634
 class EE_Template_Config extends EE_Config_Base
2635 2635
 {
2636 2636
 
2637
-    /**
2638
-     * @var boolean $enable_default_style
2639
-     */
2640
-    public $enable_default_style;
2641
-
2642
-    /**
2643
-     * @var string $custom_style_sheet
2644
-     */
2645
-    public $custom_style_sheet;
2646
-
2647
-    /**
2648
-     * @var boolean $display_address_in_regform
2649
-     */
2650
-    public $display_address_in_regform;
2651
-
2652
-    /**
2653
-     * @var int $display_description_on_multi_reg_page
2654
-     */
2655
-    public $display_description_on_multi_reg_page;
2656
-
2657
-    /**
2658
-     * @var boolean $use_custom_templates
2659
-     */
2660
-    public $use_custom_templates;
2661
-
2662
-    /**
2663
-     * @var string $current_espresso_theme
2664
-     */
2665
-    public $current_espresso_theme;
2666
-
2667
-    /**
2668
-     * @var EE_Ticket_Selector_Config $EED_Ticket_Selector
2669
-     */
2670
-    public $EED_Ticket_Selector;
2671
-
2672
-    /**
2673
-     * @var EE_Event_Single_Config $EED_Event_Single
2674
-     */
2675
-    public $EED_Event_Single;
2676
-
2677
-    /**
2678
-     * @var EE_Events_Archive_Config $EED_Events_Archive
2679
-     */
2680
-    public $EED_Events_Archive;
2681
-
2682
-
2683
-
2684
-    /**
2685
-     *    class constructor
2686
-     *
2687
-     * @access    public
2688
-     */
2689
-    public function __construct()
2690
-    {
2691
-        // set default template settings
2692
-        $this->enable_default_style = true;
2693
-        $this->custom_style_sheet = null;
2694
-        $this->display_address_in_regform = true;
2695
-        $this->display_description_on_multi_reg_page = false;
2696
-        $this->use_custom_templates = false;
2697
-        $this->current_espresso_theme = 'Espresso_Arabica_2014';
2698
-        $this->EED_Event_Single = null;
2699
-        $this->EED_Events_Archive = null;
2700
-        $this->EED_Ticket_Selector = null;
2701
-    }
2637
+	/**
2638
+	 * @var boolean $enable_default_style
2639
+	 */
2640
+	public $enable_default_style;
2641
+
2642
+	/**
2643
+	 * @var string $custom_style_sheet
2644
+	 */
2645
+	public $custom_style_sheet;
2646
+
2647
+	/**
2648
+	 * @var boolean $display_address_in_regform
2649
+	 */
2650
+	public $display_address_in_regform;
2651
+
2652
+	/**
2653
+	 * @var int $display_description_on_multi_reg_page
2654
+	 */
2655
+	public $display_description_on_multi_reg_page;
2656
+
2657
+	/**
2658
+	 * @var boolean $use_custom_templates
2659
+	 */
2660
+	public $use_custom_templates;
2661
+
2662
+	/**
2663
+	 * @var string $current_espresso_theme
2664
+	 */
2665
+	public $current_espresso_theme;
2666
+
2667
+	/**
2668
+	 * @var EE_Ticket_Selector_Config $EED_Ticket_Selector
2669
+	 */
2670
+	public $EED_Ticket_Selector;
2671
+
2672
+	/**
2673
+	 * @var EE_Event_Single_Config $EED_Event_Single
2674
+	 */
2675
+	public $EED_Event_Single;
2676
+
2677
+	/**
2678
+	 * @var EE_Events_Archive_Config $EED_Events_Archive
2679
+	 */
2680
+	public $EED_Events_Archive;
2681
+
2682
+
2683
+
2684
+	/**
2685
+	 *    class constructor
2686
+	 *
2687
+	 * @access    public
2688
+	 */
2689
+	public function __construct()
2690
+	{
2691
+		// set default template settings
2692
+		$this->enable_default_style = true;
2693
+		$this->custom_style_sheet = null;
2694
+		$this->display_address_in_regform = true;
2695
+		$this->display_description_on_multi_reg_page = false;
2696
+		$this->use_custom_templates = false;
2697
+		$this->current_espresso_theme = 'Espresso_Arabica_2014';
2698
+		$this->EED_Event_Single = null;
2699
+		$this->EED_Events_Archive = null;
2700
+		$this->EED_Ticket_Selector = null;
2701
+	}
2702 2702
 
2703 2703
 }
2704 2704
 
@@ -2710,115 +2710,115 @@  discard block
 block discarded – undo
2710 2710
 class EE_Map_Config extends EE_Config_Base
2711 2711
 {
2712 2712
 
2713
-    /**
2714
-     * @var boolean $use_google_maps
2715
-     */
2716
-    public $use_google_maps;
2717
-
2718
-    /**
2719
-     * @var string $api_key
2720
-     */
2721
-    public $google_map_api_key;
2722
-
2723
-    /**
2724
-     * @var int $event_details_map_width
2725
-     */
2726
-    public $event_details_map_width;
2727
-
2728
-    /**
2729
-     * @var int $event_details_map_height
2730
-     */
2731
-    public $event_details_map_height;
2732
-
2733
-    /**
2734
-     * @var int $event_details_map_zoom
2735
-     */
2736
-    public $event_details_map_zoom;
2737
-
2738
-    /**
2739
-     * @var boolean $event_details_display_nav
2740
-     */
2741
-    public $event_details_display_nav;
2742
-
2743
-    /**
2744
-     * @var boolean $event_details_nav_size
2745
-     */
2746
-    public $event_details_nav_size;
2747
-
2748
-    /**
2749
-     * @var string $event_details_control_type
2750
-     */
2751
-    public $event_details_control_type;
2752
-
2753
-    /**
2754
-     * @var string $event_details_map_align
2755
-     */
2756
-    public $event_details_map_align;
2757
-
2758
-    /**
2759
-     * @var int $event_list_map_width
2760
-     */
2761
-    public $event_list_map_width;
2762
-
2763
-    /**
2764
-     * @var int $event_list_map_height
2765
-     */
2766
-    public $event_list_map_height;
2767
-
2768
-    /**
2769
-     * @var int $event_list_map_zoom
2770
-     */
2771
-    public $event_list_map_zoom;
2772
-
2773
-    /**
2774
-     * @var boolean $event_list_display_nav
2775
-     */
2776
-    public $event_list_display_nav;
2777
-
2778
-    /**
2779
-     * @var boolean $event_list_nav_size
2780
-     */
2781
-    public $event_list_nav_size;
2782
-
2783
-    /**
2784
-     * @var string $event_list_control_type
2785
-     */
2786
-    public $event_list_control_type;
2787
-
2788
-    /**
2789
-     * @var string $event_list_map_align
2790
-     */
2791
-    public $event_list_map_align;
2792
-
2793
-
2794
-
2795
-    /**
2796
-     *    class constructor
2797
-     *
2798
-     * @access    public
2799
-     */
2800
-    public function __construct()
2801
-    {
2802
-        // set default map settings
2803
-        $this->use_google_maps = true;
2804
-        $this->google_map_api_key = '';
2805
-        // for event details pages (reg page)
2806
-        $this->event_details_map_width = 585;            // ee_map_width_single
2807
-        $this->event_details_map_height = 362;            // ee_map_height_single
2808
-        $this->event_details_map_zoom = 14;            // ee_map_zoom_single
2809
-        $this->event_details_display_nav = true;            // ee_map_nav_display_single
2810
-        $this->event_details_nav_size = false;            // ee_map_nav_size_single
2811
-        $this->event_details_control_type = 'default';        // ee_map_type_control_single
2812
-        $this->event_details_map_align = 'center';            // ee_map_align_single
2813
-        // for event list pages
2814
-        $this->event_list_map_width = 300;            // ee_map_width
2815
-        $this->event_list_map_height = 185;        // ee_map_height
2816
-        $this->event_list_map_zoom = 12;            // ee_map_zoom
2817
-        $this->event_list_display_nav = false;        // ee_map_nav_display
2818
-        $this->event_list_nav_size = true;            // ee_map_nav_size
2819
-        $this->event_list_control_type = 'dropdown';        // ee_map_type_control
2820
-        $this->event_list_map_align = 'center';            // ee_map_align
2821
-    }
2713
+	/**
2714
+	 * @var boolean $use_google_maps
2715
+	 */
2716
+	public $use_google_maps;
2717
+
2718
+	/**
2719
+	 * @var string $api_key
2720
+	 */
2721
+	public $google_map_api_key;
2722
+
2723
+	/**
2724
+	 * @var int $event_details_map_width
2725
+	 */
2726
+	public $event_details_map_width;
2727
+
2728
+	/**
2729
+	 * @var int $event_details_map_height
2730
+	 */
2731
+	public $event_details_map_height;
2732
+
2733
+	/**
2734
+	 * @var int $event_details_map_zoom
2735
+	 */
2736
+	public $event_details_map_zoom;
2737
+
2738
+	/**
2739
+	 * @var boolean $event_details_display_nav
2740
+	 */
2741
+	public $event_details_display_nav;
2742
+
2743
+	/**
2744
+	 * @var boolean $event_details_nav_size
2745
+	 */
2746
+	public $event_details_nav_size;
2747
+
2748
+	/**
2749
+	 * @var string $event_details_control_type
2750
+	 */
2751
+	public $event_details_control_type;
2752
+
2753
+	/**
2754
+	 * @var string $event_details_map_align
2755
+	 */
2756
+	public $event_details_map_align;
2757
+
2758
+	/**
2759
+	 * @var int $event_list_map_width
2760
+	 */
2761
+	public $event_list_map_width;
2762
+
2763
+	/**
2764
+	 * @var int $event_list_map_height
2765
+	 */
2766
+	public $event_list_map_height;
2767
+
2768
+	/**
2769
+	 * @var int $event_list_map_zoom
2770
+	 */
2771
+	public $event_list_map_zoom;
2772
+
2773
+	/**
2774
+	 * @var boolean $event_list_display_nav
2775
+	 */
2776
+	public $event_list_display_nav;
2777
+
2778
+	/**
2779
+	 * @var boolean $event_list_nav_size
2780
+	 */
2781
+	public $event_list_nav_size;
2782
+
2783
+	/**
2784
+	 * @var string $event_list_control_type
2785
+	 */
2786
+	public $event_list_control_type;
2787
+
2788
+	/**
2789
+	 * @var string $event_list_map_align
2790
+	 */
2791
+	public $event_list_map_align;
2792
+
2793
+
2794
+
2795
+	/**
2796
+	 *    class constructor
2797
+	 *
2798
+	 * @access    public
2799
+	 */
2800
+	public function __construct()
2801
+	{
2802
+		// set default map settings
2803
+		$this->use_google_maps = true;
2804
+		$this->google_map_api_key = '';
2805
+		// for event details pages (reg page)
2806
+		$this->event_details_map_width = 585;            // ee_map_width_single
2807
+		$this->event_details_map_height = 362;            // ee_map_height_single
2808
+		$this->event_details_map_zoom = 14;            // ee_map_zoom_single
2809
+		$this->event_details_display_nav = true;            // ee_map_nav_display_single
2810
+		$this->event_details_nav_size = false;            // ee_map_nav_size_single
2811
+		$this->event_details_control_type = 'default';        // ee_map_type_control_single
2812
+		$this->event_details_map_align = 'center';            // ee_map_align_single
2813
+		// for event list pages
2814
+		$this->event_list_map_width = 300;            // ee_map_width
2815
+		$this->event_list_map_height = 185;        // ee_map_height
2816
+		$this->event_list_map_zoom = 12;            // ee_map_zoom
2817
+		$this->event_list_display_nav = false;        // ee_map_nav_display
2818
+		$this->event_list_nav_size = true;            // ee_map_nav_size
2819
+		$this->event_list_control_type = 'dropdown';        // ee_map_type_control
2820
+		$this->event_list_map_align = 'center';            // ee_map_align
2821
+	}
2822 2822
 
2823 2823
 }
2824 2824
 
@@ -2830,47 +2830,47 @@  discard block
 block discarded – undo
2830 2830
 class EE_Events_Archive_Config extends EE_Config_Base
2831 2831
 {
2832 2832
 
2833
-    public $display_status_banner;
2833
+	public $display_status_banner;
2834 2834
 
2835
-    public $display_description;
2835
+	public $display_description;
2836 2836
 
2837
-    public $display_ticket_selector;
2837
+	public $display_ticket_selector;
2838 2838
 
2839
-    public $display_datetimes;
2839
+	public $display_datetimes;
2840 2840
 
2841
-    public $display_venue;
2841
+	public $display_venue;
2842 2842
 
2843
-    public $display_expired_events;
2843
+	public $display_expired_events;
2844 2844
 
2845
-    public $use_sortable_display_order;
2845
+	public $use_sortable_display_order;
2846 2846
 
2847
-    public $display_order_tickets;
2847
+	public $display_order_tickets;
2848 2848
 
2849
-    public $display_order_datetimes;
2849
+	public $display_order_datetimes;
2850 2850
 
2851
-    public $display_order_event;
2851
+	public $display_order_event;
2852 2852
 
2853
-    public $display_order_venue;
2853
+	public $display_order_venue;
2854 2854
 
2855 2855
 
2856 2856
 
2857
-    /**
2858
-     *    class constructor
2859
-     */
2860
-    public function __construct()
2861
-    {
2862
-        $this->display_status_banner = 0;
2863
-        $this->display_description = 1;
2864
-        $this->display_ticket_selector = 0;
2865
-        $this->display_datetimes = 1;
2866
-        $this->display_venue = 0;
2867
-        $this->display_expired_events = 0;
2868
-        $this->use_sortable_display_order = false;
2869
-        $this->display_order_tickets = 100;
2870
-        $this->display_order_datetimes = 110;
2871
-        $this->display_order_event = 120;
2872
-        $this->display_order_venue = 130;
2873
-    }
2857
+	/**
2858
+	 *    class constructor
2859
+	 */
2860
+	public function __construct()
2861
+	{
2862
+		$this->display_status_banner = 0;
2863
+		$this->display_description = 1;
2864
+		$this->display_ticket_selector = 0;
2865
+		$this->display_datetimes = 1;
2866
+		$this->display_venue = 0;
2867
+		$this->display_expired_events = 0;
2868
+		$this->use_sortable_display_order = false;
2869
+		$this->display_order_tickets = 100;
2870
+		$this->display_order_datetimes = 110;
2871
+		$this->display_order_event = 120;
2872
+		$this->display_order_venue = 130;
2873
+	}
2874 2874
 }
2875 2875
 
2876 2876
 
@@ -2881,35 +2881,35 @@  discard block
 block discarded – undo
2881 2881
 class EE_Event_Single_Config extends EE_Config_Base
2882 2882
 {
2883 2883
 
2884
-    public $display_status_banner_single;
2884
+	public $display_status_banner_single;
2885 2885
 
2886
-    public $display_venue;
2886
+	public $display_venue;
2887 2887
 
2888
-    public $use_sortable_display_order;
2888
+	public $use_sortable_display_order;
2889 2889
 
2890
-    public $display_order_tickets;
2890
+	public $display_order_tickets;
2891 2891
 
2892
-    public $display_order_datetimes;
2892
+	public $display_order_datetimes;
2893 2893
 
2894
-    public $display_order_event;
2894
+	public $display_order_event;
2895 2895
 
2896
-    public $display_order_venue;
2896
+	public $display_order_venue;
2897 2897
 
2898 2898
 
2899 2899
 
2900
-    /**
2901
-     *    class constructor
2902
-     */
2903
-    public function __construct()
2904
-    {
2905
-        $this->display_status_banner_single = 0;
2906
-        $this->display_venue = 1;
2907
-        $this->use_sortable_display_order = false;
2908
-        $this->display_order_tickets = 100;
2909
-        $this->display_order_datetimes = 110;
2910
-        $this->display_order_event = 120;
2911
-        $this->display_order_venue = 130;
2912
-    }
2900
+	/**
2901
+	 *    class constructor
2902
+	 */
2903
+	public function __construct()
2904
+	{
2905
+		$this->display_status_banner_single = 0;
2906
+		$this->display_venue = 1;
2907
+		$this->use_sortable_display_order = false;
2908
+		$this->display_order_tickets = 100;
2909
+		$this->display_order_datetimes = 110;
2910
+		$this->display_order_event = 120;
2911
+		$this->display_order_venue = 130;
2912
+	}
2913 2913
 }
2914 2914
 
2915 2915
 
@@ -2920,152 +2920,152 @@  discard block
 block discarded – undo
2920 2920
 class EE_Ticket_Selector_Config extends EE_Config_Base
2921 2921
 {
2922 2922
 
2923
-    /**
2924
-     * constant to indicate that a datetime selector should NEVER be shown for ticket selectors
2925
-     */
2926
-    const DO_NOT_SHOW_DATETIME_SELECTOR = 'no_datetime_selector';
2927
-
2928
-    /**
2929
-     * constant to indicate that a datetime selector should only be shown for ticket selectors
2930
-     * when the number of datetimes for the event matches the value set for $datetime_selector_threshold
2931
-     */
2932
-    const MAYBE_SHOW_DATETIME_SELECTOR = 'maybe_datetime_selector';
2933
-
2934
-    /**
2935
-     * @var boolean $show_ticket_sale_columns
2936
-     */
2937
-    public $show_ticket_sale_columns;
2938
-
2939
-    /**
2940
-     * @var boolean $show_ticket_details
2941
-     */
2942
-    public $show_ticket_details;
2943
-
2944
-    /**
2945
-     * @var boolean $show_expired_tickets
2946
-     */
2947
-    public $show_expired_tickets;
2948
-
2949
-    /**
2950
-     * whether or not to display a dropdown box populated with event datetimes
2951
-     * that toggles which tickets are displayed for a ticket selector.
2952
-     * uses one of the *_DATETIME_SELECTOR constants defined above
2953
-     *
2954
-     * @var string $show_datetime_selector
2955
-     */
2956
-    private $show_datetime_selector = 'no_datetime_selector';
2957
-
2958
-    /**
2959
-     * the number of datetimes an event has to have before conditionally displaying a datetime selector
2960
-     *
2961
-     * @var int $datetime_selector_threshold
2962
-     */
2963
-    private $datetime_selector_threshold = 3;
2964
-
2965
-
2966
-
2967
-    /**
2968
-     *    class constructor
2969
-     */
2970
-    public function __construct()
2971
-    {
2972
-        $this->show_ticket_sale_columns = true;
2973
-        $this->show_ticket_details = true;
2974
-        $this->show_expired_tickets = true;
2975
-        $this->show_datetime_selector = \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
2976
-        $this->datetime_selector_threshold = 3;
2977
-    }
2978
-
2979
-
2980
-
2981
-    /**
2982
-     * returns true if a datetime selector should be displayed
2983
-     *
2984
-     * @param array $datetimes
2985
-     * @return bool
2986
-     */
2987
-    public function showDatetimeSelector(array $datetimes)
2988
-    {
2989
-        // if the settings are NOT: don't show OR below threshold, THEN active = true
2990
-        return ! (
2991
-            $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
2992
-            || (
2993
-                $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR
2994
-                && count($datetimes) < $this->getDatetimeSelectorThreshold()
2995
-            )
2996
-        );
2997
-    }
2998
-
2999
-
3000
-
3001
-    /**
3002
-     * @return string
3003
-     */
3004
-    public function getShowDatetimeSelector()
3005
-    {
3006
-        return $this->show_datetime_selector;
3007
-    }
3008
-
3009
-
3010
-
3011
-    /**
3012
-     * @param bool $keys_only
3013
-     * @return array
3014
-     */
3015
-    public function getShowDatetimeSelectorOptions($keys_only = true)
3016
-    {
3017
-        return $keys_only
3018
-            ? array(
3019
-                \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
3020
-                \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR,
3021
-            )
3022
-            : array(
3023
-                \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR => esc_html__(
3024
-                    'Do not show date & time filter', 'event_espresso'
3025
-                ),
3026
-                \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR  => esc_html__(
3027
-                    'Maybe show date & time filter', 'event_espresso'
3028
-                ),
3029
-            );
3030
-    }
3031
-
3032
-
3033
-
3034
-    /**
3035
-     * @param string $show_datetime_selector
3036
-     */
3037
-    public function setShowDatetimeSelector($show_datetime_selector)
3038
-    {
3039
-        $this->show_datetime_selector = in_array(
3040
-            $show_datetime_selector,
3041
-            $this->getShowDatetimeSelectorOptions(),
3042
-            true
3043
-        )
3044
-            ? $show_datetime_selector
3045
-            : \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3046
-    }
3047
-
3048
-
3049
-
3050
-    /**
3051
-     * @return int
3052
-     */
3053
-    public function getDatetimeSelectorThreshold()
3054
-    {
3055
-        return $this->datetime_selector_threshold;
3056
-    }
3057
-
3058
-
3059
-
3060
-
3061
-    /**
3062
-     * @param int $datetime_selector_threshold
3063
-     */
3064
-    public function setDatetimeSelectorThreshold($datetime_selector_threshold)
3065
-    {
3066
-        $datetime_selector_threshold = absint($datetime_selector_threshold);
3067
-        $this->datetime_selector_threshold = $datetime_selector_threshold ? $datetime_selector_threshold : 3;
3068
-    }
2923
+	/**
2924
+	 * constant to indicate that a datetime selector should NEVER be shown for ticket selectors
2925
+	 */
2926
+	const DO_NOT_SHOW_DATETIME_SELECTOR = 'no_datetime_selector';
2927
+
2928
+	/**
2929
+	 * constant to indicate that a datetime selector should only be shown for ticket selectors
2930
+	 * when the number of datetimes for the event matches the value set for $datetime_selector_threshold
2931
+	 */
2932
+	const MAYBE_SHOW_DATETIME_SELECTOR = 'maybe_datetime_selector';
2933
+
2934
+	/**
2935
+	 * @var boolean $show_ticket_sale_columns
2936
+	 */
2937
+	public $show_ticket_sale_columns;
2938
+
2939
+	/**
2940
+	 * @var boolean $show_ticket_details
2941
+	 */
2942
+	public $show_ticket_details;
2943
+
2944
+	/**
2945
+	 * @var boolean $show_expired_tickets
2946
+	 */
2947
+	public $show_expired_tickets;
2948
+
2949
+	/**
2950
+	 * whether or not to display a dropdown box populated with event datetimes
2951
+	 * that toggles which tickets are displayed for a ticket selector.
2952
+	 * uses one of the *_DATETIME_SELECTOR constants defined above
2953
+	 *
2954
+	 * @var string $show_datetime_selector
2955
+	 */
2956
+	private $show_datetime_selector = 'no_datetime_selector';
2957
+
2958
+	/**
2959
+	 * the number of datetimes an event has to have before conditionally displaying a datetime selector
2960
+	 *
2961
+	 * @var int $datetime_selector_threshold
2962
+	 */
2963
+	private $datetime_selector_threshold = 3;
2964
+
2965
+
2966
+
2967
+	/**
2968
+	 *    class constructor
2969
+	 */
2970
+	public function __construct()
2971
+	{
2972
+		$this->show_ticket_sale_columns = true;
2973
+		$this->show_ticket_details = true;
2974
+		$this->show_expired_tickets = true;
2975
+		$this->show_datetime_selector = \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
2976
+		$this->datetime_selector_threshold = 3;
2977
+	}
2978
+
2979
+
2980
+
2981
+	/**
2982
+	 * returns true if a datetime selector should be displayed
2983
+	 *
2984
+	 * @param array $datetimes
2985
+	 * @return bool
2986
+	 */
2987
+	public function showDatetimeSelector(array $datetimes)
2988
+	{
2989
+		// if the settings are NOT: don't show OR below threshold, THEN active = true
2990
+		return ! (
2991
+			$this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
2992
+			|| (
2993
+				$this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR
2994
+				&& count($datetimes) < $this->getDatetimeSelectorThreshold()
2995
+			)
2996
+		);
2997
+	}
2998
+
2999
+
3000
+
3001
+	/**
3002
+	 * @return string
3003
+	 */
3004
+	public function getShowDatetimeSelector()
3005
+	{
3006
+		return $this->show_datetime_selector;
3007
+	}
3008
+
3009
+
3010
+
3011
+	/**
3012
+	 * @param bool $keys_only
3013
+	 * @return array
3014
+	 */
3015
+	public function getShowDatetimeSelectorOptions($keys_only = true)
3016
+	{
3017
+		return $keys_only
3018
+			? array(
3019
+				\EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
3020
+				\EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR,
3021
+			)
3022
+			: array(
3023
+				\EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR => esc_html__(
3024
+					'Do not show date & time filter', 'event_espresso'
3025
+				),
3026
+				\EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR  => esc_html__(
3027
+					'Maybe show date & time filter', 'event_espresso'
3028
+				),
3029
+			);
3030
+	}
3031
+
3032
+
3033
+
3034
+	/**
3035
+	 * @param string $show_datetime_selector
3036
+	 */
3037
+	public function setShowDatetimeSelector($show_datetime_selector)
3038
+	{
3039
+		$this->show_datetime_selector = in_array(
3040
+			$show_datetime_selector,
3041
+			$this->getShowDatetimeSelectorOptions(),
3042
+			true
3043
+		)
3044
+			? $show_datetime_selector
3045
+			: \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3046
+	}
3047
+
3048
+
3049
+
3050
+	/**
3051
+	 * @return int
3052
+	 */
3053
+	public function getDatetimeSelectorThreshold()
3054
+	{
3055
+		return $this->datetime_selector_threshold;
3056
+	}
3057
+
3058
+
3059
+
3060
+
3061
+	/**
3062
+	 * @param int $datetime_selector_threshold
3063
+	 */
3064
+	public function setDatetimeSelectorThreshold($datetime_selector_threshold)
3065
+	{
3066
+		$datetime_selector_threshold = absint($datetime_selector_threshold);
3067
+		$this->datetime_selector_threshold = $datetime_selector_threshold ? $datetime_selector_threshold : 3;
3068
+	}
3069 3069
 
3070 3070
 
3071 3071
 
@@ -3083,85 +3083,85 @@  discard block
 block discarded – undo
3083 3083
 class EE_Environment_Config extends EE_Config_Base
3084 3084
 {
3085 3085
 
3086
-    /**
3087
-     * Hold any php environment variables that we want to track.
3088
-     *
3089
-     * @var stdClass;
3090
-     */
3091
-    public $php;
3092
-
3093
-
3094
-
3095
-    /**
3096
-     *    constructor
3097
-     */
3098
-    public function __construct()
3099
-    {
3100
-        $this->php = new stdClass();
3101
-        $this->_set_php_values();
3102
-    }
3103
-
3104
-
3105
-
3106
-    /**
3107
-     * This sets the php environment variables.
3108
-     *
3109
-     * @since 4.4.0
3110
-     * @return void
3111
-     */
3112
-    protected function _set_php_values()
3113
-    {
3114
-        $this->php->max_input_vars = ini_get('max_input_vars');
3115
-        $this->php->version = phpversion();
3116
-    }
3117
-
3118
-
3119
-
3120
-    /**
3121
-     * helper method for determining whether input_count is
3122
-     * reaching the potential maximum the server can handle
3123
-     * according to max_input_vars
3124
-     *
3125
-     * @param int   $input_count the count of input vars.
3126
-     * @return array {
3127
-     *                           An array that represents whether available space and if no available space the error
3128
-     *                           message.
3129
-     * @type bool   $has_space   whether more inputs can be added.
3130
-     * @type string $msg         Any message to be displayed.
3131
-     *                           }
3132
-     */
3133
-    public function max_input_vars_limit_check($input_count = 0)
3134
-    {
3135
-        if (! empty($this->php->max_input_vars)
3136
-            && ($input_count >= $this->php->max_input_vars)
3137
-            && (PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9)
3138
-        ) {
3139
-            return sprintf(
3140
-                __(
3141
-                    'The maximum number of inputs on this page has been exceeded.  You cannot add anymore items (i.e. tickets, datetimes, custom fields) on this page because of your servers PHP "max_input_vars" setting.%1$sThere are %2$d inputs and the maximum amount currently allowed by your server is %3$d.',
3142
-                    'event_espresso'
3143
-                ),
3144
-                '<br>',
3145
-                $input_count,
3146
-                $this->php->max_input_vars
3147
-            );
3148
-        } else {
3149
-            return '';
3150
-        }
3151
-    }
3152
-
3153
-
3154
-
3155
-    /**
3156
-     * The purpose of this method is just to force rechecking php values so if they've changed, they get updated.
3157
-     *
3158
-     * @since 4.4.1
3159
-     * @return void
3160
-     */
3161
-    public function recheck_values()
3162
-    {
3163
-        $this->_set_php_values();
3164
-    }
3086
+	/**
3087
+	 * Hold any php environment variables that we want to track.
3088
+	 *
3089
+	 * @var stdClass;
3090
+	 */
3091
+	public $php;
3092
+
3093
+
3094
+
3095
+	/**
3096
+	 *    constructor
3097
+	 */
3098
+	public function __construct()
3099
+	{
3100
+		$this->php = new stdClass();
3101
+		$this->_set_php_values();
3102
+	}
3103
+
3104
+
3105
+
3106
+	/**
3107
+	 * This sets the php environment variables.
3108
+	 *
3109
+	 * @since 4.4.0
3110
+	 * @return void
3111
+	 */
3112
+	protected function _set_php_values()
3113
+	{
3114
+		$this->php->max_input_vars = ini_get('max_input_vars');
3115
+		$this->php->version = phpversion();
3116
+	}
3117
+
3118
+
3119
+
3120
+	/**
3121
+	 * helper method for determining whether input_count is
3122
+	 * reaching the potential maximum the server can handle
3123
+	 * according to max_input_vars
3124
+	 *
3125
+	 * @param int   $input_count the count of input vars.
3126
+	 * @return array {
3127
+	 *                           An array that represents whether available space and if no available space the error
3128
+	 *                           message.
3129
+	 * @type bool   $has_space   whether more inputs can be added.
3130
+	 * @type string $msg         Any message to be displayed.
3131
+	 *                           }
3132
+	 */
3133
+	public function max_input_vars_limit_check($input_count = 0)
3134
+	{
3135
+		if (! empty($this->php->max_input_vars)
3136
+			&& ($input_count >= $this->php->max_input_vars)
3137
+			&& (PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9)
3138
+		) {
3139
+			return sprintf(
3140
+				__(
3141
+					'The maximum number of inputs on this page has been exceeded.  You cannot add anymore items (i.e. tickets, datetimes, custom fields) on this page because of your servers PHP "max_input_vars" setting.%1$sThere are %2$d inputs and the maximum amount currently allowed by your server is %3$d.',
3142
+					'event_espresso'
3143
+				),
3144
+				'<br>',
3145
+				$input_count,
3146
+				$this->php->max_input_vars
3147
+			);
3148
+		} else {
3149
+			return '';
3150
+		}
3151
+	}
3152
+
3153
+
3154
+
3155
+	/**
3156
+	 * The purpose of this method is just to force rechecking php values so if they've changed, they get updated.
3157
+	 *
3158
+	 * @since 4.4.1
3159
+	 * @return void
3160
+	 */
3161
+	public function recheck_values()
3162
+	{
3163
+		$this->_set_php_values();
3164
+	}
3165 3165
 
3166 3166
 
3167 3167
 
@@ -3179,22 +3179,22 @@  discard block
 block discarded – undo
3179 3179
 class EE_Tax_Config extends EE_Config_Base
3180 3180
 {
3181 3181
 
3182
-    /*
3182
+	/*
3183 3183
      * flag to indicate whether or not to display ticket prices with the taxes included
3184 3184
      *
3185 3185
      * @var boolean $prices_displayed_including_taxes
3186 3186
      */
3187
-    public $prices_displayed_including_taxes;
3187
+	public $prices_displayed_including_taxes;
3188 3188
 
3189 3189
 
3190 3190
 
3191
-    /**
3192
-     *    class constructor
3193
-     */
3194
-    public function __construct()
3195
-    {
3196
-        $this->prices_displayed_including_taxes = true;
3197
-    }
3191
+	/**
3192
+	 *    class constructor
3193
+	 */
3194
+	public function __construct()
3195
+	{
3196
+		$this->prices_displayed_including_taxes = true;
3197
+	}
3198 3198
 }
3199 3199
 
3200 3200
 
@@ -3209,17 +3209,17 @@  discard block
 block discarded – undo
3209 3209
 class EE_Messages_Config extends EE_Config_Base
3210 3210
 {
3211 3211
 
3212
-    /**
3213
-     * This is an integer representing the deletion threshold in months for when old messages will get deleted.
3214
-     * A value of 0 represents never deleting.  Default is 0.
3215
-     *
3216
-     * @var integer
3217
-     */
3218
-    public $delete_threshold;
3219
-
3220
-    public function __construct() {
3221
-        $this->delete_threshold = 0;
3222
-    }
3212
+	/**
3213
+	 * This is an integer representing the deletion threshold in months for when old messages will get deleted.
3214
+	 * A value of 0 represents never deleting.  Default is 0.
3215
+	 *
3216
+	 * @var integer
3217
+	 */
3218
+	public $delete_threshold;
3219
+
3220
+	public function __construct() {
3221
+		$this->delete_threshold = 0;
3222
+	}
3223 3223
 }
3224 3224
 
3225 3225
 
@@ -3231,34 +3231,34 @@  discard block
 block discarded – undo
3231 3231
 class EE_Gateway_Config extends EE_Config_Base
3232 3232
 {
3233 3233
 
3234
-    /**
3235
-     * Array with keys that are payment gateways slugs, and values are arrays
3236
-     * with any config info the gateway wants to store
3237
-     *
3238
-     * @var array
3239
-     */
3240
-    public $payment_settings;
3241
-
3242
-    /**
3243
-     * Where keys are gateway slugs, and values are booleans indicating whether or not
3244
-     * the gateway is stored in the uploads directory
3245
-     *
3246
-     * @var array
3247
-     */
3248
-    public $active_gateways;
3249
-
3250
-
3251
-
3252
-    /**
3253
-     *    class constructor
3254
-     *
3255
-     * @deprecated
3256
-     */
3257
-    public function __construct()
3258
-    {
3259
-        $this->payment_settings = array();
3260
-        $this->active_gateways = array('Invoice' => false);
3261
-    }
3234
+	/**
3235
+	 * Array with keys that are payment gateways slugs, and values are arrays
3236
+	 * with any config info the gateway wants to store
3237
+	 *
3238
+	 * @var array
3239
+	 */
3240
+	public $payment_settings;
3241
+
3242
+	/**
3243
+	 * Where keys are gateway slugs, and values are booleans indicating whether or not
3244
+	 * the gateway is stored in the uploads directory
3245
+	 *
3246
+	 * @var array
3247
+	 */
3248
+	public $active_gateways;
3249
+
3250
+
3251
+
3252
+	/**
3253
+	 *    class constructor
3254
+	 *
3255
+	 * @deprecated
3256
+	 */
3257
+	public function __construct()
3258
+	{
3259
+		$this->payment_settings = array();
3260
+		$this->active_gateways = array('Invoice' => false);
3261
+	}
3262 3262
 }
3263 3263
 
3264 3264
 // End of file EE_Config.core.php
Please login to merge, or discard this patch.
core/EE_Cart.core.php 1 patch
Indentation   +413 added lines, -413 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\interfaces\ResettableInterface;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 do_action('AHEE_log', __FILE__, __FUNCTION__, '');
8 8
 
@@ -23,418 +23,418 @@  discard block
 block discarded – undo
23 23
 class EE_Cart implements ResettableInterface
24 24
 {
25 25
 
26
-    /**
27
-     * instance of the EE_Cart object
28
-     *
29
-     * @access    private
30
-     * @var EE_Cart $_instance
31
-     */
32
-    private static $_instance;
33
-
34
-    /**
35
-     * instance of the EE_Session object
36
-     *
37
-     * @access    protected
38
-     * @var EE_Session $_session
39
-     */
40
-    protected $_session;
41
-
42
-    /**
43
-     * The total Line item which comprises all the children line-item subtotals,
44
-     * which in turn each have their line items.
45
-     * Typically, the line item structure will look like:
46
-     * grand total
47
-     * -tickets-sub-total
48
-     * --ticket1
49
-     * --ticket2
50
-     * --...
51
-     * -taxes-sub-total
52
-     * --tax1
53
-     * --tax2
54
-     *
55
-     * @var EE_Line_Item
56
-     */
57
-    private $_grand_total;
58
-
59
-
60
-
61
-    /**
62
-     * @singleton method used to instantiate class object
63
-     * @access    public
64
-     * @param EE_Line_Item $grand_total
65
-     * @param EE_Session   $session
66
-     * @return \EE_Cart
67
-     * @throws \EE_Error
68
-     */
69
-    public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
70
-    {
71
-        if ( ! empty($grand_total)) {
72
-            self::$_instance = new self($grand_total, $session);
73
-        }
74
-        // or maybe retrieve an existing one ?
75
-        if ( ! self::$_instance instanceof EE_Cart) {
76
-            // try getting the cart out of the session
77
-            $saved_cart = $session instanceof EE_Session ? $session->cart() : null;
78
-            self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
79
-            unset($saved_cart);
80
-        }
81
-        // verify that cart is ok and grand total line item exists
82
-        if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
83
-            self::$_instance = new self($grand_total, $session);
84
-        }
85
-        self::$_instance->get_grand_total();
86
-        // once everything is all said and done, save the cart to the EE_Session
87
-        add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
88
-        return self::$_instance;
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * private constructor to prevent direct creation
95
-     *
96
-     * @Constructor
97
-     * @access private
98
-     * @param EE_Line_Item $grand_total
99
-     * @param EE_Session   $session
100
-     */
101
-    private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
102
-    {
103
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
104
-        $this->set_session($session);
105
-        if ($grand_total instanceof EE_Line_Item) {
106
-            $this->set_grand_total_line_item($grand_total);
107
-        }
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * Resets the cart completely (whereas empty_cart
114
-     *
115
-     * @param EE_Line_Item $grand_total
116
-     * @param EE_Session   $session
117
-     * @return EE_Cart
118
-     * @throws \EE_Error
119
-     */
120
-    public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
121
-    {
122
-        remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
123
-        if ($session instanceof EE_Session) {
124
-            $session->reset_cart();
125
-        }
126
-        self::$_instance = null;
127
-        return self::instance($grand_total, $session);
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * @return \EE_Session
134
-     */
135
-    public function session()
136
-    {
137
-        if ( ! $this->_session instanceof EE_Session) {
138
-            $this->set_session();
139
-        }
140
-        return $this->_session;
141
-    }
142
-
143
-
144
-
145
-    /**
146
-     * @param EE_Session $session
147
-     */
148
-    public function set_session(EE_Session $session = null)
149
-    {
150
-        $this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * Sets the cart to match the line item. Especially handy for loading an old cart where you
157
-     *  know the grand total line item on it
158
-     *
159
-     * @param EE_Line_Item $line_item
160
-     */
161
-    public function set_grand_total_line_item(EE_Line_Item $line_item)
162
-    {
163
-        $this->_grand_total = $line_item;
164
-    }
165
-
166
-
167
-
168
-    /**
169
-     * get_cart_from_reg_url_link
170
-     *
171
-     * @access public
172
-     * @param EE_Transaction $transaction
173
-     * @param EE_Session     $session
174
-     * @return \EE_Cart
175
-     * @throws \EE_Error
176
-     */
177
-    public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
178
-    {
179
-        $grand_total = $transaction->total_line_item();
180
-        $grand_total->get_items();
181
-        $grand_total->tax_descendants();
182
-        return EE_Cart::instance($grand_total, $session);
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
189
-     *
190
-     * @return EE_Line_Item
191
-     * @throws \EE_Error
192
-     */
193
-    private function _create_grand_total()
194
-    {
195
-        $this->_grand_total = EEH_Line_Item::create_total_line_item();
196
-        return $this->_grand_total;
197
-    }
198
-
199
-
200
-
201
-    /**
202
-     * Gets all the line items of object type Ticket
203
-     *
204
-     * @access public
205
-     * @return \EE_Line_Item[]
206
-     */
207
-    public function get_tickets()
208
-    {
209
-        if ($this->_grand_total === null ) {
210
-            return array();
211
-        }
212
-        return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
213
-    }
214
-
215
-
216
-
217
-    /**
218
-     * returns the total quantity of tickets in the cart
219
-     *
220
-     * @access public
221
-     * @return int
222
-     * @throws \EE_Error
223
-     */
224
-    public function all_ticket_quantity_count()
225
-    {
226
-        $tickets = $this->get_tickets();
227
-        if (empty($tickets)) {
228
-            return 0;
229
-        }
230
-        $count = 0;
231
-        foreach ($tickets as $ticket) {
232
-            $count += $ticket->get('LIN_quantity');
233
-        }
234
-        return $count;
235
-    }
236
-
237
-
238
-
239
-    /**
240
-     * Gets all the tax line items
241
-     *
242
-     * @return \EE_Line_Item[]
243
-     * @throws \EE_Error
244
-     */
245
-    public function get_taxes()
246
-    {
247
-        return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
248
-    }
249
-
250
-
251
-
252
-    /**
253
-     * Gets the total line item (which is a parent of all other line items) on this cart
254
-     *
255
-     * @return EE_Line_Item
256
-     * @throws \EE_Error
257
-     */
258
-    public function get_grand_total()
259
-    {
260
-        return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     * @process items for adding to cart
267
-     * @access  public
268
-     * @param EE_Ticket $ticket
269
-     * @param int       $qty
270
-     * @return TRUE on success, FALSE on fail
271
-     * @throws \EE_Error
272
-     */
273
-    public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
274
-    {
275
-        EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
276
-        return $this->save_cart() ? true : false;
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * get_cart_total_before_tax
283
-     *
284
-     * @access public
285
-     * @return float
286
-     * @throws \EE_Error
287
-     */
288
-    public function get_cart_total_before_tax()
289
-    {
290
-        return $this->get_grand_total()->recalculate_pre_tax_total();
291
-    }
292
-
293
-
294
-
295
-    /**
296
-     * gets the total amount of tax paid for items in this cart
297
-     *
298
-     * @access public
299
-     * @return float
300
-     * @throws \EE_Error
301
-     */
302
-    public function get_applied_taxes()
303
-    {
304
-        return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
305
-    }
306
-
307
-
308
-
309
-    /**
310
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
311
-     *
312
-     * @access public
313
-     * @return float
314
-     * @throws \EE_Error
315
-     */
316
-    public function get_cart_grand_total()
317
-    {
318
-        EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
319
-        return $this->get_grand_total()->total();
320
-    }
321
-
322
-
323
-
324
-    /**
325
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
326
-     *
327
-     * @access public
328
-     * @return float
329
-     * @throws \EE_Error
330
-     */
331
-    public function recalculate_all_cart_totals()
332
-    {
333
-        $pre_tax_total = $this->get_cart_total_before_tax();
334
-        $taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
335
-        $this->_grand_total->set_total($pre_tax_total + $taxes_total);
336
-        $this->_grand_total->save_this_and_descendants_to_txn();
337
-        return $this->get_grand_total()->total();
338
-    }
339
-
340
-
341
-
342
-    /**
343
-     * deletes an item from the cart
344
-     *
345
-     * @access public
346
-     * @param array|bool|string $line_item_codes
347
-     * @return int on success, FALSE on fail
348
-     * @throws \EE_Error
349
-     */
350
-    public function delete_items($line_item_codes = false)
351
-    {
352
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
353
-        return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
354
-    }
355
-
356
-
357
-
358
-    /**
359
-     * @remove ALL items from cart and zero ALL totals
360
-     * @access public
361
-     * @return bool
362
-     * @throws \EE_Error
363
-     */
364
-    public function empty_cart()
365
-    {
366
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
367
-        $this->_grand_total = $this->_create_grand_total();
368
-        return $this->save_cart(true);
369
-    }
370
-
371
-
372
-
373
-    /**
374
-     * @remove ALL items from cart and delete total as well
375
-     * @access public
376
-     * @return bool
377
-     * @throws \EE_Error
378
-     */
379
-    public function delete_cart()
380
-    {
381
-        $deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
382
-        if ($deleted) {
383
-            $deleted += $this->_grand_total->delete();
384
-            $this->_grand_total = null;
385
-        }
386
-        return $deleted;
387
-    }
388
-
389
-
390
-
391
-    /**
392
-     * @save   cart to session
393
-     * @access public
394
-     * @param bool $apply_taxes
395
-     * @return TRUE on success, FALSE on fail
396
-     * @throws \EE_Error
397
-     */
398
-    public function save_cart($apply_taxes = true)
399
-    {
400
-        if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
401
-            EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
402
-            //make sure we don't cache the transaction because it can get stale
403
-            if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
404
-                && $this->_grand_total->get_one_from_cache('Transaction')->ID()
405
-            ) {
406
-                $this->_grand_total->clear_cache('Transaction', null, true);
407
-            }
408
-        }
409
-        if ($this->session() instanceof EE_Session) {
410
-            return $this->session()->set_cart($this);
411
-        } else {
412
-            return false;
413
-        }
414
-    }
415
-
416
-
417
-
418
-    public function __wakeup()
419
-    {
420
-        if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
421
-            // $this->_grand_total is actually just an ID, so use it to get the object from the db
422
-            $this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
423
-        }
424
-    }
425
-
426
-
427
-
428
-    /**
429
-     * @return array
430
-     */
431
-    public function __sleep()
432
-    {
433
-        if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
434
-            $this->_grand_total = $this->_grand_total->ID();
435
-        }
436
-        return array('_grand_total');
437
-    }
26
+	/**
27
+	 * instance of the EE_Cart object
28
+	 *
29
+	 * @access    private
30
+	 * @var EE_Cart $_instance
31
+	 */
32
+	private static $_instance;
33
+
34
+	/**
35
+	 * instance of the EE_Session object
36
+	 *
37
+	 * @access    protected
38
+	 * @var EE_Session $_session
39
+	 */
40
+	protected $_session;
41
+
42
+	/**
43
+	 * The total Line item which comprises all the children line-item subtotals,
44
+	 * which in turn each have their line items.
45
+	 * Typically, the line item structure will look like:
46
+	 * grand total
47
+	 * -tickets-sub-total
48
+	 * --ticket1
49
+	 * --ticket2
50
+	 * --...
51
+	 * -taxes-sub-total
52
+	 * --tax1
53
+	 * --tax2
54
+	 *
55
+	 * @var EE_Line_Item
56
+	 */
57
+	private $_grand_total;
58
+
59
+
60
+
61
+	/**
62
+	 * @singleton method used to instantiate class object
63
+	 * @access    public
64
+	 * @param EE_Line_Item $grand_total
65
+	 * @param EE_Session   $session
66
+	 * @return \EE_Cart
67
+	 * @throws \EE_Error
68
+	 */
69
+	public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
70
+	{
71
+		if ( ! empty($grand_total)) {
72
+			self::$_instance = new self($grand_total, $session);
73
+		}
74
+		// or maybe retrieve an existing one ?
75
+		if ( ! self::$_instance instanceof EE_Cart) {
76
+			// try getting the cart out of the session
77
+			$saved_cart = $session instanceof EE_Session ? $session->cart() : null;
78
+			self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
79
+			unset($saved_cart);
80
+		}
81
+		// verify that cart is ok and grand total line item exists
82
+		if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
83
+			self::$_instance = new self($grand_total, $session);
84
+		}
85
+		self::$_instance->get_grand_total();
86
+		// once everything is all said and done, save the cart to the EE_Session
87
+		add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
88
+		return self::$_instance;
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * private constructor to prevent direct creation
95
+	 *
96
+	 * @Constructor
97
+	 * @access private
98
+	 * @param EE_Line_Item $grand_total
99
+	 * @param EE_Session   $session
100
+	 */
101
+	private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
102
+	{
103
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
104
+		$this->set_session($session);
105
+		if ($grand_total instanceof EE_Line_Item) {
106
+			$this->set_grand_total_line_item($grand_total);
107
+		}
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * Resets the cart completely (whereas empty_cart
114
+	 *
115
+	 * @param EE_Line_Item $grand_total
116
+	 * @param EE_Session   $session
117
+	 * @return EE_Cart
118
+	 * @throws \EE_Error
119
+	 */
120
+	public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
121
+	{
122
+		remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
123
+		if ($session instanceof EE_Session) {
124
+			$session->reset_cart();
125
+		}
126
+		self::$_instance = null;
127
+		return self::instance($grand_total, $session);
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * @return \EE_Session
134
+	 */
135
+	public function session()
136
+	{
137
+		if ( ! $this->_session instanceof EE_Session) {
138
+			$this->set_session();
139
+		}
140
+		return $this->_session;
141
+	}
142
+
143
+
144
+
145
+	/**
146
+	 * @param EE_Session $session
147
+	 */
148
+	public function set_session(EE_Session $session = null)
149
+	{
150
+		$this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * Sets the cart to match the line item. Especially handy for loading an old cart where you
157
+	 *  know the grand total line item on it
158
+	 *
159
+	 * @param EE_Line_Item $line_item
160
+	 */
161
+	public function set_grand_total_line_item(EE_Line_Item $line_item)
162
+	{
163
+		$this->_grand_total = $line_item;
164
+	}
165
+
166
+
167
+
168
+	/**
169
+	 * get_cart_from_reg_url_link
170
+	 *
171
+	 * @access public
172
+	 * @param EE_Transaction $transaction
173
+	 * @param EE_Session     $session
174
+	 * @return \EE_Cart
175
+	 * @throws \EE_Error
176
+	 */
177
+	public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
178
+	{
179
+		$grand_total = $transaction->total_line_item();
180
+		$grand_total->get_items();
181
+		$grand_total->tax_descendants();
182
+		return EE_Cart::instance($grand_total, $session);
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
189
+	 *
190
+	 * @return EE_Line_Item
191
+	 * @throws \EE_Error
192
+	 */
193
+	private function _create_grand_total()
194
+	{
195
+		$this->_grand_total = EEH_Line_Item::create_total_line_item();
196
+		return $this->_grand_total;
197
+	}
198
+
199
+
200
+
201
+	/**
202
+	 * Gets all the line items of object type Ticket
203
+	 *
204
+	 * @access public
205
+	 * @return \EE_Line_Item[]
206
+	 */
207
+	public function get_tickets()
208
+	{
209
+		if ($this->_grand_total === null ) {
210
+			return array();
211
+		}
212
+		return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
213
+	}
214
+
215
+
216
+
217
+	/**
218
+	 * returns the total quantity of tickets in the cart
219
+	 *
220
+	 * @access public
221
+	 * @return int
222
+	 * @throws \EE_Error
223
+	 */
224
+	public function all_ticket_quantity_count()
225
+	{
226
+		$tickets = $this->get_tickets();
227
+		if (empty($tickets)) {
228
+			return 0;
229
+		}
230
+		$count = 0;
231
+		foreach ($tickets as $ticket) {
232
+			$count += $ticket->get('LIN_quantity');
233
+		}
234
+		return $count;
235
+	}
236
+
237
+
238
+
239
+	/**
240
+	 * Gets all the tax line items
241
+	 *
242
+	 * @return \EE_Line_Item[]
243
+	 * @throws \EE_Error
244
+	 */
245
+	public function get_taxes()
246
+	{
247
+		return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
248
+	}
249
+
250
+
251
+
252
+	/**
253
+	 * Gets the total line item (which is a parent of all other line items) on this cart
254
+	 *
255
+	 * @return EE_Line_Item
256
+	 * @throws \EE_Error
257
+	 */
258
+	public function get_grand_total()
259
+	{
260
+		return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 * @process items for adding to cart
267
+	 * @access  public
268
+	 * @param EE_Ticket $ticket
269
+	 * @param int       $qty
270
+	 * @return TRUE on success, FALSE on fail
271
+	 * @throws \EE_Error
272
+	 */
273
+	public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
274
+	{
275
+		EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
276
+		return $this->save_cart() ? true : false;
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * get_cart_total_before_tax
283
+	 *
284
+	 * @access public
285
+	 * @return float
286
+	 * @throws \EE_Error
287
+	 */
288
+	public function get_cart_total_before_tax()
289
+	{
290
+		return $this->get_grand_total()->recalculate_pre_tax_total();
291
+	}
292
+
293
+
294
+
295
+	/**
296
+	 * gets the total amount of tax paid for items in this cart
297
+	 *
298
+	 * @access public
299
+	 * @return float
300
+	 * @throws \EE_Error
301
+	 */
302
+	public function get_applied_taxes()
303
+	{
304
+		return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
305
+	}
306
+
307
+
308
+
309
+	/**
310
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
311
+	 *
312
+	 * @access public
313
+	 * @return float
314
+	 * @throws \EE_Error
315
+	 */
316
+	public function get_cart_grand_total()
317
+	{
318
+		EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
319
+		return $this->get_grand_total()->total();
320
+	}
321
+
322
+
323
+
324
+	/**
325
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
326
+	 *
327
+	 * @access public
328
+	 * @return float
329
+	 * @throws \EE_Error
330
+	 */
331
+	public function recalculate_all_cart_totals()
332
+	{
333
+		$pre_tax_total = $this->get_cart_total_before_tax();
334
+		$taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
335
+		$this->_grand_total->set_total($pre_tax_total + $taxes_total);
336
+		$this->_grand_total->save_this_and_descendants_to_txn();
337
+		return $this->get_grand_total()->total();
338
+	}
339
+
340
+
341
+
342
+	/**
343
+	 * deletes an item from the cart
344
+	 *
345
+	 * @access public
346
+	 * @param array|bool|string $line_item_codes
347
+	 * @return int on success, FALSE on fail
348
+	 * @throws \EE_Error
349
+	 */
350
+	public function delete_items($line_item_codes = false)
351
+	{
352
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
353
+		return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
354
+	}
355
+
356
+
357
+
358
+	/**
359
+	 * @remove ALL items from cart and zero ALL totals
360
+	 * @access public
361
+	 * @return bool
362
+	 * @throws \EE_Error
363
+	 */
364
+	public function empty_cart()
365
+	{
366
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
367
+		$this->_grand_total = $this->_create_grand_total();
368
+		return $this->save_cart(true);
369
+	}
370
+
371
+
372
+
373
+	/**
374
+	 * @remove ALL items from cart and delete total as well
375
+	 * @access public
376
+	 * @return bool
377
+	 * @throws \EE_Error
378
+	 */
379
+	public function delete_cart()
380
+	{
381
+		$deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
382
+		if ($deleted) {
383
+			$deleted += $this->_grand_total->delete();
384
+			$this->_grand_total = null;
385
+		}
386
+		return $deleted;
387
+	}
388
+
389
+
390
+
391
+	/**
392
+	 * @save   cart to session
393
+	 * @access public
394
+	 * @param bool $apply_taxes
395
+	 * @return TRUE on success, FALSE on fail
396
+	 * @throws \EE_Error
397
+	 */
398
+	public function save_cart($apply_taxes = true)
399
+	{
400
+		if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
401
+			EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
402
+			//make sure we don't cache the transaction because it can get stale
403
+			if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
404
+				&& $this->_grand_total->get_one_from_cache('Transaction')->ID()
405
+			) {
406
+				$this->_grand_total->clear_cache('Transaction', null, true);
407
+			}
408
+		}
409
+		if ($this->session() instanceof EE_Session) {
410
+			return $this->session()->set_cart($this);
411
+		} else {
412
+			return false;
413
+		}
414
+	}
415
+
416
+
417
+
418
+	public function __wakeup()
419
+	{
420
+		if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
421
+			// $this->_grand_total is actually just an ID, so use it to get the object from the db
422
+			$this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
423
+		}
424
+	}
425
+
426
+
427
+
428
+	/**
429
+	 * @return array
430
+	 */
431
+	public function __sleep()
432
+	{
433
+		if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
434
+			$this->_grand_total = $this->_grand_total->ID();
435
+		}
436
+		return array('_grand_total');
437
+	}
438 438
 
439 439
 
440 440
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +5817 added lines, -5817 removed lines patch added patch discarded remove patch
@@ -28,5825 +28,5825 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base implements EventEspresso\core\interfaces\ResettableInterface
29 29
 {
30 30
 
31
-    //admin posty
32
-    //basic -> grants access to mine -> if they don't have it, select none
33
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
-    //*_published -> grants access to published -> if they dont have it, select non-published
36
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
38
-    //frontend posty
39
-    //by default has access to published
40
-    //basic -> grants access to mine that aren't published, and all published
41
-    //*_others ->grants access to others that aren't private, all mine
42
-    //*_private -> grants full access
43
-    //frontend non-posty
44
-    //like admin posty
45
-    //category-y
46
-    //assign -> grants access to join-table
47
-    //(delete, edit)
48
-    //payment-method-y
49
-    //for each registered payment method,
50
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
-    /**
52
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
-     * They almost always WILL NOT, but it's not necessarily a requirement.
55
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
-     *
57
-     * @var boolean
58
-     */
59
-    private $_values_already_prepared_by_model_object = 0;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the data is just like form input that needs to have the model fields'
64
-     * prepare_for_set and prepare_for_use_in_db called on it
65
-     */
66
-    const not_prepared_by_model_object = 0;
67
-
68
-    /**
69
-     * when $_values_already_prepared_by_model_object equals this, we
70
-     * assume this value is coming from a model object and doesn't need to have
71
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
72
-     */
73
-    const prepared_by_model_object = 1;
74
-
75
-    /**
76
-     * when $_values_already_prepared_by_model_object equals this, we assume
77
-     * the values are already to be used in the database (ie no processing is done
78
-     * on them by the model's fields)
79
-     */
80
-    const prepared_for_use_in_db = 2;
81
-
82
-
83
-    protected $singular_item = 'Item';
84
-
85
-    protected $plural_item   = 'Items';
86
-
87
-    /**
88
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
-     */
90
-    protected $_tables;
91
-
92
-    /**
93
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
-     *
97
-     * @var \EE_Model_Field_Base[] $_fields
98
-     */
99
-    protected $_fields;
100
-
101
-    /**
102
-     * array of different kinds of relations
103
-     *
104
-     * @var \EE_Model_Relation_Base[] $_model_relations
105
-     */
106
-    protected $_model_relations;
107
-
108
-    /**
109
-     * @var \EE_Index[] $_indexes
110
-     */
111
-    protected $_indexes = array();
112
-
113
-    /**
114
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
115
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
-     * by setting the same columns as used in these queries in the query yourself.
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_default_where_conditions_strategy;
121
-
122
-    /**
123
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
-     * This is particularly useful when you want something between 'none' and 'default'
125
-     *
126
-     * @var EE_Default_Where_Conditions
127
-     */
128
-    protected $_minimum_where_conditions_strategy;
129
-
130
-    /**
131
-     * String describing how to find the "owner" of this model's objects.
132
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
-     * But when there isn't, this indicates which related model, or transiently-related model,
134
-     * has the foreign key to the wp_users table.
135
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
-     * related to events, and events have a foreign key to wp_users.
137
-     * On EEM_Transaction, this would be 'Transaction.Event'
138
-     *
139
-     * @var string
140
-     */
141
-    protected $_model_chain_to_wp_user = '';
142
-
143
-    /**
144
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
-     * don't need it (particularly CPT models)
146
-     *
147
-     * @var bool
148
-     */
149
-    protected $_ignore_where_strategy = false;
150
-
151
-    /**
152
-     * String used in caps relating to this model. Eg, if the caps relating to this
153
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
-     *
155
-     * @var string. If null it hasn't been initialized yet. If false then we
156
-     * have indicated capabilities don't apply to this
157
-     */
158
-    protected $_caps_slug = null;
159
-
160
-    /**
161
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
-     * and next-level keys are capability names, and each's value is a
163
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
-     * they specify which context to use (ie, frontend, backend, edit or delete)
165
-     * and then each capability in the corresponding sub-array that they're missing
166
-     * adds the where conditions onto the query.
167
-     *
168
-     * @var array
169
-     */
170
-    protected $_cap_restrictions = array(
171
-        self::caps_read       => array(),
172
-        self::caps_read_admin => array(),
173
-        self::caps_edit       => array(),
174
-        self::caps_delete     => array(),
175
-    );
176
-
177
-    /**
178
-     * Array defining which cap restriction generators to use to create default
179
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
180
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
-     * automatically set this to false (not just null).
183
-     *
184
-     * @var EE_Restriction_Generator_Base[]
185
-     */
186
-    protected $_cap_restriction_generators = array();
187
-
188
-    /**
189
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
-     */
191
-    const caps_read       = 'read';
192
-
193
-    const caps_read_admin = 'read_admin';
194
-
195
-    const caps_edit       = 'edit';
196
-
197
-    const caps_delete     = 'delete';
198
-
199
-    /**
200
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
-     * maps to 'read' because when looking for relevant permissions we're going to use
203
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
204
-     *
205
-     * @var array
206
-     */
207
-    protected $_cap_contexts_to_cap_action_map = array(
208
-        self::caps_read       => 'read',
209
-        self::caps_read_admin => 'read',
210
-        self::caps_edit       => 'edit',
211
-        self::caps_delete     => 'delete',
212
-    );
213
-
214
-    /**
215
-     * Timezone
216
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
-     * EE_Datetime_Field data type will have access to it.
220
-     *
221
-     * @var string
222
-     */
223
-    protected $_timezone;
224
-
225
-
226
-    /**
227
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
-     * multisite.
229
-     *
230
-     * @var int
231
-     */
232
-    protected static $_model_query_blog_id;
233
-
234
-    /**
235
-     * A copy of _fields, except the array keys are the model names pointed to by
236
-     * the field
237
-     *
238
-     * @var EE_Model_Field_Base[]
239
-     */
240
-    private $_cache_foreign_key_to_fields = array();
241
-
242
-    /**
243
-     * Cached list of all the fields on the model, indexed by their name
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cached_fields = null;
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, except those that are
251
-     * marked as only pertinent to the database
252
-     *
253
-     * @var EE_Model_Field_Base[]
254
-     */
255
-    private $_cached_fields_non_db_only = null;
256
-
257
-    /**
258
-     * A cached reference to the primary key for quick lookup
259
-     *
260
-     * @var EE_Model_Field_Base
261
-     */
262
-    private $_primary_key_field = null;
263
-
264
-    /**
265
-     * Flag indicating whether this model has a primary key or not
266
-     *
267
-     * @var boolean
268
-     */
269
-    protected $_has_primary_key_field = null;
270
-
271
-    /**
272
-     * Whether or not this model is based off a table in WP core only (CPTs should set
273
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
-     *
275
-     * @var boolean
276
-     */
277
-    protected $_wp_core_model = false;
278
-
279
-    /**
280
-     *    List of valid operators that can be used for querying.
281
-     * The keys are all operators we'll accept, the values are the real SQL
282
-     * operators used
283
-     *
284
-     * @var array
285
-     */
286
-    protected $_valid_operators = array(
287
-        '='           => '=',
288
-        '<='          => '<=',
289
-        '<'           => '<',
290
-        '>='          => '>=',
291
-        '>'           => '>',
292
-        '!='          => '!=',
293
-        'LIKE'        => 'LIKE',
294
-        'like'        => 'LIKE',
295
-        'NOT_LIKE'    => 'NOT LIKE',
296
-        'not_like'    => 'NOT LIKE',
297
-        'NOT LIKE'    => 'NOT LIKE',
298
-        'not like'    => 'NOT LIKE',
299
-        'IN'          => 'IN',
300
-        'in'          => 'IN',
301
-        'NOT_IN'      => 'NOT IN',
302
-        'not_in'      => 'NOT IN',
303
-        'NOT IN'      => 'NOT IN',
304
-        'not in'      => 'NOT IN',
305
-        'between'     => 'BETWEEN',
306
-        'BETWEEN'     => 'BETWEEN',
307
-        'IS_NOT_NULL' => 'IS NOT NULL',
308
-        'is_not_null' => 'IS NOT NULL',
309
-        'IS NOT NULL' => 'IS NOT NULL',
310
-        'is not null' => 'IS NOT NULL',
311
-        'IS_NULL'     => 'IS NULL',
312
-        'is_null'     => 'IS NULL',
313
-        'IS NULL'     => 'IS NULL',
314
-        'is null'     => 'IS NULL',
315
-        'REGEXP'      => 'REGEXP',
316
-        'regexp'      => 'REGEXP',
317
-        'NOT_REGEXP'  => 'NOT REGEXP',
318
-        'not_regexp'  => 'NOT REGEXP',
319
-        'NOT REGEXP'  => 'NOT REGEXP',
320
-        'not regexp'  => 'NOT REGEXP',
321
-    );
322
-
323
-    /**
324
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
-     *
326
-     * @var array
327
-     */
328
-    protected $_in_style_operators = array('IN', 'NOT IN');
329
-
330
-    /**
331
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
-     * '12-31-2012'"
333
-     *
334
-     * @var array
335
-     */
336
-    protected $_between_style_operators = array('BETWEEN');
337
-
338
-    /**
339
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
-     * on a join table.
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
-
346
-    /**
347
-     * Allowed values for $query_params['order'] for ordering in queries
348
-     *
349
-     * @var array
350
-     */
351
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
-
353
-    /**
354
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
356
-     *
357
-     * @var array
358
-     */
359
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
-
361
-    /**
362
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
364
-     *
365
-     * @var array
366
-     */
367
-    private $_allowed_query_params = array(
368
-        0,
369
-        'limit',
370
-        'order_by',
371
-        'group_by',
372
-        'having',
373
-        'force_join',
374
-        'order',
375
-        'on_join_limit',
376
-        'default_where_conditions',
377
-        'caps',
378
-    );
379
-
380
-    /**
381
-     * All the data types that can be used in $wpdb->prepare statements.
382
-     *
383
-     * @var array
384
-     */
385
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
-
387
-    /**
388
-     *    EE_Registry Object
389
-     *
390
-     * @var    object
391
-     * @access    protected
392
-     */
393
-    protected $EE = null;
394
-
395
-
396
-    /**
397
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
-     *
399
-     * @var int
400
-     */
401
-    protected $_show_next_x_db_queries = 0;
402
-
403
-    /**
404
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
-     *
407
-     * @var array
408
-     */
409
-    protected $_custom_selections = array();
410
-
411
-    /**
412
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
-     * caches every model object we've fetched from the DB on this request
414
-     *
415
-     * @var array
416
-     */
417
-    protected $_entity_map;
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws \EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Generates the cap restrictions for the given context, or if they were
654
-     * already generated just gets what's cached
655
-     *
656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
657
-     * @return EE_Default_Where_Conditions[]
658
-     */
659
-    protected function _generate_cap_restrictions($context)
660
-    {
661
-        if (isset($this->_cap_restriction_generators[$context])
662
-            && $this->_cap_restriction_generators[$context]
663
-               instanceof
664
-               EE_Restriction_Generator_Base
665
-        ) {
666
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
-        } else {
668
-            return array();
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Used to set the $_model_query_blog_id static property.
676
-     *
677
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
-     *                      value for get_current_blog_id() will be used.
679
-     */
680
-    public static function set_model_query_blog_id($blog_id = 0)
681
-    {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns whatever is set as the internal $model_query_blog_id.
689
-     *
690
-     * @return int
691
-     */
692
-    public static function get_model_query_blog_id()
693
-    {
694
-        return EEM_Base::$_model_query_blog_id;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *        This function is a singleton method used to instantiate the Espresso_model object
701
-     *
702
-     * @access public
703
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
-     *                         timezone in the 'timezone_string' wp option)
707
-     * @return static (as in the concrete child class)
708
-     */
709
-    public static function instance($timezone = null)
710
-    {
711
-        // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
713
-            // instantiate Espresso_model
714
-            static::$_instance = new static($timezone);
715
-        }
716
-        //we might have a timezone set, let set_timezone decide what to do with it
717
-        static::$_instance->set_timezone($timezone);
718
-        // Espresso_model object
719
-        return static::$_instance;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * resets the model and returns it
726
-     *
727
-     * @param null | string $timezone
728
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
-     * all its properties reset; if it wasn't instantiated, returns null)
730
-     */
731
-    public static function reset($timezone = null)
732
-    {
733
-        if (static::$_instance instanceof EEM_Base) {
734
-            //let's try to NOT swap out the current instance for a new one
735
-            //because if someone has a reference to it, we can't remove their reference
736
-            //so it's best to keep using the same reference, but change the original object
737
-            //reset all its properties to their original values as defined in the class
738
-            $r = new ReflectionClass(get_class(static::$_instance));
739
-            $static_properties = $r->getStaticProperties();
740
-            foreach ($r->getDefaultProperties() as $property => $value) {
741
-                //don't set instance to null like it was originally,
742
-                //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
744
-                    static::$_instance->{$property} = $value;
745
-                }
746
-            }
747
-            //and then directly call its constructor again, like we would if we
748
-            //were creating a new one
749
-            static::$_instance->__construct($timezone);
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
-     *
760
-     * @param  boolean $translated return localized strings or JUST the array.
761
-     * @return array
762
-     * @throws \EE_Error
763
-     */
764
-    public function status_array($translated = false)
765
-    {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
-            return array();
768
-        }
769
-        $model_name = $this->get_this_model_name();
770
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
-        $status_array = array();
773
-        foreach ($stati as $status) {
774
-            $status_array[$status->ID()] = $status->get('STS_code');
775
-        }
776
-        return $translated
777
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
-            : $status_array;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
-     *
786
-     * @param array $query_params             {
787
-     * @var array $0 (where) array {
788
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
-     *                                        conditions based on related models (and even
792
-     *                                        models-related-to-related-models) prepend the model's name onto the field
793
-     *                                        name. Eg,
794
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
-     *                                        to Venues (even when each of those models actually consisted of two
802
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
803
-     *                                        just having
804
-     *                                        "Venue.VNU_ID", you could have
805
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
-     *                                        events are related to Registrations, which are related to Attendees). You
807
-     *                                        can take it even further with
808
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
-     *                                        (from the default of '='), change the value to an numerically-indexed
810
-     *                                        array, where the first item in the list is the operator. eg: array(
811
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
819
-     *                                        the value is a field, simply provide a third array item (true) to the
820
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
-     *                                        Note: you can also use related model field names like you would any other
823
-     *                                        field name. eg:
824
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
826
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
833
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
-     *                                        "stick" until you specify an AND. eg
835
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
840
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
-     *                                        too, eg:
843
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
848
-     *                                        the OFFSET, the 2nd is the LIMIT
849
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
-     *                                        following format array('on_join_limit'
852
-     *                                        => array( 'table_alias', array(1,2) ) ).
853
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
-     *                                        values are either 'ASC' or 'DESC'.
855
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
-     *                                        DESC..." respectively. Like the
858
-     *                                        'where' conditions, these fields can be on related models. Eg
859
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
861
-     *                                        Attendee, Price, Datetime, etc.)
862
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
864
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
-     *                                        order by the primary key. Eg,
867
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
-     *                                        //(will join with the Datetime model's table(s) and order by its field
869
-     *                                        DTT_EVT_start) or
870
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
-     *                                        'group_by'=>'VNU_ID', or
874
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
-     *                                        if no
876
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
877
-     *                                        model's primary key (or combined primary keys). This avoids some
878
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
879
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
-     *                                        results)
883
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
-     *                                        array where values are models to be joined in the query.Eg
885
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
887
-     *                                        probably only want to do this in hopes of increasing efficiency, as
888
-     *                                        related models which belongs to the current model
889
-     *                                        (ie, the current model has a foreign key to them, like how Registration
890
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
891
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
894
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
-     *                                        default where conditions set it to 'other_models_only'. If you only want
896
-     *                                        this model's default where conditions added to the query, use
897
-     *                                        'this_model_only'. If you want to use all default where conditions
898
-     *                                        (default), set to 'all'.
899
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
-     *                                        everything? Or should we only show the current user items they should be
902
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
-     *                                        }
905
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
-     *                                        array( array(
911
-     *                                        'OR'=>array(
912
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
-     *                                        )
915
-     *                                        ),
916
-     *                                        'limit'=>10,
917
-     *                                        'group_by'=>'TXN_ID'
918
-     *                                        ));
919
-     *                                        get all the answers to the question titled "shirt size" for event with id
920
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
-     *                                        'Question.QST_display_text'=>'shirt size',
922
-     *                                        'Registration.Event.EVT_ID'=>12
923
-     *                                        ),
924
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
925
-     *                                        ));
926
-     * @throws \EE_Error
927
-     */
928
-    public function get_all($query_params = array())
929
-    {
930
-        if (isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Modifies the query parameters so we only get back model objects
942
-     * that "belong" to the current user
943
-     *
944
-     * @param array $query_params @see EEM_Base::get_all()
945
-     * @return array like EEM_Base::get_all
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = array())
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     */
966
-    public function wp_user_field_name()
967
-    {
968
-        try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
970
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
-                $last_model_name = end($models_to_follow_to_wp_users);
972
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
-            } else {
975
-                $model_with_fk_to_wp_users = $this;
976
-                $model_chain_to_wp_user = '';
977
-            }
978
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
-        } catch (EE_Error $e) {
981
-            return false;
982
-        }
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        } else {
1017
-            try {
1018
-                $this->get_foreign_key_to('WP_User');
1019
-                return true;
1020
-            } catch (EE_Error $e) {
1021
-                return false;
1022
-            }
1023
-        }
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws \EE_Error
1045
-     */
1046
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        // remember the custom selections, if any, and type cast as array
1049
-        // (unless $columns_to_select is an object, then just set as an empty array)
1050
-        // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions = $columns_to_select !== null
1054
-            ? $this->_construct_select_from_input($columns_to_select)
1055
-            : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1064
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
-     * take care of joins, field preparation etc.
1066
-     *
1067
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1071
-     *                                  override this and set the select to "*", or a specific column name, like
1072
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
-     *                                  the aliases used to refer to this selection, and values are to be
1075
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
-     * @throws \EE_Error
1079
-     */
1080
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
-    {
1082
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * For creating a custom select statement
1089
-     *
1090
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
-     *                                 SQL, and 1=>is the datatype
1093
-     * @throws EE_Error
1094
-     * @return string
1095
-     */
1096
-    private function _construct_select_from_input($columns_to_select)
1097
-    {
1098
-        if (is_array($columns_to_select)) {
1099
-            $select_sql_array = array();
1100
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
-                    throw new EE_Error(
1103
-                        sprintf(
1104
-                            __(
1105
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
-                                "event_espresso"
1107
-                            ),
1108
-                            $selection_and_datatype,
1109
-                            $alias
1110
-                        )
1111
-                    );
1112
-                }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
-                    throw new EE_Error(
1115
-                        sprintf(
1116
-                            __(
1117
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
-                                "event_espresso"
1119
-                            ),
1120
-                            $selection_and_datatype[1],
1121
-                            $selection_and_datatype[0],
1122
-                            $alias,
1123
-                            implode(",", $this->_valid_wpdb_data_types)
1124
-                        )
1125
-                    );
1126
-                }
1127
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
-            }
1129
-            $columns_to_select_string = implode(", ", $select_sql_array);
1130
-        } else {
1131
-            $columns_to_select_string = $columns_to_select;
1132
-        }
1133
-        return $columns_to_select_string;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
-     *
1141
-     * @return string
1142
-     * @throws \EE_Error
1143
-     */
1144
-    public function primary_key_name()
1145
-    {
1146
-        return $this->get_primary_key_field()->get_name();
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
-     * If there is no primary key on this model, $id is treated as primary key string
1154
-     *
1155
-     * @param mixed $id int or string, depending on the type of the model's primary key
1156
-     * @return EE_Base_Class
1157
-     */
1158
-    public function get_one_by_ID($id)
1159
-    {
1160
-        if ($this->get_from_entity_map($id)) {
1161
-            return $this->get_from_entity_map($id);
1162
-        }
1163
-        return $this->get_one(
1164
-            $this->alter_query_params_to_restrict_by_ID(
1165
-                $id,
1166
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
-            )
1168
-        );
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Alters query parameters to only get items with this ID are returned.
1175
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
-     * or could just be a simple primary key ID
1177
-     *
1178
-     * @param int   $id
1179
-     * @param array $query_params
1180
-     * @return array of normal query params, @see EEM_Base::get_all
1181
-     * @throws \EE_Error
1182
-     */
1183
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
-    {
1185
-        if (! isset($query_params[0])) {
1186
-            $query_params[0] = array();
1187
-        }
1188
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1189
-        if ($conditions_from_id === null) {
1190
-            $query_params[0][$this->primary_key_name()] = $id;
1191
-        } else {
1192
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1193
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
-        }
1195
-        return $query_params;
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
-     * array. If no item is found, null is returned.
1203
-     *
1204
-     * @param array $query_params like EEM_Base's $query_params variable.
1205
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
-     * @throws \EE_Error
1207
-     */
1208
-    public function get_one($query_params = array())
1209
-    {
1210
-        if (! is_array($query_params)) {
1211
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
-                    gettype($query_params)), '4.6.0');
1214
-            $query_params = array();
1215
-        }
1216
-        $query_params['limit'] = 1;
1217
-        $items = $this->get_all($query_params);
1218
-        if (empty($items)) {
1219
-            return null;
1220
-        } else {
1221
-            return array_shift($items);
1222
-        }
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Returns the next x number of items in sequence from the given value as
1229
-     * found in the database matching the given query conditions.
1230
-     *
1231
-     * @param mixed $current_field_value    Value used for the reference point.
1232
-     * @param null  $field_to_order_by      What field is used for the
1233
-     *                                      reference point.
1234
-     * @param int   $limit                  How many to return.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an array of
1237
-     *                                      EE_Base_Class objects is returned,
1238
-     *                                      otherwise you can indicate just the
1239
-     *                                      columns you want returned.
1240
-     * @return EE_Base_Class[]|array
1241
-     * @throws \EE_Error
1242
-     */
1243
-    public function next_x(
1244
-        $current_field_value,
1245
-        $field_to_order_by = null,
1246
-        $limit = 1,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
-            $columns_to_select);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the previous x number of items in sequence from the given value
1258
-     * as found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws \EE_Error
1271
-     */
1272
-    public function previous_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
-            $columns_to_select);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * Returns the next item in sequence from the given value as found in the
1287
-     * database matching the given query conditions.
1288
-     *
1289
-     * @param mixed $current_field_value    Value used for the reference point.
1290
-     * @param null  $field_to_order_by      What field is used for the
1291
-     *                                      reference point.
1292
-     * @param array $query_params           Extra conditions on the query.
1293
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
-     *                                      object is returned, otherwise you
1295
-     *                                      can indicate just the columns you
1296
-     *                                      want and a single array indexed by
1297
-     *                                      the columns will be returned.
1298
-     * @return EE_Base_Class|null|array()
1299
-     * @throws \EE_Error
1300
-     */
1301
-    public function next(
1302
-        $current_field_value,
1303
-        $field_to_order_by = null,
1304
-        $query_params = array(),
1305
-        $columns_to_select = null
1306
-    ) {
1307
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
-            $columns_to_select);
1309
-        return empty($results) ? null : reset($results);
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     * Returns the previous item in sequence from the given value as found in
1316
-     * the database matching the given query conditions.
1317
-     *
1318
-     * @param mixed $current_field_value    Value used for the reference point.
1319
-     * @param null  $field_to_order_by      What field is used for the
1320
-     *                                      reference point.
1321
-     * @param array $query_params           Extra conditions on the query.
1322
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
-     *                                      object is returned, otherwise you
1324
-     *                                      can indicate just the columns you
1325
-     *                                      want and a single array indexed by
1326
-     *                                      the columns will be returned.
1327
-     * @return EE_Base_Class|null|array()
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function previous(
1331
-        $current_field_value,
1332
-        $field_to_order_by = null,
1333
-        $query_params = array(),
1334
-        $columns_to_select = null
1335
-    ) {
1336
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
-            $columns_to_select);
1338
-        return empty($results) ? null : reset($results);
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * Returns the a consecutive number of items in sequence from the given
1345
-     * value as found in the database matching the given query conditions.
1346
-     *
1347
-     * @param mixed  $current_field_value   Value used for the reference point.
1348
-     * @param string $operand               What operand is used for the sequence.
1349
-     * @param string $field_to_order_by     What field is used for the reference point.
1350
-     * @param int    $limit                 How many to return.
1351
-     * @param array  $query_params          Extra conditions on the query.
1352
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
-     *                                      otherwise you can indicate just the columns you want returned.
1354
-     * @return EE_Base_Class[]|array
1355
-     * @throws EE_Error
1356
-     */
1357
-    protected function _get_consecutive(
1358
-        $current_field_value,
1359
-        $operand = '>',
1360
-        $field_to_order_by = null,
1361
-        $limit = 1,
1362
-        $query_params = array(),
1363
-        $columns_to_select = null
1364
-    ) {
1365
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
-        if (empty($field_to_order_by)) {
1367
-            if ($this->has_primary_key_field()) {
1368
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1369
-            } else {
1370
-                if (WP_DEBUG) {
1371
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1372
-                        'event_espresso'));
1373
-                }
1374
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
-                return array();
1376
-            }
1377
-        }
1378
-        if (! is_array($query_params)) {
1379
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
-                    gettype($query_params)), '4.6.0');
1382
-            $query_params = array();
1383
-        }
1384
-        //let's add the where query param for consecutive look up.
1385
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
-        $query_params['limit'] = $limit;
1387
-        //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
-        $query_params['order_by'] = $operand === '>'
1390
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
-        if (empty($columns_to_select)) {
1394
-            return $this->get_all($query_params);
1395
-        } else {
1396
-            //getting just the fields
1397
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
-        }
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        //note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        //and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        //if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469
-                'event_espresso'), $field_name));
1470
-        }
1471
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
-        //the field.
1473
-        $this->_timezone = $field_settings->get_timezone();
1474
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
-    }
1476
-
1477
-
1478
-
1479
-    /**
1480
-     * This returns the current time in a format setup for a query on this model.
1481
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
-     * it will return:
1483
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
-     *  NOW
1485
-     *  - or a unix timestamp (equivalent to time())
1486
-     *
1487
-     * @since 4.6.x
1488
-     * @param string $field_name       The field the current time is needed for.
1489
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1490
-     *                                 formatted string matching the set format for the field in the set timezone will
1491
-     *                                 be returned.
1492
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1493
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1494
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
-     *                                 exception is triggered.
1496
-     */
1497
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1498
-    {
1499
-        $formats = $this->get_formats_for($field_name);
1500
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1501
-        if ($timestamp) {
1502
-            return $DateTime->format('U');
1503
-        }
1504
-        //not returning timestamp, so return formatted string in timezone.
1505
-        switch ($what) {
1506
-            case 'time' :
1507
-                return $DateTime->format($formats[1]);
1508
-                break;
1509
-            case 'date' :
1510
-                return $DateTime->format($formats[0]);
1511
-                break;
1512
-            default :
1513
-                return $DateTime->format(implode(' ', $formats));
1514
-                break;
1515
-        }
1516
-    }
1517
-
1518
-
1519
-
1520
-    /**
1521
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1522
-     * for the model are.  Returns a DateTime object.
1523
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1524
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1525
-     * ignored.
1526
-     *
1527
-     * @param string $field_name      The field being setup.
1528
-     * @param string $timestring      The date time string being used.
1529
-     * @param string $incoming_format The format for the time string.
1530
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1531
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1532
-     *                                format is
1533
-     *                                'U', this is ignored.
1534
-     * @return DateTime
1535
-     * @throws \EE_Error
1536
-     */
1537
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1538
-    {
1539
-        //just using this to ensure the timezone is set correctly internally
1540
-        $this->get_formats_for($field_name);
1541
-        //load EEH_DTT_Helper
1542
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1543
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1544
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1545
-    }
1546
-
1547
-
1548
-
1549
-    /**
1550
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1551
-     *
1552
-     * @return EE_Table_Base[]
1553
-     */
1554
-    public function get_tables()
1555
-    {
1556
-        return $this->_tables;
1557
-    }
1558
-
1559
-
1560
-
1561
-    /**
1562
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1563
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1564
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1565
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1566
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1567
-     * model object with EVT_ID = 1
1568
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1569
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1570
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1571
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1572
-     * are not specified)
1573
-     *
1574
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1575
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1576
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1577
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1578
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1579
-     *                                         ID=34, we'd use this method as follows:
1580
-     *                                         EEM_Transaction::instance()->update(
1581
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1582
-     *                                         array(array('TXN_ID'=>34)));
1583
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1584
-     *                                         in client code into what's expected to be stored on each field. Eg,
1585
-     *                                         consider updating Question's QST_admin_label field is of type
1586
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1587
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1588
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1589
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1590
-     *                                         TRUE, it is assumed that you've already called
1591
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1592
-     *                                         malicious javascript. However, if
1593
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1594
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1595
-     *                                         and every other field, before insertion. We provide this parameter
1596
-     *                                         because model objects perform their prepare_for_set function on all
1597
-     *                                         their values, and so don't need to be called again (and in many cases,
1598
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1599
-     *                                         prepare_for_set method...)
1600
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1601
-     *                                         in this model's entity map according to $fields_n_values that match
1602
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1603
-     *                                         by setting this to FALSE, but be aware that model objects being used
1604
-     *                                         could get out-of-sync with the database
1605
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1606
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1607
-     *                                         bad)
1608
-     * @throws \EE_Error
1609
-     */
1610
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1611
-    {
1612
-        if (! is_array($query_params)) {
1613
-            EE_Error::doing_it_wrong('EEM_Base::update',
1614
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1615
-                    gettype($query_params)), '4.6.0');
1616
-            $query_params = array();
1617
-        }
1618
-        /**
1619
-         * Action called before a model update call has been made.
1620
-         *
1621
-         * @param EEM_Base $model
1622
-         * @param array    $fields_n_values the updated fields and their new values
1623
-         * @param array    $query_params    @see EEM_Base::get_all()
1624
-         */
1625
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1626
-        /**
1627
-         * Filters the fields about to be updated given the query parameters. You can provide the
1628
-         * $query_params to $this->get_all() to find exactly which records will be updated
1629
-         *
1630
-         * @param array    $fields_n_values fields and their new values
1631
-         * @param EEM_Base $model           the model being queried
1632
-         * @param array    $query_params    see EEM_Base::get_all()
1633
-         */
1634
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
-            $query_params);
1636
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1637
-        //to do that, for each table, verify that it's PK isn't null.
1638
-        $tables = $this->get_tables();
1639
-        //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
1640
-        //NOTE: we should make this code more efficient by NOT querying twice
1641
-        //before the real update, but that needs to first go through ALPHA testing
1642
-        //as it's dangerous. says Mike August 8 2014
1643
-        //we want to make sure the default_where strategy is ignored
1644
-        $this->_ignore_where_strategy = true;
1645
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1646
-        foreach ($wpdb_select_results as $wpdb_result) {
1647
-            // type cast stdClass as array
1648
-            $wpdb_result = (array)$wpdb_result;
1649
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1650
-            if ($this->has_primary_key_field()) {
1651
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1652
-            } else {
1653
-                //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)
1654
-                $main_table_pk_value = null;
1655
-            }
1656
-            //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
1657
-            //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
1658
-            if (count($tables) > 1) {
1659
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1660
-                //in that table, and so we'll want to insert one
1661
-                foreach ($tables as $table_obj) {
1662
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1663
-                    //if there is no private key for this table on the results, it means there's no entry
1664
-                    //in this table, right? so insert a row in the current table, using any fields available
1665
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
-                           && $wpdb_result[$this_table_pk_column])
1667
-                    ) {
1668
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1669
-                            $main_table_pk_value);
1670
-                        //if we died here, report the error
1671
-                        if (! $success) {
1672
-                            return false;
1673
-                        }
1674
-                    }
1675
-                }
1676
-            }
1677
-            //				//and now check that if we have cached any models by that ID on the model, that
1678
-            //				//they also get updated properly
1679
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1680
-            //				if( $model_object ){
1681
-            //					foreach( $fields_n_values as $field => $value ){
1682
-            //						$model_object->set($field, $value);
1683
-            //let's make sure default_where strategy is followed now
1684
-            $this->_ignore_where_strategy = false;
1685
-        }
1686
-        //if we want to keep model objects in sync, AND
1687
-        //if this wasn't called from a model object (to update itself)
1688
-        //then we want to make sure we keep all the existing
1689
-        //model objects in sync with the db
1690
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1691
-            if ($this->has_primary_key_field()) {
1692
-                $model_objs_affected_ids = $this->get_col($query_params);
1693
-            } else {
1694
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1695
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1696
-                $model_objs_affected_ids = array();
1697
-                foreach ($models_affected_key_columns as $row) {
1698
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1699
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1700
-                }
1701
-            }
1702
-            if (! $model_objs_affected_ids) {
1703
-                //wait wait wait- if nothing was affected let's stop here
1704
-                return 0;
1705
-            }
1706
-            foreach ($model_objs_affected_ids as $id) {
1707
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1708
-                if ($model_obj_in_entity_map) {
1709
-                    foreach ($fields_n_values as $field => $new_value) {
1710
-                        $model_obj_in_entity_map->set($field, $new_value);
1711
-                    }
1712
-                }
1713
-            }
1714
-            //if there is a primary key on this model, we can now do a slight optimization
1715
-            if ($this->has_primary_key_field()) {
1716
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1717
-                $query_params = array(
1718
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1719
-                    'limit'                    => count($model_objs_affected_ids),
1720
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1721
-                );
1722
-            }
1723
-        }
1724
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1725
-        $SQL = "UPDATE "
1726
-               . $model_query_info->get_full_join_sql()
1727
-               . " SET "
1728
-               . $this->_construct_update_sql($fields_n_values)
1729
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1730
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1731
-        /**
1732
-         * Action called after a model update call has been made.
1733
-         *
1734
-         * @param EEM_Base $model
1735
-         * @param array    $fields_n_values the updated fields and their new values
1736
-         * @param array    $query_params    @see EEM_Base::get_all()
1737
-         * @param int      $rows_affected
1738
-         */
1739
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1740
-        return $rows_affected;//how many supposedly got updated
1741
-    }
1742
-
1743
-
1744
-
1745
-    /**
1746
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1747
-     * are teh values of the field specified (or by default the primary key field)
1748
-     * that matched the query params. Note that you should pass the name of the
1749
-     * model FIELD, not the database table's column name.
1750
-     *
1751
-     * @param array  $query_params @see EEM_Base::get_all()
1752
-     * @param string $field_to_select
1753
-     * @return array just like $wpdb->get_col()
1754
-     * @throws \EE_Error
1755
-     */
1756
-    public function get_col($query_params = array(), $field_to_select = null)
1757
-    {
1758
-        if ($field_to_select) {
1759
-            $field = $this->field_settings_for($field_to_select);
1760
-        } elseif ($this->has_primary_key_field()) {
1761
-            $field = $this->get_primary_key_field();
1762
-        } else {
1763
-            //no primary key, just grab the first column
1764
-            $field = reset($this->field_settings());
1765
-        }
1766
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1767
-        $select_expressions = $field->get_qualified_column();
1768
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
-        return $this->_do_wpdb_query('get_col', array($SQL));
1770
-    }
1771
-
1772
-
1773
-
1774
-    /**
1775
-     * Returns a single column value for a single row from the database
1776
-     *
1777
-     * @param array  $query_params    @see EEM_Base::get_all()
1778
-     * @param string $field_to_select @see EEM_Base::get_col()
1779
-     * @return string
1780
-     * @throws \EE_Error
1781
-     */
1782
-    public function get_var($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        $query_params['limit'] = 1;
1785
-        $col = $this->get_col($query_params, $field_to_select);
1786
-        if (! empty($col)) {
1787
-            return reset($col);
1788
-        } else {
1789
-            return null;
1790
-        }
1791
-    }
1792
-
1793
-
1794
-
1795
-    /**
1796
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1797
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1798
-     * injection, but currently no further filtering is done
1799
-     *
1800
-     * @global      $wpdb
1801
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1802
-     *                               be updated to in the DB
1803
-     * @return string of SQL
1804
-     * @throws \EE_Error
1805
-     */
1806
-    public function _construct_update_sql($fields_n_values)
1807
-    {
1808
-        /** @type WPDB $wpdb */
1809
-        global $wpdb;
1810
-        $cols_n_values = array();
1811
-        foreach ($fields_n_values as $field_name => $value) {
1812
-            $field_obj = $this->field_settings_for($field_name);
1813
-            //if the value is NULL, we want to assign the value to that.
1814
-            //wpdb->prepare doesn't really handle that properly
1815
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1816
-            $value_sql = $prepared_value === null ? 'NULL'
1817
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1818
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
-        }
1820
-        return implode(",", $cols_n_values);
1821
-    }
1822
-
1823
-
1824
-
1825
-    /**
1826
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1827
-     * Performs a HARD delete, meaning the database row should always be removed,
1828
-     * not just have a flag field on it switched
1829
-     * Wrapper for EEM_Base::delete_permanently()
1830
-     *
1831
-     * @param mixed $id
1832
-     * @return boolean whether the row got deleted or not
1833
-     * @throws \EE_Error
1834
-     */
1835
-    public function delete_permanently_by_ID($id)
1836
-    {
1837
-        return $this->delete_permanently(
1838
-            array(
1839
-                array($this->get_primary_key_field()->get_name() => $id),
1840
-                'limit' => 1,
1841
-            )
1842
-        );
1843
-    }
1844
-
1845
-
1846
-
1847
-    /**
1848
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
-     * Wrapper for EEM_Base::delete()
1850
-     *
1851
-     * @param mixed $id
1852
-     * @return boolean whether the row got deleted or not
1853
-     * @throws \EE_Error
1854
-     */
1855
-    public function delete_by_ID($id)
1856
-    {
1857
-        return $this->delete(
1858
-            array(
1859
-                array($this->get_primary_key_field()->get_name() => $id),
1860
-                'limit' => 1,
1861
-            )
1862
-        );
1863
-    }
1864
-
1865
-
1866
-
1867
-    /**
1868
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1869
-     * meaning if the model has a field that indicates its been "trashed" or
1870
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1871
-     *
1872
-     * @see EEM_Base::delete_permanently
1873
-     * @param array   $query_params
1874
-     * @param boolean $allow_blocking
1875
-     * @return int how many rows got deleted
1876
-     * @throws \EE_Error
1877
-     */
1878
-    public function delete($query_params, $allow_blocking = true)
1879
-    {
1880
-        return $this->delete_permanently($query_params, $allow_blocking);
1881
-    }
1882
-
1883
-
1884
-
1885
-    /**
1886
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1887
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1888
-     * as archived, not actually deleted
1889
-     *
1890
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1891
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1892
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1893
-     *                                deletes regardless of other objects which may depend on it. Its generally
1894
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1895
-     *                                DB
1896
-     * @return int how many rows got deleted
1897
-     * @throws \EE_Error
1898
-     */
1899
-    public function delete_permanently($query_params, $allow_blocking = true)
1900
-    {
1901
-        /**
1902
-         * Action called just before performing a real deletion query. You can use the
1903
-         * model and its $query_params to find exactly which items will be deleted
1904
-         *
1905
-         * @param EEM_Base $model
1906
-         * @param array    $query_params   @see EEM_Base::get_all()
1907
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1908
-         *                                 to block (prevent) this deletion
1909
-         */
1910
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1911
-        //some MySQL databases may be running safe mode, which may restrict
1912
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1913
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1914
-        //to delete them
1915
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1916
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1917
-        if ($deletion_where) {
1918
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1919
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1920
-            $table_aliases = array_keys($this->_tables);
1921
-            $SQL = "DELETE "
1922
-                   . implode(", ", $table_aliases)
1923
-                   . " FROM "
1924
-                   . $model_query_info->get_full_join_sql()
1925
-                   . " WHERE "
1926
-                   . $deletion_where;
1927
-            //		/echo "delete sql:$SQL";
1928
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1929
-        } else {
1930
-            $rows_deleted = 0;
1931
-        }
1932
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1933
-        if ($this->has_primary_key_field()) {
1934
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1935
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1936
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1937
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1938
-                }
1939
-            }
1940
-        }
1941
-        /**
1942
-         * Action called just after performing a real deletion query. Although at this point the
1943
-         * items should have been deleted
1944
-         *
1945
-         * @param EEM_Base $model
1946
-         * @param array    $query_params @see EEM_Base::get_all()
1947
-         * @param int      $rows_deleted
1948
-         */
1949
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1950
-        return $rows_deleted;//how many supposedly got deleted
1951
-    }
1952
-
1953
-
1954
-
1955
-    /**
1956
-     * Checks all the relations that throw error messages when there are blocking related objects
1957
-     * for related model objects. If there are any related model objects on those relations,
1958
-     * adds an EE_Error, and return true
1959
-     *
1960
-     * @param EE_Base_Class|int $this_model_obj_or_id
1961
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1962
-     *                                                 should be ignored when determining whether there are related
1963
-     *                                                 model objects which block this model object's deletion. Useful
1964
-     *                                                 if you know A is related to B and are considering deleting A,
1965
-     *                                                 but want to see if A has any other objects blocking its deletion
1966
-     *                                                 before removing the relation between A and B
1967
-     * @return boolean
1968
-     * @throws \EE_Error
1969
-     */
1970
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1971
-    {
1972
-        //first, if $ignore_this_model_obj was supplied, get its model
1973
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1974
-            $ignored_model = $ignore_this_model_obj->get_model();
1975
-        } else {
1976
-            $ignored_model = null;
1977
-        }
1978
-        //now check all the relations of $this_model_obj_or_id and see if there
1979
-        //are any related model objects blocking it?
1980
-        $is_blocked = false;
1981
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1982
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1983
-                //if $ignore_this_model_obj was supplied, then for the query
1984
-                //on that model needs to be told to ignore $ignore_this_model_obj
1985
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1986
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1987
-                        array(
1988
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1989
-                                '!=',
1990
-                                $ignore_this_model_obj->ID(),
1991
-                            ),
1992
-                        ),
1993
-                    ));
1994
-                } else {
1995
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1996
-                }
1997
-                if ($related_model_objects) {
1998
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1999
-                    $is_blocked = true;
2000
-                }
2001
-            }
2002
-        }
2003
-        return $is_blocked;
2004
-    }
2005
-
2006
-
2007
-
2008
-    /**
2009
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2010
-     * well.
2011
-     *
2012
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2013
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2014
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2015
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2016
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2017
-     *                                      easily corrupt your DB
2018
-     * @throws EE_Error
2019
-     * @return string    everything that comes after the WHERE statement.
2020
-     */
2021
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2022
-    {
2023
-        if ($this->has_primary_key_field()) {
2024
-            $primary_table = $this->_get_main_table();
2025
-            $other_tables = $this->_get_other_tables();
2026
-            $deletes = $query = array();
2027
-            foreach ($objects_for_deletion as $delete_object) {
2028
-                //before we mark this object for deletion,
2029
-                //make sure there's no related objects blocking its deletion (if we're checking)
2030
-                if (
2031
-                    $allow_blocking
2032
-                    && $this->delete_is_blocked_by_related_models(
2033
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2034
-                    )
2035
-                ) {
2036
-                    continue;
2037
-                }
2038
-                //primary table deletes
2039
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2040
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2041
-                }
2042
-                //other tables
2043
-                if (! empty($other_tables)) {
2044
-                    foreach ($other_tables as $ot) {
2045
-                        //first check if we've got the foreign key column here.
2046
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2047
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2048
-                        }
2049
-                        // wait! it's entirely possible that we'll have a the primary key
2050
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2051
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2052
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2053
-                        }
2054
-                        // finally, it is possible that the fk for this table is found
2055
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2056
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2057
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2058
-                        }
2059
-                    }
2060
-                }
2061
-            }
2062
-            //we should have deletes now, so let's just go through and setup the where statement
2063
-            foreach ($deletes as $column => $values) {
2064
-                //make sure we have unique $values;
2065
-                $values = array_unique($values);
2066
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
-            }
2068
-            return ! empty($query) ? implode(' AND ', $query) : '';
2069
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2070
-            $ways_to_identify_a_row = array();
2071
-            $fields = $this->get_combined_primary_key_fields();
2072
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2073
-            foreach ($objects_for_deletion as $delete_object) {
2074
-                $values_for_each_cpk_for_a_row = array();
2075
-                foreach ($fields as $cpk_field) {
2076
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2077
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2078
-                                                           . "="
2079
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2080
-                    }
2081
-                }
2082
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
-            }
2084
-            return implode(" OR ", $ways_to_identify_a_row);
2085
-        } else {
2086
-            //so there's no primary key and no combined key...
2087
-            //sorry, can't help you
2088
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2089
-                "event_espresso"), get_class($this)));
2090
-        }
2091
-    }
2092
-
2093
-
2094
-
2095
-    /**
2096
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2097
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2098
-     * column
2099
-     *
2100
-     * @param array  $query_params   like EEM_Base::get_all's
2101
-     * @param string $field_to_count field on model to count by (not column name)
2102
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2103
-     *                               that by the setting $distinct to TRUE;
2104
-     * @return int
2105
-     * @throws \EE_Error
2106
-     */
2107
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2108
-    {
2109
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2110
-        if ($field_to_count) {
2111
-            $field_obj = $this->field_settings_for($field_to_count);
2112
-            $column_to_count = $field_obj->get_qualified_column();
2113
-        } elseif ($this->has_primary_key_field()) {
2114
-            $pk_field_obj = $this->get_primary_key_field();
2115
-            $column_to_count = $pk_field_obj->get_qualified_column();
2116
-        } else {
2117
-            //there's no primary key
2118
-            //if we're counting distinct items, and there's no primary key,
2119
-            //we need to list out the columns for distinction;
2120
-            //otherwise we can just use star
2121
-            if ($distinct) {
2122
-                $columns_to_use = array();
2123
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2124
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2125
-                }
2126
-                $column_to_count = implode(',', $columns_to_use);
2127
-            } else {
2128
-                $column_to_count = '*';
2129
-            }
2130
-        }
2131
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2132
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2133
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2134
-    }
2135
-
2136
-
2137
-
2138
-    /**
2139
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2140
-     *
2141
-     * @param array  $query_params like EEM_Base::get_all
2142
-     * @param string $field_to_sum name of field (array key in $_fields array)
2143
-     * @return float
2144
-     * @throws \EE_Error
2145
-     */
2146
-    public function sum($query_params, $field_to_sum = null)
2147
-    {
2148
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2149
-        if ($field_to_sum) {
2150
-            $field_obj = $this->field_settings_for($field_to_sum);
2151
-        } else {
2152
-            $field_obj = $this->get_primary_key_field();
2153
-        }
2154
-        $column_to_count = $field_obj->get_qualified_column();
2155
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2157
-        $data_type = $field_obj->get_wpdb_data_type();
2158
-        if ($data_type === '%d' || $data_type === '%s') {
2159
-            return (float)$return_value;
2160
-        } else {//must be %f
2161
-            return (float)$return_value;
2162
-        }
2163
-    }
2164
-
2165
-
2166
-
2167
-    /**
2168
-     * Just calls the specified method on $wpdb with the given arguments
2169
-     * Consolidates a little extra error handling code
2170
-     *
2171
-     * @param string $wpdb_method
2172
-     * @param array  $arguments_to_provide
2173
-     * @throws EE_Error
2174
-     * @global wpdb  $wpdb
2175
-     * @return mixed
2176
-     */
2177
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2178
-    {
2179
-        //if we're in maintenance mode level 2, DON'T run any queries
2180
-        //because level 2 indicates the database needs updating and
2181
-        //is probably out of sync with the code
2182
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2184
-                "event_espresso")));
2185
-        }
2186
-        /** @type WPDB $wpdb */
2187
-        global $wpdb;
2188
-        if (! method_exists($wpdb, $wpdb_method)) {
2189
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2190
-                'event_espresso'), $wpdb_method));
2191
-        }
2192
-        if (WP_DEBUG) {
2193
-            $old_show_errors_value = $wpdb->show_errors;
2194
-            $wpdb->show_errors(false);
2195
-        }
2196
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2197
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2198
-        if (WP_DEBUG) {
2199
-            $wpdb->show_errors($old_show_errors_value);
2200
-            if (! empty($wpdb->last_error)) {
2201
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2202
-            } elseif ($result === false) {
2203
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2204
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2205
-            }
2206
-        } elseif ($result === false) {
2207
-            EE_Error::add_error(
2208
-                sprintf(
2209
-                    __('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"',
2210
-                        'event_espresso'),
2211
-                    $wpdb_method,
2212
-                    var_export($arguments_to_provide, true),
2213
-                    $wpdb->last_error
2214
-                ),
2215
-                __FILE__,
2216
-                __FUNCTION__,
2217
-                __LINE__
2218
-            );
2219
-        }
2220
-        return $result;
2221
-    }
2222
-
2223
-
2224
-
2225
-    /**
2226
-     * Attempts to run the indicated WPDB method with the provided arguments,
2227
-     * and if there's an error tries to verify the DB is correct. Uses
2228
-     * the static property EEM_Base::$_db_verification_level to determine whether
2229
-     * we should try to fix the EE core db, the addons, or just give up
2230
-     *
2231
-     * @param string $wpdb_method
2232
-     * @param array  $arguments_to_provide
2233
-     * @return mixed
2234
-     */
2235
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2236
-    {
2237
-        /** @type WPDB $wpdb */
2238
-        global $wpdb;
2239
-        $wpdb->last_error = null;
2240
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2241
-        // was there an error running the query? but we don't care on new activations
2242
-        // (we're going to setup the DB anyway on new activations)
2243
-        if (($result === false || ! empty($wpdb->last_error))
2244
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2245
-        ) {
2246
-            switch (EEM_Base::$_db_verification_level) {
2247
-                case EEM_Base::db_verified_none :
2248
-                    // let's double-check core's DB
2249
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2250
-                    break;
2251
-                case EEM_Base::db_verified_core :
2252
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2253
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2254
-                    break;
2255
-                case EEM_Base::db_verified_addons :
2256
-                    // ummmm... you in trouble
2257
-                    return $result;
2258
-                    break;
2259
-            }
2260
-            if (! empty($error_message)) {
2261
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2262
-                trigger_error($error_message);
2263
-            }
2264
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2265
-        }
2266
-        return $result;
2267
-    }
2268
-
2269
-
2270
-
2271
-    /**
2272
-     * Verifies the EE core database is up-to-date and records that we've done it on
2273
-     * EEM_Base::$_db_verification_level
2274
-     *
2275
-     * @param string $wpdb_method
2276
-     * @param array  $arguments_to_provide
2277
-     * @return string
2278
-     */
2279
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2280
-    {
2281
-        /** @type WPDB $wpdb */
2282
-        global $wpdb;
2283
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2284
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2285
-        $error_message = sprintf(
2286
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2287
-                'event_espresso'),
2288
-            $wpdb->last_error,
2289
-            $wpdb_method,
2290
-            wp_json_encode($arguments_to_provide)
2291
-        );
2292
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2293
-        return $error_message;
2294
-    }
2295
-
2296
-
2297
-
2298
-    /**
2299
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2300
-     * EEM_Base::$_db_verification_level
2301
-     *
2302
-     * @param $wpdb_method
2303
-     * @param $arguments_to_provide
2304
-     * @return string
2305
-     */
2306
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2307
-    {
2308
-        /** @type WPDB $wpdb */
2309
-        global $wpdb;
2310
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2311
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2312
-        $error_message = sprintf(
2313
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2314
-                'event_espresso'),
2315
-            $wpdb->last_error,
2316
-            $wpdb_method,
2317
-            wp_json_encode($arguments_to_provide)
2318
-        );
2319
-        EE_System::instance()->initialize_addons();
2320
-        return $error_message;
2321
-    }
2322
-
2323
-
2324
-
2325
-    /**
2326
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2327
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2328
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2329
-     * ..."
2330
-     *
2331
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2332
-     * @return string
2333
-     */
2334
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2335
-    {
2336
-        return " FROM " . $model_query_info->get_full_join_sql() .
2337
-               $model_query_info->get_where_sql() .
2338
-               $model_query_info->get_group_by_sql() .
2339
-               $model_query_info->get_having_sql() .
2340
-               $model_query_info->get_order_by_sql() .
2341
-               $model_query_info->get_limit_sql();
2342
-    }
2343
-
2344
-
2345
-
2346
-    /**
2347
-     * Set to easily debug the next X queries ran from this model.
2348
-     *
2349
-     * @param int $count
2350
-     */
2351
-    public function show_next_x_db_queries($count = 1)
2352
-    {
2353
-        $this->_show_next_x_db_queries = $count;
2354
-    }
2355
-
2356
-
2357
-
2358
-    /**
2359
-     * @param $sql_query
2360
-     */
2361
-    public function show_db_query_if_previously_requested($sql_query)
2362
-    {
2363
-        if ($this->_show_next_x_db_queries > 0) {
2364
-            echo $sql_query;
2365
-            $this->_show_next_x_db_queries--;
2366
-        }
2367
-    }
2368
-
2369
-
2370
-
2371
-    /**
2372
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2373
-     * There are the 3 cases:
2374
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2375
-     * $otherModelObject has no ID, it is first saved.
2376
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2377
-     * has no ID, it is first saved.
2378
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2379
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2380
-     * join table
2381
-     *
2382
-     * @param        EE_Base_Class                     /int $thisModelObject
2383
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2384
-     * @param string $relationName                     , key in EEM_Base::_relations
2385
-     *                                                 an attendee to a group, you also want to specify which role they
2386
-     *                                                 will have in that group. So you would use this parameter to
2387
-     *                                                 specify array('role-column-name'=>'role-id')
2388
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2389
-     *                                                 to for relation to methods that allow you to further specify
2390
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2391
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2392
-     *                                                 because these will be inserted in any new rows created as well.
2393
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2394
-     * @throws \EE_Error
2395
-     */
2396
-    public function add_relationship_to(
2397
-        $id_or_obj,
2398
-        $other_model_id_or_obj,
2399
-        $relationName,
2400
-        $extra_join_model_fields_n_values = array()
2401
-    ) {
2402
-        $relation_obj = $this->related_settings_for($relationName);
2403
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2404
-    }
2405
-
2406
-
2407
-
2408
-    /**
2409
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2410
-     * There are the 3 cases:
2411
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2412
-     * error
2413
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2414
-     * an error
2415
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2416
-     *
2417
-     * @param        EE_Base_Class /int $id_or_obj
2418
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2419
-     * @param string $relationName key in EEM_Base::_relations
2420
-     * @return boolean of success
2421
-     * @throws \EE_Error
2422
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2423
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2424
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2425
-     *                             because these will be inserted in any new rows created as well.
2426
-     */
2427
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2428
-    {
2429
-        $relation_obj = $this->related_settings_for($relationName);
2430
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2431
-    }
2432
-
2433
-
2434
-
2435
-    /**
2436
-     * @param mixed           $id_or_obj
2437
-     * @param string          $relationName
2438
-     * @param array           $where_query_params
2439
-     * @param EE_Base_Class[] objects to which relations were removed
2440
-     * @return \EE_Base_Class[]
2441
-     * @throws \EE_Error
2442
-     */
2443
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2444
-    {
2445
-        $relation_obj = $this->related_settings_for($relationName);
2446
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2447
-    }
2448
-
2449
-
2450
-
2451
-    /**
2452
-     * Gets all the related items of the specified $model_name, using $query_params.
2453
-     * Note: by default, we remove the "default query params"
2454
-     * because we want to get even deleted items etc.
2455
-     *
2456
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2457
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2458
-     * @param array  $query_params like EEM_Base::get_all
2459
-     * @return EE_Base_Class[]
2460
-     * @throws \EE_Error
2461
-     */
2462
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2463
-    {
2464
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2465
-        $relation_settings = $this->related_settings_for($model_name);
2466
-        return $relation_settings->get_all_related($model_obj, $query_params);
2467
-    }
2468
-
2469
-
2470
-
2471
-    /**
2472
-     * Deletes all the model objects across the relation indicated by $model_name
2473
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2474
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2475
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2476
-     *
2477
-     * @param EE_Base_Class|int|string $id_or_obj
2478
-     * @param string                   $model_name
2479
-     * @param array                    $query_params
2480
-     * @return int how many deleted
2481
-     * @throws \EE_Error
2482
-     */
2483
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2484
-    {
2485
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2486
-        $relation_settings = $this->related_settings_for($model_name);
2487
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2488
-    }
2489
-
2490
-
2491
-
2492
-    /**
2493
-     * Hard deletes all the model objects across the relation indicated by $model_name
2494
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2495
-     * the model objects can't be hard deleted because of blocking related model objects,
2496
-     * just does a soft-delete on them instead.
2497
-     *
2498
-     * @param EE_Base_Class|int|string $id_or_obj
2499
-     * @param string                   $model_name
2500
-     * @param array                    $query_params
2501
-     * @return int how many deleted
2502
-     * @throws \EE_Error
2503
-     */
2504
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2505
-    {
2506
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2507
-        $relation_settings = $this->related_settings_for($model_name);
2508
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2509
-    }
2510
-
2511
-
2512
-
2513
-    /**
2514
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2515
-     * unless otherwise specified in the $query_params
2516
-     *
2517
-     * @param        int             /EE_Base_Class $id_or_obj
2518
-     * @param string $model_name     like 'Event', or 'Registration'
2519
-     * @param array  $query_params   like EEM_Base::get_all's
2520
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2521
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2522
-     *                               that by the setting $distinct to TRUE;
2523
-     * @return int
2524
-     * @throws \EE_Error
2525
-     */
2526
-    public function count_related(
2527
-        $id_or_obj,
2528
-        $model_name,
2529
-        $query_params = array(),
2530
-        $field_to_count = null,
2531
-        $distinct = false
2532
-    ) {
2533
-        $related_model = $this->get_related_model_obj($model_name);
2534
-        //we're just going to use the query params on the related model's normal get_all query,
2535
-        //except add a condition to say to match the current mod
2536
-        if (! isset($query_params['default_where_conditions'])) {
2537
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2538
-        }
2539
-        $this_model_name = $this->get_this_model_name();
2540
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2541
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
-        return $related_model->count($query_params, $field_to_count, $distinct);
2543
-    }
2544
-
2545
-
2546
-
2547
-    /**
2548
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2549
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2550
-     *
2551
-     * @param        int           /EE_Base_Class $id_or_obj
2552
-     * @param string $model_name   like 'Event', or 'Registration'
2553
-     * @param array  $query_params like EEM_Base::get_all's
2554
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2555
-     * @return float
2556
-     * @throws \EE_Error
2557
-     */
2558
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2559
-    {
2560
-        $related_model = $this->get_related_model_obj($model_name);
2561
-        if (! is_array($query_params)) {
2562
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2563
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2564
-                    gettype($query_params)), '4.6.0');
2565
-            $query_params = array();
2566
-        }
2567
-        //we're just going to use the query params on the related model's normal get_all query,
2568
-        //except add a condition to say to match the current mod
2569
-        if (! isset($query_params['default_where_conditions'])) {
2570
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2571
-        }
2572
-        $this_model_name = $this->get_this_model_name();
2573
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2574
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
-        return $related_model->sum($query_params, $field_to_sum);
2576
-    }
2577
-
2578
-
2579
-
2580
-    /**
2581
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2582
-     * $modelObject
2583
-     *
2584
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2585
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2586
-     * @param array               $query_params     like EEM_Base::get_all's
2587
-     * @return EE_Base_Class
2588
-     * @throws \EE_Error
2589
-     */
2590
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2591
-    {
2592
-        $query_params['limit'] = 1;
2593
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2594
-        if ($results) {
2595
-            return array_shift($results);
2596
-        } else {
2597
-            return null;
2598
-        }
2599
-    }
2600
-
2601
-
2602
-
2603
-    /**
2604
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2605
-     *
2606
-     * @return string
2607
-     */
2608
-    public function get_this_model_name()
2609
-    {
2610
-        return str_replace("EEM_", "", get_class($this));
2611
-    }
2612
-
2613
-
2614
-
2615
-    /**
2616
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2617
-     *
2618
-     * @return EE_Any_Foreign_Model_Name_Field
2619
-     * @throws EE_Error
2620
-     */
2621
-    public function get_field_containing_related_model_name()
2622
-    {
2623
-        foreach ($this->field_settings(true) as $field) {
2624
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2625
-                $field_with_model_name = $field;
2626
-            }
2627
-        }
2628
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2630
-                $this->get_this_model_name()));
2631
-        }
2632
-        return $field_with_model_name;
2633
-    }
2634
-
2635
-
2636
-
2637
-    /**
2638
-     * Inserts a new entry into the database, for each table.
2639
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2640
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2641
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2642
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2643
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2644
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2645
-     *
2646
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2647
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2648
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2649
-     *                              of EEM_Base)
2650
-     * @return int new primary key on main table that got inserted
2651
-     * @throws EE_Error
2652
-     */
2653
-    public function insert($field_n_values)
2654
-    {
2655
-        /**
2656
-         * Filters the fields and their values before inserting an item using the models
2657
-         *
2658
-         * @param array    $fields_n_values keys are the fields and values are their new values
2659
-         * @param EEM_Base $model           the model used
2660
-         */
2661
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2663
-            $main_table = $this->_get_main_table();
2664
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2665
-            if ($new_id !== false) {
2666
-                foreach ($this->_get_other_tables() as $other_table) {
2667
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2668
-                }
2669
-            }
2670
-            /**
2671
-             * Done just after attempting to insert a new model object
2672
-             *
2673
-             * @param EEM_Base   $model           used
2674
-             * @param array      $fields_n_values fields and their values
2675
-             * @param int|string the              ID of the newly-inserted model object
2676
-             */
2677
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2678
-            return $new_id;
2679
-        } else {
2680
-            return false;
2681
-        }
2682
-    }
2683
-
2684
-
2685
-
2686
-    /**
2687
-     * Checks that the result would satisfy the unique indexes on this model
2688
-     *
2689
-     * @param array  $field_n_values
2690
-     * @param string $action
2691
-     * @return boolean
2692
-     * @throws \EE_Error
2693
-     */
2694
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2695
-    {
2696
-        foreach ($this->unique_indexes() as $index_name => $index) {
2697
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2698
-            if ($this->exists(array($uniqueness_where_params))) {
2699
-                EE_Error::add_error(
2700
-                    sprintf(
2701
-                        __(
2702
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2703
-                            "event_espresso"
2704
-                        ),
2705
-                        $action,
2706
-                        $this->_get_class_name(),
2707
-                        $index_name,
2708
-                        implode(",", $index->field_names()),
2709
-                        http_build_query($uniqueness_where_params)
2710
-                    ),
2711
-                    __FILE__,
2712
-                    __FUNCTION__,
2713
-                    __LINE__
2714
-                );
2715
-                return false;
2716
-            }
2717
-        }
2718
-        return true;
2719
-    }
2720
-
2721
-
2722
-
2723
-    /**
2724
-     * Checks the database for an item that conflicts (ie, if this item were
2725
-     * saved to the DB would break some uniqueness requirement, like a primary key
2726
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2727
-     * can be either an EE_Base_Class or an array of fields n values
2728
-     *
2729
-     * @param EE_Base_Class|array $obj_or_fields_array
2730
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2731
-     *                                                 when looking for conflicts
2732
-     *                                                 (ie, if false, we ignore the model object's primary key
2733
-     *                                                 when finding "conflicts". If true, it's also considered).
2734
-     *                                                 Only works for INT primary key,
2735
-     *                                                 STRING primary keys cannot be ignored
2736
-     * @throws EE_Error
2737
-     * @return EE_Base_Class|array
2738
-     */
2739
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2740
-    {
2741
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2742
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2743
-        } elseif (is_array($obj_or_fields_array)) {
2744
-            $fields_n_values = $obj_or_fields_array;
2745
-        } else {
2746
-            throw new EE_Error(
2747
-                sprintf(
2748
-                    __(
2749
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2750
-                        "event_espresso"
2751
-                    ),
2752
-                    get_class($this),
2753
-                    $obj_or_fields_array
2754
-                )
2755
-            );
2756
-        }
2757
-        $query_params = array();
2758
-        if ($this->has_primary_key_field()
2759
-            && ($include_primary_key
2760
-                || $this->get_primary_key_field()
2761
-                   instanceof
2762
-                   EE_Primary_Key_String_Field)
2763
-            && isset($fields_n_values[$this->primary_key_name()])
2764
-        ) {
2765
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2766
-        }
2767
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2768
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2769
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
-        }
2771
-        //if there is nothing to base this search on, then we shouldn't find anything
2772
-        if (empty($query_params)) {
2773
-            return array();
2774
-        } else {
2775
-            return $this->get_one($query_params);
2776
-        }
2777
-    }
2778
-
2779
-
2780
-
2781
-    /**
2782
-     * Like count, but is optimized and returns a boolean instead of an int
2783
-     *
2784
-     * @param array $query_params
2785
-     * @return boolean
2786
-     * @throws \EE_Error
2787
-     */
2788
-    public function exists($query_params)
2789
-    {
2790
-        $query_params['limit'] = 1;
2791
-        return $this->count($query_params) > 0;
2792
-    }
2793
-
2794
-
2795
-
2796
-    /**
2797
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2798
-     *
2799
-     * @param int|string $id
2800
-     * @return boolean
2801
-     * @throws \EE_Error
2802
-     */
2803
-    public function exists_by_ID($id)
2804
-    {
2805
-        return $this->exists(
2806
-            array(
2807
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2808
-                array(
2809
-                    $this->primary_key_name() => $id,
2810
-                ),
2811
-            )
2812
-        );
2813
-    }
2814
-
2815
-
2816
-
2817
-    /**
2818
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2819
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2820
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2821
-     * on the main table)
2822
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2823
-     * cases where we want to call it directly rather than via insert().
2824
-     *
2825
-     * @access   protected
2826
-     * @param EE_Table_Base $table
2827
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2828
-     *                                       float
2829
-     * @param int           $new_id          for now we assume only int keys
2830
-     * @throws EE_Error
2831
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2832
-     * @return int ID of new row inserted, or FALSE on failure
2833
-     */
2834
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2835
-    {
2836
-        global $wpdb;
2837
-        $insertion_col_n_values = array();
2838
-        $format_for_insertion = array();
2839
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2840
-        foreach ($fields_on_table as $field_name => $field_obj) {
2841
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2842
-            if ($field_obj->is_auto_increment()) {
2843
-                continue;
2844
-            }
2845
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2846
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2847
-            if ($prepared_value !== null) {
2848
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2849
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2850
-            }
2851
-        }
2852
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2853
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2854
-            //so add the fk to the main table as a column
2855
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2856
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
-        }
2858
-        //insert the new entry
2859
-        $result = $this->_do_wpdb_query('insert',
2860
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2861
-        if ($result === false) {
2862
-            return false;
2863
-        }
2864
-        //ok, now what do we return for the ID of the newly-inserted thing?
2865
-        if ($this->has_primary_key_field()) {
2866
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2867
-                return $wpdb->insert_id;
2868
-            } else {
2869
-                //it's not an auto-increment primary key, so
2870
-                //it must have been supplied
2871
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2872
-            }
2873
-        } else {
2874
-            //we can't return a  primary key because there is none. instead return
2875
-            //a unique string indicating this model
2876
-            return $this->get_index_primary_key_string($fields_n_values);
2877
-        }
2878
-    }
2879
-
2880
-
2881
-
2882
-    /**
2883
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2884
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2885
-     * and there is no default, we pass it along. WPDB will take care of it)
2886
-     *
2887
-     * @param EE_Model_Field_Base $field_obj
2888
-     * @param array               $fields_n_values
2889
-     * @return mixed string|int|float depending on what the table column will be expecting
2890
-     * @throws \EE_Error
2891
-     */
2892
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2893
-    {
2894
-        //if this field doesn't allow nullable, don't allow it
2895
-        if (! $field_obj->is_nullable()
2896
-            && (
2897
-                ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2898
-        ) {
2899
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2900
-        }
2901
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2902
-            : null;
2903
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2904
-    }
2905
-
2906
-
2907
-
2908
-    /**
2909
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2910
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2911
-     * the field's prepare_for_set() method.
2912
-     *
2913
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2914
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2915
-     *                                   top of file)
2916
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2917
-     *                                   $value is a custom selection
2918
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2919
-     */
2920
-    private function _prepare_value_for_use_in_db($value, $field)
2921
-    {
2922
-        if ($field && $field instanceof EE_Model_Field_Base) {
2923
-            switch ($this->_values_already_prepared_by_model_object) {
2924
-                /** @noinspection PhpMissingBreakStatementInspection */
2925
-                case self::not_prepared_by_model_object:
2926
-                    $value = $field->prepare_for_set($value);
2927
-                //purposefully left out "return"
2928
-                case self::prepared_by_model_object:
2929
-                    $value = $field->prepare_for_use_in_db($value);
2930
-                case self::prepared_for_use_in_db:
2931
-                    //leave the value alone
2932
-            }
2933
-            return $value;
2934
-        } else {
2935
-            return $value;
2936
-        }
2937
-    }
2938
-
2939
-
2940
-
2941
-    /**
2942
-     * Returns the main table on this model
2943
-     *
2944
-     * @return EE_Primary_Table
2945
-     * @throws EE_Error
2946
-     */
2947
-    protected function _get_main_table()
2948
-    {
2949
-        foreach ($this->_tables as $table) {
2950
-            if ($table instanceof EE_Primary_Table) {
2951
-                return $table;
2952
-            }
2953
-        }
2954
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2955
-            'event_espresso'), get_class($this)));
2956
-    }
2957
-
2958
-
2959
-
2960
-    /**
2961
-     * table
2962
-     * returns EE_Primary_Table table name
2963
-     *
2964
-     * @return string
2965
-     * @throws \EE_Error
2966
-     */
2967
-    public function table()
2968
-    {
2969
-        return $this->_get_main_table()->get_table_name();
2970
-    }
2971
-
2972
-
2973
-
2974
-    /**
2975
-     * table
2976
-     * returns first EE_Secondary_Table table name
2977
-     *
2978
-     * @return string
2979
-     */
2980
-    public function second_table()
2981
-    {
2982
-        // grab second table from tables array
2983
-        $second_table = end($this->_tables);
2984
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2985
-    }
2986
-
2987
-
2988
-
2989
-    /**
2990
-     * get_table_obj_by_alias
2991
-     * returns table name given it's alias
2992
-     *
2993
-     * @param string $table_alias
2994
-     * @return EE_Primary_Table | EE_Secondary_Table
2995
-     */
2996
-    public function get_table_obj_by_alias($table_alias = '')
2997
-    {
2998
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2999
-    }
3000
-
3001
-
3002
-
3003
-    /**
3004
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3005
-     *
3006
-     * @return EE_Secondary_Table[]
3007
-     */
3008
-    protected function _get_other_tables()
3009
-    {
3010
-        $other_tables = array();
3011
-        foreach ($this->_tables as $table_alias => $table) {
3012
-            if ($table instanceof EE_Secondary_Table) {
3013
-                $other_tables[$table_alias] = $table;
3014
-            }
3015
-        }
3016
-        return $other_tables;
3017
-    }
3018
-
3019
-
3020
-
3021
-    /**
3022
-     * Finds all the fields that correspond to the given table
3023
-     *
3024
-     * @param string $table_alias , array key in EEM_Base::_tables
3025
-     * @return EE_Model_Field_Base[]
3026
-     */
3027
-    public function _get_fields_for_table($table_alias)
3028
-    {
3029
-        return $this->_fields[$table_alias];
3030
-    }
3031
-
3032
-
3033
-
3034
-    /**
3035
-     * Recurses through all the where parameters, and finds all the related models we'll need
3036
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3037
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3038
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3039
-     * related Registration, Transaction, and Payment models.
3040
-     *
3041
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3042
-     * @return EE_Model_Query_Info_Carrier
3043
-     * @throws \EE_Error
3044
-     */
3045
-    public function _extract_related_models_from_query($query_params)
3046
-    {
3047
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3048
-        if (array_key_exists(0, $query_params)) {
3049
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3050
-        }
3051
-        if (array_key_exists('group_by', $query_params)) {
3052
-            if (is_array($query_params['group_by'])) {
3053
-                $this->_extract_related_models_from_sub_params_array_values(
3054
-                    $query_params['group_by'],
3055
-                    $query_info_carrier,
3056
-                    'group_by'
3057
-                );
3058
-            } elseif (! empty ($query_params['group_by'])) {
3059
-                $this->_extract_related_model_info_from_query_param(
3060
-                    $query_params['group_by'],
3061
-                    $query_info_carrier,
3062
-                    'group_by'
3063
-                );
3064
-            }
3065
-        }
3066
-        if (array_key_exists('having', $query_params)) {
3067
-            $this->_extract_related_models_from_sub_params_array_keys(
3068
-                $query_params[0],
3069
-                $query_info_carrier,
3070
-                'having'
3071
-            );
3072
-        }
3073
-        if (array_key_exists('order_by', $query_params)) {
3074
-            if (is_array($query_params['order_by'])) {
3075
-                $this->_extract_related_models_from_sub_params_array_keys(
3076
-                    $query_params['order_by'],
3077
-                    $query_info_carrier,
3078
-                    'order_by'
3079
-                );
3080
-            } elseif (! empty($query_params['order_by'])) {
3081
-                $this->_extract_related_model_info_from_query_param(
3082
-                    $query_params['order_by'],
3083
-                    $query_info_carrier,
3084
-                    'order_by'
3085
-                );
3086
-            }
3087
-        }
3088
-        if (array_key_exists('force_join', $query_params)) {
3089
-            $this->_extract_related_models_from_sub_params_array_values(
3090
-                $query_params['force_join'],
3091
-                $query_info_carrier,
3092
-                'force_join'
3093
-            );
3094
-        }
3095
-        return $query_info_carrier;
3096
-    }
3097
-
3098
-
3099
-
3100
-    /**
3101
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3102
-     *
3103
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3104
-     *                                                      $query_params['having']
3105
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3106
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3107
-     * @throws EE_Error
3108
-     * @return \EE_Model_Query_Info_Carrier
3109
-     */
3110
-    private function _extract_related_models_from_sub_params_array_keys(
3111
-        $sub_query_params,
3112
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3113
-        $query_param_type
3114
-    ) {
3115
-        if (! empty($sub_query_params)) {
3116
-            $sub_query_params = (array)$sub_query_params;
3117
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3118
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3119
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3120
-                    $query_param_type);
3121
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3122
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3123
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3124
-                //of array('Registration.TXN_ID'=>23)
3125
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3126
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3127
-                    if (! is_array($possibly_array_of_params)) {
3128
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3129
-                            "event_espresso"),
3130
-                            $param, $possibly_array_of_params));
3131
-                    } else {
3132
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3133
-                            $model_query_info_carrier, $query_param_type);
3134
-                    }
3135
-                } elseif ($query_param_type === 0 //ie WHERE
3136
-                          && is_array($possibly_array_of_params)
3137
-                          && isset($possibly_array_of_params[2])
3138
-                          && $possibly_array_of_params[2] == true
3139
-                ) {
3140
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3141
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3142
-                    //from which we should extract query parameters!
3143
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3144
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3145
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3146
-                    }
3147
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3148
-                        $model_query_info_carrier, $query_param_type);
3149
-                }
3150
-            }
3151
-        }
3152
-        return $model_query_info_carrier;
3153
-    }
3154
-
3155
-
3156
-
3157
-    /**
3158
-     * For extracting related models from forced_joins, where the array values contain the info about what
3159
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3160
-     *
3161
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3162
-     *                                                      $query_params['having']
3163
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3164
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3165
-     * @throws EE_Error
3166
-     * @return \EE_Model_Query_Info_Carrier
3167
-     */
3168
-    private function _extract_related_models_from_sub_params_array_values(
3169
-        $sub_query_params,
3170
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3171
-        $query_param_type
3172
-    ) {
3173
-        if (! empty($sub_query_params)) {
3174
-            if (! is_array($sub_query_params)) {
3175
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3176
-                    $sub_query_params));
3177
-            }
3178
-            foreach ($sub_query_params as $param) {
3179
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3180
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3181
-                    $query_param_type);
3182
-            }
3183
-        }
3184
-        return $model_query_info_carrier;
3185
-    }
3186
-
3187
-
3188
-
3189
-    /**
3190
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3191
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3192
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3193
-     * but use them in a different order. Eg, we need to know what models we are querying
3194
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3195
-     * other models before we can finalize the where clause SQL.
3196
-     *
3197
-     * @param array $query_params
3198
-     * @throws EE_Error
3199
-     * @return EE_Model_Query_Info_Carrier
3200
-     */
3201
-    public function _create_model_query_info_carrier($query_params)
3202
-    {
3203
-        if (! is_array($query_params)) {
3204
-            EE_Error::doing_it_wrong(
3205
-                'EEM_Base::_create_model_query_info_carrier',
3206
-                sprintf(
3207
-                    __(
3208
-                        '$query_params should be an array, you passed a variable of type %s',
3209
-                        'event_espresso'
3210
-                    ),
3211
-                    gettype($query_params)
3212
-                ),
3213
-                '4.6.0'
3214
-            );
3215
-            $query_params = array();
3216
-        }
3217
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3218
-        //first check if we should alter the query to account for caps or not
3219
-        //because the caps might require us to do extra joins
3220
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3221
-            $query_params[0] = $where_query_params = array_replace_recursive(
3222
-                $where_query_params,
3223
-                $this->caps_where_conditions(
3224
-                    $query_params['caps']
3225
-                )
3226
-            );
3227
-        }
3228
-        $query_object = $this->_extract_related_models_from_query($query_params);
3229
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3230
-        foreach ($where_query_params as $key => $value) {
3231
-            if (is_int($key)) {
3232
-                throw new EE_Error(
3233
-                    sprintf(
3234
-                        __(
3235
-                            "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.",
3236
-                            "event_espresso"
3237
-                        ),
3238
-                        $key,
3239
-                        var_export($value, true),
3240
-                        var_export($query_params, true),
3241
-                        get_class($this)
3242
-                    )
3243
-                );
3244
-            }
3245
-        }
3246
-        if (
3247
-            array_key_exists('default_where_conditions', $query_params)
3248
-            && ! empty($query_params['default_where_conditions'])
3249
-        ) {
3250
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3251
-        } else {
3252
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3253
-        }
3254
-        $where_query_params = array_merge(
3255
-            $this->_get_default_where_conditions_for_models_in_query(
3256
-                $query_object,
3257
-                $use_default_where_conditions,
3258
-                $where_query_params
3259
-            ),
3260
-            $where_query_params
3261
-        );
3262
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3263
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3264
-        // So we need to setup a subquery and use that for the main join.
3265
-        // Note for now this only works on the primary table for the model.
3266
-        // So for instance, you could set the limit array like this:
3267
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3268
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3269
-            $query_object->set_main_model_join_sql(
3270
-                $this->_construct_limit_join_select(
3271
-                    $query_params['on_join_limit'][0],
3272
-                    $query_params['on_join_limit'][1]
3273
-                )
3274
-            );
3275
-        }
3276
-        //set limit
3277
-        if (array_key_exists('limit', $query_params)) {
3278
-            if (is_array($query_params['limit'])) {
3279
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3280
-                    $e = sprintf(
3281
-                        __(
3282
-                            "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)",
3283
-                            "event_espresso"
3284
-                        ),
3285
-                        http_build_query($query_params['limit'])
3286
-                    );
3287
-                    throw new EE_Error($e . "|" . $e);
3288
-                }
3289
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3290
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3291
-            } elseif (! empty ($query_params['limit'])) {
3292
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3293
-            }
3294
-        }
3295
-        //set order by
3296
-        if (array_key_exists('order_by', $query_params)) {
3297
-            if (is_array($query_params['order_by'])) {
3298
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3299
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3300
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3301
-                if (array_key_exists('order', $query_params)) {
3302
-                    throw new EE_Error(
3303
-                        sprintf(
3304
-                            __(
3305
-                                "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 ",
3306
-                                "event_espresso"
3307
-                            ),
3308
-                            get_class($this),
3309
-                            implode(", ", array_keys($query_params['order_by'])),
3310
-                            implode(", ", $query_params['order_by']),
3311
-                            $query_params['order']
3312
-                        )
3313
-                    );
3314
-                }
3315
-                $this->_extract_related_models_from_sub_params_array_keys(
3316
-                    $query_params['order_by'],
3317
-                    $query_object,
3318
-                    'order_by'
3319
-                );
3320
-                //assume it's an array of fields to order by
3321
-                $order_array = array();
3322
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3323
-                    $order = $this->_extract_order($order);
3324
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3325
-                }
3326
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3327
-            } elseif (! empty ($query_params['order_by'])) {
3328
-                $this->_extract_related_model_info_from_query_param(
3329
-                    $query_params['order_by'],
3330
-                    $query_object,
3331
-                    'order',
3332
-                    $query_params['order_by']
3333
-                );
3334
-                $order = isset($query_params['order'])
3335
-                    ? $this->_extract_order($query_params['order'])
3336
-                    : 'DESC';
3337
-                $query_object->set_order_by_sql(
3338
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3339
-                );
3340
-            }
3341
-        }
3342
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3343
-        if (! array_key_exists('order_by', $query_params)
3344
-            && array_key_exists('order', $query_params)
3345
-            && ! empty($query_params['order'])
3346
-        ) {
3347
-            $pk_field = $this->get_primary_key_field();
3348
-            $order = $this->_extract_order($query_params['order']);
3349
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3350
-        }
3351
-        //set group by
3352
-        if (array_key_exists('group_by', $query_params)) {
3353
-            if (is_array($query_params['group_by'])) {
3354
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3355
-                $group_by_array = array();
3356
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3357
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3358
-                }
3359
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3360
-            } elseif (! empty ($query_params['group_by'])) {
3361
-                $query_object->set_group_by_sql(
3362
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3363
-                );
3364
-            }
3365
-        }
3366
-        //set having
3367
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3368
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3369
-        }
3370
-        //now, just verify they didn't pass anything wack
3371
-        foreach ($query_params as $query_key => $query_value) {
3372
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3373
-                throw new EE_Error(
3374
-                    sprintf(
3375
-                        __(
3376
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3377
-                            'event_espresso'
3378
-                        ),
3379
-                        $query_key,
3380
-                        get_class($this),
3381
-                        //						print_r( $this->_allowed_query_params, TRUE )
3382
-                        implode(',', $this->_allowed_query_params)
3383
-                    )
3384
-                );
3385
-            }
3386
-        }
3387
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3388
-        if (empty($main_model_join_sql)) {
3389
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3390
-        }
3391
-        return $query_object;
3392
-    }
3393
-
3394
-
3395
-
3396
-    /**
3397
-     * Gets the where conditions that should be imposed on the query based on the
3398
-     * context (eg reading frontend, backend, edit or delete).
3399
-     *
3400
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3401
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3402
-     * @throws \EE_Error
3403
-     */
3404
-    public function caps_where_conditions($context = self::caps_read)
3405
-    {
3406
-        EEM_Base::verify_is_valid_cap_context($context);
3407
-        $cap_where_conditions = array();
3408
-        $cap_restrictions = $this->caps_missing($context);
3409
-        /**
3410
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3411
-         */
3412
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3413
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3414
-                $restriction_if_no_cap->get_default_where_conditions());
3415
-        }
3416
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3417
-            $cap_restrictions);
3418
-    }
3419
-
3420
-
3421
-
3422
-    /**
3423
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3424
-     * otherwise throws an exception
3425
-     *
3426
-     * @param string $should_be_order_string
3427
-     * @return string either ASC, asc, DESC or desc
3428
-     * @throws EE_Error
3429
-     */
3430
-    private function _extract_order($should_be_order_string)
3431
-    {
3432
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3433
-            return $should_be_order_string;
3434
-        } else {
3435
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3436
-                "event_espresso"), get_class($this), $should_be_order_string));
3437
-        }
3438
-    }
3439
-
3440
-
3441
-
3442
-    /**
3443
-     * Looks at all the models which are included in this query, and asks each
3444
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3445
-     * so they can be merged
3446
-     *
3447
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3448
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3449
-     *                                                                  'none' means NO default where conditions will
3450
-     *                                                                  be used AT ALL during this query.
3451
-     *                                                                  'other_models_only' means default where
3452
-     *                                                                  conditions from other models will be used, but
3453
-     *                                                                  not for this primary model. 'all', the default,
3454
-     *                                                                  means default where conditions will apply as
3455
-     *                                                                  normal
3456
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3457
-     * @throws EE_Error
3458
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3459
-     */
3460
-    private function _get_default_where_conditions_for_models_in_query(
3461
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3462
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3463
-        $where_query_params = array()
3464
-    ) {
3465
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3466
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3467
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3468
-                "event_espresso"), $use_default_where_conditions,
3469
-                implode(", ", $allowed_used_default_where_conditions_values)));
3470
-        }
3471
-        $universal_query_params = array();
3472
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3473
-            $universal_query_params = $this->_get_default_where_conditions();
3474
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3475
-            $universal_query_params = $this->_get_minimum_where_conditions();
3476
-        }
3477
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3478
-            $related_model = $this->get_related_model_obj($model_name);
3479
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3480
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3481
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3482
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3483
-            } else {
3484
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3485
-                continue;
3486
-            }
3487
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3488
-                $related_model_universal_where_params,
3489
-                $where_query_params,
3490
-                $related_model,
3491
-                $model_relation_path
3492
-            );
3493
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3494
-                $universal_query_params,
3495
-                $overrides
3496
-            );
3497
-        }
3498
-        return $universal_query_params;
3499
-    }
3500
-
3501
-
3502
-
3503
-    /**
3504
-     * Determines whether or not we should use default where conditions for the model in question
3505
-     * (this model, or other related models).
3506
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3507
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3508
-     * We should use default where conditions on related models when they requested to use default where conditions
3509
-     * on all models, or specifically just on other related models
3510
-     * @param      $default_where_conditions_value
3511
-     * @param bool $for_this_model false means this is for OTHER related models
3512
-     * @return bool
3513
-     */
3514
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3515
-    {
3516
-        return (
3517
-                   $for_this_model
3518
-                   && in_array(
3519
-                       $default_where_conditions_value,
3520
-                       array(
3521
-                           EEM_Base::default_where_conditions_all,
3522
-                           EEM_Base::default_where_conditions_this_only,
3523
-                           EEM_Base::default_where_conditions_minimum_others,
3524
-                       ),
3525
-                       true
3526
-                   )
3527
-               )
3528
-               || (
3529
-                   ! $for_this_model
3530
-                   && in_array(
3531
-                       $default_where_conditions_value,
3532
-                       array(
3533
-                           EEM_Base::default_where_conditions_all,
3534
-                           EEM_Base::default_where_conditions_others_only,
3535
-                       ),
3536
-                       true
3537
-                   )
3538
-               );
3539
-    }
3540
-
3541
-    /**
3542
-     * Determines whether or not we should use default minimum conditions for the model in question
3543
-     * (this model, or other related models).
3544
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3545
-     * where conditions.
3546
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3547
-     * on this model or others
3548
-     * @param      $default_where_conditions_value
3549
-     * @param bool $for_this_model false means this is for OTHER related models
3550
-     * @return bool
3551
-     */
3552
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3553
-    {
3554
-        return (
3555
-                   $for_this_model
3556
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3557
-               )
3558
-               || (
3559
-                   ! $for_this_model
3560
-                   && in_array(
3561
-                       $default_where_conditions_value,
3562
-                       array(
3563
-                           EEM_Base::default_where_conditions_minimum_others,
3564
-                           EEM_Base::default_where_conditions_minimum_all,
3565
-                       ),
3566
-                       true
3567
-                   )
3568
-               );
3569
-    }
3570
-
3571
-
3572
-    /**
3573
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3574
-     * then we also add a special where condition which allows for that model's primary key
3575
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3576
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3577
-     *
3578
-     * @param array    $default_where_conditions
3579
-     * @param array    $provided_where_conditions
3580
-     * @param EEM_Base $model
3581
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3582
-     * @return array like EEM_Base::get_all's $query_params[0]
3583
-     * @throws \EE_Error
3584
-     */
3585
-    private function _override_defaults_or_make_null_friendly(
3586
-        $default_where_conditions,
3587
-        $provided_where_conditions,
3588
-        $model,
3589
-        $model_relation_path
3590
-    ) {
3591
-        $null_friendly_where_conditions = array();
3592
-        $none_overridden = true;
3593
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3594
-        foreach ($default_where_conditions as $key => $val) {
3595
-            if (isset($provided_where_conditions[$key])) {
3596
-                $none_overridden = false;
3597
-            } else {
3598
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3599
-            }
3600
-        }
3601
-        if ($none_overridden && $default_where_conditions) {
3602
-            if ($model->has_primary_key_field()) {
3603
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3604
-                                                                                . "."
3605
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3606
-            }/*else{
31
+	//admin posty
32
+	//basic -> grants access to mine -> if they don't have it, select none
33
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
+	//*_published -> grants access to published -> if they dont have it, select non-published
36
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
38
+	//frontend posty
39
+	//by default has access to published
40
+	//basic -> grants access to mine that aren't published, and all published
41
+	//*_others ->grants access to others that aren't private, all mine
42
+	//*_private -> grants full access
43
+	//frontend non-posty
44
+	//like admin posty
45
+	//category-y
46
+	//assign -> grants access to join-table
47
+	//(delete, edit)
48
+	//payment-method-y
49
+	//for each registered payment method,
50
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
+	/**
52
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
55
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
+	 *
57
+	 * @var boolean
58
+	 */
59
+	private $_values_already_prepared_by_model_object = 0;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the data is just like form input that needs to have the model fields'
64
+	 * prepare_for_set and prepare_for_use_in_db called on it
65
+	 */
66
+	const not_prepared_by_model_object = 0;
67
+
68
+	/**
69
+	 * when $_values_already_prepared_by_model_object equals this, we
70
+	 * assume this value is coming from a model object and doesn't need to have
71
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
72
+	 */
73
+	const prepared_by_model_object = 1;
74
+
75
+	/**
76
+	 * when $_values_already_prepared_by_model_object equals this, we assume
77
+	 * the values are already to be used in the database (ie no processing is done
78
+	 * on them by the model's fields)
79
+	 */
80
+	const prepared_for_use_in_db = 2;
81
+
82
+
83
+	protected $singular_item = 'Item';
84
+
85
+	protected $plural_item   = 'Items';
86
+
87
+	/**
88
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
+	 */
90
+	protected $_tables;
91
+
92
+	/**
93
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
+	 *
97
+	 * @var \EE_Model_Field_Base[] $_fields
98
+	 */
99
+	protected $_fields;
100
+
101
+	/**
102
+	 * array of different kinds of relations
103
+	 *
104
+	 * @var \EE_Model_Relation_Base[] $_model_relations
105
+	 */
106
+	protected $_model_relations;
107
+
108
+	/**
109
+	 * @var \EE_Index[] $_indexes
110
+	 */
111
+	protected $_indexes = array();
112
+
113
+	/**
114
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
+	 * by setting the same columns as used in these queries in the query yourself.
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_default_where_conditions_strategy;
121
+
122
+	/**
123
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
+	 * This is particularly useful when you want something between 'none' and 'default'
125
+	 *
126
+	 * @var EE_Default_Where_Conditions
127
+	 */
128
+	protected $_minimum_where_conditions_strategy;
129
+
130
+	/**
131
+	 * String describing how to find the "owner" of this model's objects.
132
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
+	 * But when there isn't, this indicates which related model, or transiently-related model,
134
+	 * has the foreign key to the wp_users table.
135
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
+	 * related to events, and events have a foreign key to wp_users.
137
+	 * On EEM_Transaction, this would be 'Transaction.Event'
138
+	 *
139
+	 * @var string
140
+	 */
141
+	protected $_model_chain_to_wp_user = '';
142
+
143
+	/**
144
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
+	 * don't need it (particularly CPT models)
146
+	 *
147
+	 * @var bool
148
+	 */
149
+	protected $_ignore_where_strategy = false;
150
+
151
+	/**
152
+	 * String used in caps relating to this model. Eg, if the caps relating to this
153
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
+	 *
155
+	 * @var string. If null it hasn't been initialized yet. If false then we
156
+	 * have indicated capabilities don't apply to this
157
+	 */
158
+	protected $_caps_slug = null;
159
+
160
+	/**
161
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
+	 * and next-level keys are capability names, and each's value is a
163
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
165
+	 * and then each capability in the corresponding sub-array that they're missing
166
+	 * adds the where conditions onto the query.
167
+	 *
168
+	 * @var array
169
+	 */
170
+	protected $_cap_restrictions = array(
171
+		self::caps_read       => array(),
172
+		self::caps_read_admin => array(),
173
+		self::caps_edit       => array(),
174
+		self::caps_delete     => array(),
175
+	);
176
+
177
+	/**
178
+	 * Array defining which cap restriction generators to use to create default
179
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
180
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
+	 * automatically set this to false (not just null).
183
+	 *
184
+	 * @var EE_Restriction_Generator_Base[]
185
+	 */
186
+	protected $_cap_restriction_generators = array();
187
+
188
+	/**
189
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
+	 */
191
+	const caps_read       = 'read';
192
+
193
+	const caps_read_admin = 'read_admin';
194
+
195
+	const caps_edit       = 'edit';
196
+
197
+	const caps_delete     = 'delete';
198
+
199
+	/**
200
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
+	 * maps to 'read' because when looking for relevant permissions we're going to use
203
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
204
+	 *
205
+	 * @var array
206
+	 */
207
+	protected $_cap_contexts_to_cap_action_map = array(
208
+		self::caps_read       => 'read',
209
+		self::caps_read_admin => 'read',
210
+		self::caps_edit       => 'edit',
211
+		self::caps_delete     => 'delete',
212
+	);
213
+
214
+	/**
215
+	 * Timezone
216
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
+	 * EE_Datetime_Field data type will have access to it.
220
+	 *
221
+	 * @var string
222
+	 */
223
+	protected $_timezone;
224
+
225
+
226
+	/**
227
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
+	 * multisite.
229
+	 *
230
+	 * @var int
231
+	 */
232
+	protected static $_model_query_blog_id;
233
+
234
+	/**
235
+	 * A copy of _fields, except the array keys are the model names pointed to by
236
+	 * the field
237
+	 *
238
+	 * @var EE_Model_Field_Base[]
239
+	 */
240
+	private $_cache_foreign_key_to_fields = array();
241
+
242
+	/**
243
+	 * Cached list of all the fields on the model, indexed by their name
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cached_fields = null;
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, except those that are
251
+	 * marked as only pertinent to the database
252
+	 *
253
+	 * @var EE_Model_Field_Base[]
254
+	 */
255
+	private $_cached_fields_non_db_only = null;
256
+
257
+	/**
258
+	 * A cached reference to the primary key for quick lookup
259
+	 *
260
+	 * @var EE_Model_Field_Base
261
+	 */
262
+	private $_primary_key_field = null;
263
+
264
+	/**
265
+	 * Flag indicating whether this model has a primary key or not
266
+	 *
267
+	 * @var boolean
268
+	 */
269
+	protected $_has_primary_key_field = null;
270
+
271
+	/**
272
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
273
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
+	 *
275
+	 * @var boolean
276
+	 */
277
+	protected $_wp_core_model = false;
278
+
279
+	/**
280
+	 *    List of valid operators that can be used for querying.
281
+	 * The keys are all operators we'll accept, the values are the real SQL
282
+	 * operators used
283
+	 *
284
+	 * @var array
285
+	 */
286
+	protected $_valid_operators = array(
287
+		'='           => '=',
288
+		'<='          => '<=',
289
+		'<'           => '<',
290
+		'>='          => '>=',
291
+		'>'           => '>',
292
+		'!='          => '!=',
293
+		'LIKE'        => 'LIKE',
294
+		'like'        => 'LIKE',
295
+		'NOT_LIKE'    => 'NOT LIKE',
296
+		'not_like'    => 'NOT LIKE',
297
+		'NOT LIKE'    => 'NOT LIKE',
298
+		'not like'    => 'NOT LIKE',
299
+		'IN'          => 'IN',
300
+		'in'          => 'IN',
301
+		'NOT_IN'      => 'NOT IN',
302
+		'not_in'      => 'NOT IN',
303
+		'NOT IN'      => 'NOT IN',
304
+		'not in'      => 'NOT IN',
305
+		'between'     => 'BETWEEN',
306
+		'BETWEEN'     => 'BETWEEN',
307
+		'IS_NOT_NULL' => 'IS NOT NULL',
308
+		'is_not_null' => 'IS NOT NULL',
309
+		'IS NOT NULL' => 'IS NOT NULL',
310
+		'is not null' => 'IS NOT NULL',
311
+		'IS_NULL'     => 'IS NULL',
312
+		'is_null'     => 'IS NULL',
313
+		'IS NULL'     => 'IS NULL',
314
+		'is null'     => 'IS NULL',
315
+		'REGEXP'      => 'REGEXP',
316
+		'regexp'      => 'REGEXP',
317
+		'NOT_REGEXP'  => 'NOT REGEXP',
318
+		'not_regexp'  => 'NOT REGEXP',
319
+		'NOT REGEXP'  => 'NOT REGEXP',
320
+		'not regexp'  => 'NOT REGEXP',
321
+	);
322
+
323
+	/**
324
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
+	 *
326
+	 * @var array
327
+	 */
328
+	protected $_in_style_operators = array('IN', 'NOT IN');
329
+
330
+	/**
331
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
+	 * '12-31-2012'"
333
+	 *
334
+	 * @var array
335
+	 */
336
+	protected $_between_style_operators = array('BETWEEN');
337
+
338
+	/**
339
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
+	 * on a join table.
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
+
346
+	/**
347
+	 * Allowed values for $query_params['order'] for ordering in queries
348
+	 *
349
+	 * @var array
350
+	 */
351
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
+
353
+	/**
354
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
356
+	 *
357
+	 * @var array
358
+	 */
359
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
+
361
+	/**
362
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
364
+	 *
365
+	 * @var array
366
+	 */
367
+	private $_allowed_query_params = array(
368
+		0,
369
+		'limit',
370
+		'order_by',
371
+		'group_by',
372
+		'having',
373
+		'force_join',
374
+		'order',
375
+		'on_join_limit',
376
+		'default_where_conditions',
377
+		'caps',
378
+	);
379
+
380
+	/**
381
+	 * All the data types that can be used in $wpdb->prepare statements.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
+
387
+	/**
388
+	 *    EE_Registry Object
389
+	 *
390
+	 * @var    object
391
+	 * @access    protected
392
+	 */
393
+	protected $EE = null;
394
+
395
+
396
+	/**
397
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
+	 *
399
+	 * @var int
400
+	 */
401
+	protected $_show_next_x_db_queries = 0;
402
+
403
+	/**
404
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
+	 *
407
+	 * @var array
408
+	 */
409
+	protected $_custom_selections = array();
410
+
411
+	/**
412
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
+	 * caches every model object we've fetched from the DB on this request
414
+	 *
415
+	 * @var array
416
+	 */
417
+	protected $_entity_map;
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws \EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Generates the cap restrictions for the given context, or if they were
654
+	 * already generated just gets what's cached
655
+	 *
656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
657
+	 * @return EE_Default_Where_Conditions[]
658
+	 */
659
+	protected function _generate_cap_restrictions($context)
660
+	{
661
+		if (isset($this->_cap_restriction_generators[$context])
662
+			&& $this->_cap_restriction_generators[$context]
663
+			   instanceof
664
+			   EE_Restriction_Generator_Base
665
+		) {
666
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
+		} else {
668
+			return array();
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Used to set the $_model_query_blog_id static property.
676
+	 *
677
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
+	 *                      value for get_current_blog_id() will be used.
679
+	 */
680
+	public static function set_model_query_blog_id($blog_id = 0)
681
+	{
682
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns whatever is set as the internal $model_query_blog_id.
689
+	 *
690
+	 * @return int
691
+	 */
692
+	public static function get_model_query_blog_id()
693
+	{
694
+		return EEM_Base::$_model_query_blog_id;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *        This function is a singleton method used to instantiate the Espresso_model object
701
+	 *
702
+	 * @access public
703
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
+	 *                         timezone in the 'timezone_string' wp option)
707
+	 * @return static (as in the concrete child class)
708
+	 */
709
+	public static function instance($timezone = null)
710
+	{
711
+		// check if instance of Espresso_model already exists
712
+		if (! static::$_instance instanceof static) {
713
+			// instantiate Espresso_model
714
+			static::$_instance = new static($timezone);
715
+		}
716
+		//we might have a timezone set, let set_timezone decide what to do with it
717
+		static::$_instance->set_timezone($timezone);
718
+		// Espresso_model object
719
+		return static::$_instance;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * resets the model and returns it
726
+	 *
727
+	 * @param null | string $timezone
728
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
+	 * all its properties reset; if it wasn't instantiated, returns null)
730
+	 */
731
+	public static function reset($timezone = null)
732
+	{
733
+		if (static::$_instance instanceof EEM_Base) {
734
+			//let's try to NOT swap out the current instance for a new one
735
+			//because if someone has a reference to it, we can't remove their reference
736
+			//so it's best to keep using the same reference, but change the original object
737
+			//reset all its properties to their original values as defined in the class
738
+			$r = new ReflectionClass(get_class(static::$_instance));
739
+			$static_properties = $r->getStaticProperties();
740
+			foreach ($r->getDefaultProperties() as $property => $value) {
741
+				//don't set instance to null like it was originally,
742
+				//but it's static anyways, and we're ignoring static properties (for now at least)
743
+				if (! isset($static_properties[$property])) {
744
+					static::$_instance->{$property} = $value;
745
+				}
746
+			}
747
+			//and then directly call its constructor again, like we would if we
748
+			//were creating a new one
749
+			static::$_instance->__construct($timezone);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
+	 *
760
+	 * @param  boolean $translated return localized strings or JUST the array.
761
+	 * @return array
762
+	 * @throws \EE_Error
763
+	 */
764
+	public function status_array($translated = false)
765
+	{
766
+		if (! array_key_exists('Status', $this->_model_relations)) {
767
+			return array();
768
+		}
769
+		$model_name = $this->get_this_model_name();
770
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
+		$status_array = array();
773
+		foreach ($stati as $status) {
774
+			$status_array[$status->ID()] = $status->get('STS_code');
775
+		}
776
+		return $translated
777
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
+			: $status_array;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
+	 *
786
+	 * @param array $query_params             {
787
+	 * @var array $0 (where) array {
788
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
+	 *                                        conditions based on related models (and even
792
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
793
+	 *                                        name. Eg,
794
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
+	 *                                        to Venues (even when each of those models actually consisted of two
802
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
803
+	 *                                        just having
804
+	 *                                        "Venue.VNU_ID", you could have
805
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
+	 *                                        events are related to Registrations, which are related to Attendees). You
807
+	 *                                        can take it even further with
808
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
+	 *                                        (from the default of '='), change the value to an numerically-indexed
810
+	 *                                        array, where the first item in the list is the operator. eg: array(
811
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
819
+	 *                                        the value is a field, simply provide a third array item (true) to the
820
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
+	 *                                        Note: you can also use related model field names like you would any other
823
+	 *                                        field name. eg:
824
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
826
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
833
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
+	 *                                        "stick" until you specify an AND. eg
835
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
840
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
+	 *                                        too, eg:
843
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
848
+	 *                                        the OFFSET, the 2nd is the LIMIT
849
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
+	 *                                        following format array('on_join_limit'
852
+	 *                                        => array( 'table_alias', array(1,2) ) ).
853
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
+	 *                                        values are either 'ASC' or 'DESC'.
855
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
+	 *                                        DESC..." respectively. Like the
858
+	 *                                        'where' conditions, these fields can be on related models. Eg
859
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
861
+	 *                                        Attendee, Price, Datetime, etc.)
862
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
864
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
+	 *                                        order by the primary key. Eg,
867
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
869
+	 *                                        DTT_EVT_start) or
870
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
+	 *                                        'group_by'=>'VNU_ID', or
874
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
+	 *                                        if no
876
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
877
+	 *                                        model's primary key (or combined primary keys). This avoids some
878
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
879
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
+	 *                                        results)
883
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
+	 *                                        array where values are models to be joined in the query.Eg
885
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
887
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
888
+	 *                                        related models which belongs to the current model
889
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
890
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
891
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
894
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
896
+	 *                                        this model's default where conditions added to the query, use
897
+	 *                                        'this_model_only'. If you want to use all default where conditions
898
+	 *                                        (default), set to 'all'.
899
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
+	 *                                        everything? Or should we only show the current user items they should be
902
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
+	 *                                        }
905
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
+	 *                                        array( array(
911
+	 *                                        'OR'=>array(
912
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
+	 *                                        )
915
+	 *                                        ),
916
+	 *                                        'limit'=>10,
917
+	 *                                        'group_by'=>'TXN_ID'
918
+	 *                                        ));
919
+	 *                                        get all the answers to the question titled "shirt size" for event with id
920
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
+	 *                                        'Question.QST_display_text'=>'shirt size',
922
+	 *                                        'Registration.Event.EVT_ID'=>12
923
+	 *                                        ),
924
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
925
+	 *                                        ));
926
+	 * @throws \EE_Error
927
+	 */
928
+	public function get_all($query_params = array())
929
+	{
930
+		if (isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Modifies the query parameters so we only get back model objects
942
+	 * that "belong" to the current user
943
+	 *
944
+	 * @param array $query_params @see EEM_Base::get_all()
945
+	 * @return array like EEM_Base::get_all
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = array())
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 */
966
+	public function wp_user_field_name()
967
+	{
968
+		try {
969
+			if (! empty($this->_model_chain_to_wp_user)) {
970
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
+				$last_model_name = end($models_to_follow_to_wp_users);
972
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+			} else {
975
+				$model_with_fk_to_wp_users = $this;
976
+				$model_chain_to_wp_user = '';
977
+			}
978
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+		} catch (EE_Error $e) {
981
+			return false;
982
+		}
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		} else {
1017
+			try {
1018
+				$this->get_foreign_key_to('WP_User');
1019
+				return true;
1020
+			} catch (EE_Error $e) {
1021
+				return false;
1022
+			}
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws \EE_Error
1045
+	 */
1046
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		// remember the custom selections, if any, and type cast as array
1049
+		// (unless $columns_to_select is an object, then just set as an empty array)
1050
+		// Note: (array) 'some string' === array( 'some string' )
1051
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions = $columns_to_select !== null
1054
+			? $this->_construct_select_from_input($columns_to_select)
1055
+			: $this->_construct_default_select_sql($model_query_info);
1056
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1064
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
+	 * take care of joins, field preparation etc.
1066
+	 *
1067
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1071
+	 *                                  override this and set the select to "*", or a specific column name, like
1072
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
+	 *                                  the aliases used to refer to this selection, and values are to be
1075
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
+	 * @throws \EE_Error
1079
+	 */
1080
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
+	{
1082
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * For creating a custom select statement
1089
+	 *
1090
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
+	 *                                 SQL, and 1=>is the datatype
1093
+	 * @throws EE_Error
1094
+	 * @return string
1095
+	 */
1096
+	private function _construct_select_from_input($columns_to_select)
1097
+	{
1098
+		if (is_array($columns_to_select)) {
1099
+			$select_sql_array = array();
1100
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+					throw new EE_Error(
1103
+						sprintf(
1104
+							__(
1105
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
+								"event_espresso"
1107
+							),
1108
+							$selection_and_datatype,
1109
+							$alias
1110
+						)
1111
+					);
1112
+				}
1113
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+					throw new EE_Error(
1115
+						sprintf(
1116
+							__(
1117
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
+								"event_espresso"
1119
+							),
1120
+							$selection_and_datatype[1],
1121
+							$selection_and_datatype[0],
1122
+							$alias,
1123
+							implode(",", $this->_valid_wpdb_data_types)
1124
+						)
1125
+					);
1126
+				}
1127
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
+			}
1129
+			$columns_to_select_string = implode(", ", $select_sql_array);
1130
+		} else {
1131
+			$columns_to_select_string = $columns_to_select;
1132
+		}
1133
+		return $columns_to_select_string;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
+	 *
1141
+	 * @return string
1142
+	 * @throws \EE_Error
1143
+	 */
1144
+	public function primary_key_name()
1145
+	{
1146
+		return $this->get_primary_key_field()->get_name();
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
+	 * If there is no primary key on this model, $id is treated as primary key string
1154
+	 *
1155
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1156
+	 * @return EE_Base_Class
1157
+	 */
1158
+	public function get_one_by_ID($id)
1159
+	{
1160
+		if ($this->get_from_entity_map($id)) {
1161
+			return $this->get_from_entity_map($id);
1162
+		}
1163
+		return $this->get_one(
1164
+			$this->alter_query_params_to_restrict_by_ID(
1165
+				$id,
1166
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
+			)
1168
+		);
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Alters query parameters to only get items with this ID are returned.
1175
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
+	 * or could just be a simple primary key ID
1177
+	 *
1178
+	 * @param int   $id
1179
+	 * @param array $query_params
1180
+	 * @return array of normal query params, @see EEM_Base::get_all
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
+	{
1185
+		if (! isset($query_params[0])) {
1186
+			$query_params[0] = array();
1187
+		}
1188
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1189
+		if ($conditions_from_id === null) {
1190
+			$query_params[0][$this->primary_key_name()] = $id;
1191
+		} else {
1192
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1193
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
+		}
1195
+		return $query_params;
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
+	 * array. If no item is found, null is returned.
1203
+	 *
1204
+	 * @param array $query_params like EEM_Base's $query_params variable.
1205
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
+	 * @throws \EE_Error
1207
+	 */
1208
+	public function get_one($query_params = array())
1209
+	{
1210
+		if (! is_array($query_params)) {
1211
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
+					gettype($query_params)), '4.6.0');
1214
+			$query_params = array();
1215
+		}
1216
+		$query_params['limit'] = 1;
1217
+		$items = $this->get_all($query_params);
1218
+		if (empty($items)) {
1219
+			return null;
1220
+		} else {
1221
+			return array_shift($items);
1222
+		}
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Returns the next x number of items in sequence from the given value as
1229
+	 * found in the database matching the given query conditions.
1230
+	 *
1231
+	 * @param mixed $current_field_value    Value used for the reference point.
1232
+	 * @param null  $field_to_order_by      What field is used for the
1233
+	 *                                      reference point.
1234
+	 * @param int   $limit                  How many to return.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an array of
1237
+	 *                                      EE_Base_Class objects is returned,
1238
+	 *                                      otherwise you can indicate just the
1239
+	 *                                      columns you want returned.
1240
+	 * @return EE_Base_Class[]|array
1241
+	 * @throws \EE_Error
1242
+	 */
1243
+	public function next_x(
1244
+		$current_field_value,
1245
+		$field_to_order_by = null,
1246
+		$limit = 1,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
+			$columns_to_select);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the previous x number of items in sequence from the given value
1258
+	 * as found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws \EE_Error
1271
+	 */
1272
+	public function previous_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
+			$columns_to_select);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * Returns the next item in sequence from the given value as found in the
1287
+	 * database matching the given query conditions.
1288
+	 *
1289
+	 * @param mixed $current_field_value    Value used for the reference point.
1290
+	 * @param null  $field_to_order_by      What field is used for the
1291
+	 *                                      reference point.
1292
+	 * @param array $query_params           Extra conditions on the query.
1293
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
+	 *                                      object is returned, otherwise you
1295
+	 *                                      can indicate just the columns you
1296
+	 *                                      want and a single array indexed by
1297
+	 *                                      the columns will be returned.
1298
+	 * @return EE_Base_Class|null|array()
1299
+	 * @throws \EE_Error
1300
+	 */
1301
+	public function next(
1302
+		$current_field_value,
1303
+		$field_to_order_by = null,
1304
+		$query_params = array(),
1305
+		$columns_to_select = null
1306
+	) {
1307
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
+			$columns_to_select);
1309
+		return empty($results) ? null : reset($results);
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 * Returns the previous item in sequence from the given value as found in
1316
+	 * the database matching the given query conditions.
1317
+	 *
1318
+	 * @param mixed $current_field_value    Value used for the reference point.
1319
+	 * @param null  $field_to_order_by      What field is used for the
1320
+	 *                                      reference point.
1321
+	 * @param array $query_params           Extra conditions on the query.
1322
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
+	 *                                      object is returned, otherwise you
1324
+	 *                                      can indicate just the columns you
1325
+	 *                                      want and a single array indexed by
1326
+	 *                                      the columns will be returned.
1327
+	 * @return EE_Base_Class|null|array()
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function previous(
1331
+		$current_field_value,
1332
+		$field_to_order_by = null,
1333
+		$query_params = array(),
1334
+		$columns_to_select = null
1335
+	) {
1336
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
+			$columns_to_select);
1338
+		return empty($results) ? null : reset($results);
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the a consecutive number of items in sequence from the given
1345
+	 * value as found in the database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed  $current_field_value   Value used for the reference point.
1348
+	 * @param string $operand               What operand is used for the sequence.
1349
+	 * @param string $field_to_order_by     What field is used for the reference point.
1350
+	 * @param int    $limit                 How many to return.
1351
+	 * @param array  $query_params          Extra conditions on the query.
1352
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
+	 *                                      otherwise you can indicate just the columns you want returned.
1354
+	 * @return EE_Base_Class[]|array
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	protected function _get_consecutive(
1358
+		$current_field_value,
1359
+		$operand = '>',
1360
+		$field_to_order_by = null,
1361
+		$limit = 1,
1362
+		$query_params = array(),
1363
+		$columns_to_select = null
1364
+	) {
1365
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
+		if (empty($field_to_order_by)) {
1367
+			if ($this->has_primary_key_field()) {
1368
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1369
+			} else {
1370
+				if (WP_DEBUG) {
1371
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1372
+						'event_espresso'));
1373
+				}
1374
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
+				return array();
1376
+			}
1377
+		}
1378
+		if (! is_array($query_params)) {
1379
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
+					gettype($query_params)), '4.6.0');
1382
+			$query_params = array();
1383
+		}
1384
+		//let's add the where query param for consecutive look up.
1385
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
+		$query_params['limit'] = $limit;
1387
+		//set direction
1388
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+		$query_params['order_by'] = $operand === '>'
1390
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
+		if (empty($columns_to_select)) {
1394
+			return $this->get_all($query_params);
1395
+		} else {
1396
+			//getting just the fields
1397
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
+		}
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		//note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		//and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		//if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		//if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1469
+				'event_espresso'), $field_name));
1470
+		}
1471
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
+		//the field.
1473
+		$this->_timezone = $field_settings->get_timezone();
1474
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
+	}
1476
+
1477
+
1478
+
1479
+	/**
1480
+	 * This returns the current time in a format setup for a query on this model.
1481
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
+	 * it will return:
1483
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
+	 *  NOW
1485
+	 *  - or a unix timestamp (equivalent to time())
1486
+	 *
1487
+	 * @since 4.6.x
1488
+	 * @param string $field_name       The field the current time is needed for.
1489
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1490
+	 *                                 formatted string matching the set format for the field in the set timezone will
1491
+	 *                                 be returned.
1492
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1493
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1494
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
+	 *                                 exception is triggered.
1496
+	 */
1497
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1498
+	{
1499
+		$formats = $this->get_formats_for($field_name);
1500
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1501
+		if ($timestamp) {
1502
+			return $DateTime->format('U');
1503
+		}
1504
+		//not returning timestamp, so return formatted string in timezone.
1505
+		switch ($what) {
1506
+			case 'time' :
1507
+				return $DateTime->format($formats[1]);
1508
+				break;
1509
+			case 'date' :
1510
+				return $DateTime->format($formats[0]);
1511
+				break;
1512
+			default :
1513
+				return $DateTime->format(implode(' ', $formats));
1514
+				break;
1515
+		}
1516
+	}
1517
+
1518
+
1519
+
1520
+	/**
1521
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1522
+	 * for the model are.  Returns a DateTime object.
1523
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1524
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1525
+	 * ignored.
1526
+	 *
1527
+	 * @param string $field_name      The field being setup.
1528
+	 * @param string $timestring      The date time string being used.
1529
+	 * @param string $incoming_format The format for the time string.
1530
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1531
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1532
+	 *                                format is
1533
+	 *                                'U', this is ignored.
1534
+	 * @return DateTime
1535
+	 * @throws \EE_Error
1536
+	 */
1537
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1538
+	{
1539
+		//just using this to ensure the timezone is set correctly internally
1540
+		$this->get_formats_for($field_name);
1541
+		//load EEH_DTT_Helper
1542
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1543
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1544
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1545
+	}
1546
+
1547
+
1548
+
1549
+	/**
1550
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1551
+	 *
1552
+	 * @return EE_Table_Base[]
1553
+	 */
1554
+	public function get_tables()
1555
+	{
1556
+		return $this->_tables;
1557
+	}
1558
+
1559
+
1560
+
1561
+	/**
1562
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1563
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1564
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1565
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1566
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1567
+	 * model object with EVT_ID = 1
1568
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1569
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1570
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1571
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1572
+	 * are not specified)
1573
+	 *
1574
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1575
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1576
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1577
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1578
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1579
+	 *                                         ID=34, we'd use this method as follows:
1580
+	 *                                         EEM_Transaction::instance()->update(
1581
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1582
+	 *                                         array(array('TXN_ID'=>34)));
1583
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1584
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1585
+	 *                                         consider updating Question's QST_admin_label field is of type
1586
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1587
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1588
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1589
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1590
+	 *                                         TRUE, it is assumed that you've already called
1591
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1592
+	 *                                         malicious javascript. However, if
1593
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1594
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1595
+	 *                                         and every other field, before insertion. We provide this parameter
1596
+	 *                                         because model objects perform their prepare_for_set function on all
1597
+	 *                                         their values, and so don't need to be called again (and in many cases,
1598
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1599
+	 *                                         prepare_for_set method...)
1600
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1601
+	 *                                         in this model's entity map according to $fields_n_values that match
1602
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1603
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1604
+	 *                                         could get out-of-sync with the database
1605
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1606
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1607
+	 *                                         bad)
1608
+	 * @throws \EE_Error
1609
+	 */
1610
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1611
+	{
1612
+		if (! is_array($query_params)) {
1613
+			EE_Error::doing_it_wrong('EEM_Base::update',
1614
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1615
+					gettype($query_params)), '4.6.0');
1616
+			$query_params = array();
1617
+		}
1618
+		/**
1619
+		 * Action called before a model update call has been made.
1620
+		 *
1621
+		 * @param EEM_Base $model
1622
+		 * @param array    $fields_n_values the updated fields and their new values
1623
+		 * @param array    $query_params    @see EEM_Base::get_all()
1624
+		 */
1625
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1626
+		/**
1627
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1628
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1629
+		 *
1630
+		 * @param array    $fields_n_values fields and their new values
1631
+		 * @param EEM_Base $model           the model being queried
1632
+		 * @param array    $query_params    see EEM_Base::get_all()
1633
+		 */
1634
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
+			$query_params);
1636
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1637
+		//to do that, for each table, verify that it's PK isn't null.
1638
+		$tables = $this->get_tables();
1639
+		//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
1640
+		//NOTE: we should make this code more efficient by NOT querying twice
1641
+		//before the real update, but that needs to first go through ALPHA testing
1642
+		//as it's dangerous. says Mike August 8 2014
1643
+		//we want to make sure the default_where strategy is ignored
1644
+		$this->_ignore_where_strategy = true;
1645
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1646
+		foreach ($wpdb_select_results as $wpdb_result) {
1647
+			// type cast stdClass as array
1648
+			$wpdb_result = (array)$wpdb_result;
1649
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1650
+			if ($this->has_primary_key_field()) {
1651
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1652
+			} else {
1653
+				//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)
1654
+				$main_table_pk_value = null;
1655
+			}
1656
+			//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
1657
+			//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
1658
+			if (count($tables) > 1) {
1659
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1660
+				//in that table, and so we'll want to insert one
1661
+				foreach ($tables as $table_obj) {
1662
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1663
+					//if there is no private key for this table on the results, it means there's no entry
1664
+					//in this table, right? so insert a row in the current table, using any fields available
1665
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
+						   && $wpdb_result[$this_table_pk_column])
1667
+					) {
1668
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1669
+							$main_table_pk_value);
1670
+						//if we died here, report the error
1671
+						if (! $success) {
1672
+							return false;
1673
+						}
1674
+					}
1675
+				}
1676
+			}
1677
+			//				//and now check that if we have cached any models by that ID on the model, that
1678
+			//				//they also get updated properly
1679
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1680
+			//				if( $model_object ){
1681
+			//					foreach( $fields_n_values as $field => $value ){
1682
+			//						$model_object->set($field, $value);
1683
+			//let's make sure default_where strategy is followed now
1684
+			$this->_ignore_where_strategy = false;
1685
+		}
1686
+		//if we want to keep model objects in sync, AND
1687
+		//if this wasn't called from a model object (to update itself)
1688
+		//then we want to make sure we keep all the existing
1689
+		//model objects in sync with the db
1690
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1691
+			if ($this->has_primary_key_field()) {
1692
+				$model_objs_affected_ids = $this->get_col($query_params);
1693
+			} else {
1694
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1695
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1696
+				$model_objs_affected_ids = array();
1697
+				foreach ($models_affected_key_columns as $row) {
1698
+					$combined_index_key = $this->get_index_primary_key_string($row);
1699
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1700
+				}
1701
+			}
1702
+			if (! $model_objs_affected_ids) {
1703
+				//wait wait wait- if nothing was affected let's stop here
1704
+				return 0;
1705
+			}
1706
+			foreach ($model_objs_affected_ids as $id) {
1707
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1708
+				if ($model_obj_in_entity_map) {
1709
+					foreach ($fields_n_values as $field => $new_value) {
1710
+						$model_obj_in_entity_map->set($field, $new_value);
1711
+					}
1712
+				}
1713
+			}
1714
+			//if there is a primary key on this model, we can now do a slight optimization
1715
+			if ($this->has_primary_key_field()) {
1716
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1717
+				$query_params = array(
1718
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1719
+					'limit'                    => count($model_objs_affected_ids),
1720
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1721
+				);
1722
+			}
1723
+		}
1724
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1725
+		$SQL = "UPDATE "
1726
+			   . $model_query_info->get_full_join_sql()
1727
+			   . " SET "
1728
+			   . $this->_construct_update_sql($fields_n_values)
1729
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1730
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1731
+		/**
1732
+		 * Action called after a model update call has been made.
1733
+		 *
1734
+		 * @param EEM_Base $model
1735
+		 * @param array    $fields_n_values the updated fields and their new values
1736
+		 * @param array    $query_params    @see EEM_Base::get_all()
1737
+		 * @param int      $rows_affected
1738
+		 */
1739
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1740
+		return $rows_affected;//how many supposedly got updated
1741
+	}
1742
+
1743
+
1744
+
1745
+	/**
1746
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1747
+	 * are teh values of the field specified (or by default the primary key field)
1748
+	 * that matched the query params. Note that you should pass the name of the
1749
+	 * model FIELD, not the database table's column name.
1750
+	 *
1751
+	 * @param array  $query_params @see EEM_Base::get_all()
1752
+	 * @param string $field_to_select
1753
+	 * @return array just like $wpdb->get_col()
1754
+	 * @throws \EE_Error
1755
+	 */
1756
+	public function get_col($query_params = array(), $field_to_select = null)
1757
+	{
1758
+		if ($field_to_select) {
1759
+			$field = $this->field_settings_for($field_to_select);
1760
+		} elseif ($this->has_primary_key_field()) {
1761
+			$field = $this->get_primary_key_field();
1762
+		} else {
1763
+			//no primary key, just grab the first column
1764
+			$field = reset($this->field_settings());
1765
+		}
1766
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1767
+		$select_expressions = $field->get_qualified_column();
1768
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
+		return $this->_do_wpdb_query('get_col', array($SQL));
1770
+	}
1771
+
1772
+
1773
+
1774
+	/**
1775
+	 * Returns a single column value for a single row from the database
1776
+	 *
1777
+	 * @param array  $query_params    @see EEM_Base::get_all()
1778
+	 * @param string $field_to_select @see EEM_Base::get_col()
1779
+	 * @return string
1780
+	 * @throws \EE_Error
1781
+	 */
1782
+	public function get_var($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		$query_params['limit'] = 1;
1785
+		$col = $this->get_col($query_params, $field_to_select);
1786
+		if (! empty($col)) {
1787
+			return reset($col);
1788
+		} else {
1789
+			return null;
1790
+		}
1791
+	}
1792
+
1793
+
1794
+
1795
+	/**
1796
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1797
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1798
+	 * injection, but currently no further filtering is done
1799
+	 *
1800
+	 * @global      $wpdb
1801
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1802
+	 *                               be updated to in the DB
1803
+	 * @return string of SQL
1804
+	 * @throws \EE_Error
1805
+	 */
1806
+	public function _construct_update_sql($fields_n_values)
1807
+	{
1808
+		/** @type WPDB $wpdb */
1809
+		global $wpdb;
1810
+		$cols_n_values = array();
1811
+		foreach ($fields_n_values as $field_name => $value) {
1812
+			$field_obj = $this->field_settings_for($field_name);
1813
+			//if the value is NULL, we want to assign the value to that.
1814
+			//wpdb->prepare doesn't really handle that properly
1815
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1816
+			$value_sql = $prepared_value === null ? 'NULL'
1817
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1818
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
+		}
1820
+		return implode(",", $cols_n_values);
1821
+	}
1822
+
1823
+
1824
+
1825
+	/**
1826
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1827
+	 * Performs a HARD delete, meaning the database row should always be removed,
1828
+	 * not just have a flag field on it switched
1829
+	 * Wrapper for EEM_Base::delete_permanently()
1830
+	 *
1831
+	 * @param mixed $id
1832
+	 * @return boolean whether the row got deleted or not
1833
+	 * @throws \EE_Error
1834
+	 */
1835
+	public function delete_permanently_by_ID($id)
1836
+	{
1837
+		return $this->delete_permanently(
1838
+			array(
1839
+				array($this->get_primary_key_field()->get_name() => $id),
1840
+				'limit' => 1,
1841
+			)
1842
+		);
1843
+	}
1844
+
1845
+
1846
+
1847
+	/**
1848
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
+	 * Wrapper for EEM_Base::delete()
1850
+	 *
1851
+	 * @param mixed $id
1852
+	 * @return boolean whether the row got deleted or not
1853
+	 * @throws \EE_Error
1854
+	 */
1855
+	public function delete_by_ID($id)
1856
+	{
1857
+		return $this->delete(
1858
+			array(
1859
+				array($this->get_primary_key_field()->get_name() => $id),
1860
+				'limit' => 1,
1861
+			)
1862
+		);
1863
+	}
1864
+
1865
+
1866
+
1867
+	/**
1868
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1869
+	 * meaning if the model has a field that indicates its been "trashed" or
1870
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1871
+	 *
1872
+	 * @see EEM_Base::delete_permanently
1873
+	 * @param array   $query_params
1874
+	 * @param boolean $allow_blocking
1875
+	 * @return int how many rows got deleted
1876
+	 * @throws \EE_Error
1877
+	 */
1878
+	public function delete($query_params, $allow_blocking = true)
1879
+	{
1880
+		return $this->delete_permanently($query_params, $allow_blocking);
1881
+	}
1882
+
1883
+
1884
+
1885
+	/**
1886
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1887
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1888
+	 * as archived, not actually deleted
1889
+	 *
1890
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1891
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1892
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1893
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1894
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1895
+	 *                                DB
1896
+	 * @return int how many rows got deleted
1897
+	 * @throws \EE_Error
1898
+	 */
1899
+	public function delete_permanently($query_params, $allow_blocking = true)
1900
+	{
1901
+		/**
1902
+		 * Action called just before performing a real deletion query. You can use the
1903
+		 * model and its $query_params to find exactly which items will be deleted
1904
+		 *
1905
+		 * @param EEM_Base $model
1906
+		 * @param array    $query_params   @see EEM_Base::get_all()
1907
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1908
+		 *                                 to block (prevent) this deletion
1909
+		 */
1910
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1911
+		//some MySQL databases may be running safe mode, which may restrict
1912
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1913
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1914
+		//to delete them
1915
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1916
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1917
+		if ($deletion_where) {
1918
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1919
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1920
+			$table_aliases = array_keys($this->_tables);
1921
+			$SQL = "DELETE "
1922
+				   . implode(", ", $table_aliases)
1923
+				   . " FROM "
1924
+				   . $model_query_info->get_full_join_sql()
1925
+				   . " WHERE "
1926
+				   . $deletion_where;
1927
+			//		/echo "delete sql:$SQL";
1928
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1929
+		} else {
1930
+			$rows_deleted = 0;
1931
+		}
1932
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1933
+		if ($this->has_primary_key_field()) {
1934
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1935
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1936
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1937
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1938
+				}
1939
+			}
1940
+		}
1941
+		/**
1942
+		 * Action called just after performing a real deletion query. Although at this point the
1943
+		 * items should have been deleted
1944
+		 *
1945
+		 * @param EEM_Base $model
1946
+		 * @param array    $query_params @see EEM_Base::get_all()
1947
+		 * @param int      $rows_deleted
1948
+		 */
1949
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1950
+		return $rows_deleted;//how many supposedly got deleted
1951
+	}
1952
+
1953
+
1954
+
1955
+	/**
1956
+	 * Checks all the relations that throw error messages when there are blocking related objects
1957
+	 * for related model objects. If there are any related model objects on those relations,
1958
+	 * adds an EE_Error, and return true
1959
+	 *
1960
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1961
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1962
+	 *                                                 should be ignored when determining whether there are related
1963
+	 *                                                 model objects which block this model object's deletion. Useful
1964
+	 *                                                 if you know A is related to B and are considering deleting A,
1965
+	 *                                                 but want to see if A has any other objects blocking its deletion
1966
+	 *                                                 before removing the relation between A and B
1967
+	 * @return boolean
1968
+	 * @throws \EE_Error
1969
+	 */
1970
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1971
+	{
1972
+		//first, if $ignore_this_model_obj was supplied, get its model
1973
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1974
+			$ignored_model = $ignore_this_model_obj->get_model();
1975
+		} else {
1976
+			$ignored_model = null;
1977
+		}
1978
+		//now check all the relations of $this_model_obj_or_id and see if there
1979
+		//are any related model objects blocking it?
1980
+		$is_blocked = false;
1981
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1982
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1983
+				//if $ignore_this_model_obj was supplied, then for the query
1984
+				//on that model needs to be told to ignore $ignore_this_model_obj
1985
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1986
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1987
+						array(
1988
+							$ignored_model->get_primary_key_field()->get_name() => array(
1989
+								'!=',
1990
+								$ignore_this_model_obj->ID(),
1991
+							),
1992
+						),
1993
+					));
1994
+				} else {
1995
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1996
+				}
1997
+				if ($related_model_objects) {
1998
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1999
+					$is_blocked = true;
2000
+				}
2001
+			}
2002
+		}
2003
+		return $is_blocked;
2004
+	}
2005
+
2006
+
2007
+
2008
+	/**
2009
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2010
+	 * well.
2011
+	 *
2012
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2013
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2014
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2015
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2016
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2017
+	 *                                      easily corrupt your DB
2018
+	 * @throws EE_Error
2019
+	 * @return string    everything that comes after the WHERE statement.
2020
+	 */
2021
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2022
+	{
2023
+		if ($this->has_primary_key_field()) {
2024
+			$primary_table = $this->_get_main_table();
2025
+			$other_tables = $this->_get_other_tables();
2026
+			$deletes = $query = array();
2027
+			foreach ($objects_for_deletion as $delete_object) {
2028
+				//before we mark this object for deletion,
2029
+				//make sure there's no related objects blocking its deletion (if we're checking)
2030
+				if (
2031
+					$allow_blocking
2032
+					&& $this->delete_is_blocked_by_related_models(
2033
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2034
+					)
2035
+				) {
2036
+					continue;
2037
+				}
2038
+				//primary table deletes
2039
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2040
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2041
+				}
2042
+				//other tables
2043
+				if (! empty($other_tables)) {
2044
+					foreach ($other_tables as $ot) {
2045
+						//first check if we've got the foreign key column here.
2046
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2047
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2048
+						}
2049
+						// wait! it's entirely possible that we'll have a the primary key
2050
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2051
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2052
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2053
+						}
2054
+						// finally, it is possible that the fk for this table is found
2055
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2056
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2057
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2058
+						}
2059
+					}
2060
+				}
2061
+			}
2062
+			//we should have deletes now, so let's just go through and setup the where statement
2063
+			foreach ($deletes as $column => $values) {
2064
+				//make sure we have unique $values;
2065
+				$values = array_unique($values);
2066
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
+			}
2068
+			return ! empty($query) ? implode(' AND ', $query) : '';
2069
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2070
+			$ways_to_identify_a_row = array();
2071
+			$fields = $this->get_combined_primary_key_fields();
2072
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2073
+			foreach ($objects_for_deletion as $delete_object) {
2074
+				$values_for_each_cpk_for_a_row = array();
2075
+				foreach ($fields as $cpk_field) {
2076
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2077
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2078
+														   . "="
2079
+														   . $delete_object[$cpk_field->get_qualified_column()];
2080
+					}
2081
+				}
2082
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
+			}
2084
+			return implode(" OR ", $ways_to_identify_a_row);
2085
+		} else {
2086
+			//so there's no primary key and no combined key...
2087
+			//sorry, can't help you
2088
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2089
+				"event_espresso"), get_class($this)));
2090
+		}
2091
+	}
2092
+
2093
+
2094
+
2095
+	/**
2096
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2097
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2098
+	 * column
2099
+	 *
2100
+	 * @param array  $query_params   like EEM_Base::get_all's
2101
+	 * @param string $field_to_count field on model to count by (not column name)
2102
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2103
+	 *                               that by the setting $distinct to TRUE;
2104
+	 * @return int
2105
+	 * @throws \EE_Error
2106
+	 */
2107
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2108
+	{
2109
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2110
+		if ($field_to_count) {
2111
+			$field_obj = $this->field_settings_for($field_to_count);
2112
+			$column_to_count = $field_obj->get_qualified_column();
2113
+		} elseif ($this->has_primary_key_field()) {
2114
+			$pk_field_obj = $this->get_primary_key_field();
2115
+			$column_to_count = $pk_field_obj->get_qualified_column();
2116
+		} else {
2117
+			//there's no primary key
2118
+			//if we're counting distinct items, and there's no primary key,
2119
+			//we need to list out the columns for distinction;
2120
+			//otherwise we can just use star
2121
+			if ($distinct) {
2122
+				$columns_to_use = array();
2123
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2124
+					$columns_to_use[] = $field_obj->get_qualified_column();
2125
+				}
2126
+				$column_to_count = implode(',', $columns_to_use);
2127
+			} else {
2128
+				$column_to_count = '*';
2129
+			}
2130
+		}
2131
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2132
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2133
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2134
+	}
2135
+
2136
+
2137
+
2138
+	/**
2139
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2140
+	 *
2141
+	 * @param array  $query_params like EEM_Base::get_all
2142
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2143
+	 * @return float
2144
+	 * @throws \EE_Error
2145
+	 */
2146
+	public function sum($query_params, $field_to_sum = null)
2147
+	{
2148
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2149
+		if ($field_to_sum) {
2150
+			$field_obj = $this->field_settings_for($field_to_sum);
2151
+		} else {
2152
+			$field_obj = $this->get_primary_key_field();
2153
+		}
2154
+		$column_to_count = $field_obj->get_qualified_column();
2155
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2157
+		$data_type = $field_obj->get_wpdb_data_type();
2158
+		if ($data_type === '%d' || $data_type === '%s') {
2159
+			return (float)$return_value;
2160
+		} else {//must be %f
2161
+			return (float)$return_value;
2162
+		}
2163
+	}
2164
+
2165
+
2166
+
2167
+	/**
2168
+	 * Just calls the specified method on $wpdb with the given arguments
2169
+	 * Consolidates a little extra error handling code
2170
+	 *
2171
+	 * @param string $wpdb_method
2172
+	 * @param array  $arguments_to_provide
2173
+	 * @throws EE_Error
2174
+	 * @global wpdb  $wpdb
2175
+	 * @return mixed
2176
+	 */
2177
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2178
+	{
2179
+		//if we're in maintenance mode level 2, DON'T run any queries
2180
+		//because level 2 indicates the database needs updating and
2181
+		//is probably out of sync with the code
2182
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2184
+				"event_espresso")));
2185
+		}
2186
+		/** @type WPDB $wpdb */
2187
+		global $wpdb;
2188
+		if (! method_exists($wpdb, $wpdb_method)) {
2189
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2190
+				'event_espresso'), $wpdb_method));
2191
+		}
2192
+		if (WP_DEBUG) {
2193
+			$old_show_errors_value = $wpdb->show_errors;
2194
+			$wpdb->show_errors(false);
2195
+		}
2196
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2197
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2198
+		if (WP_DEBUG) {
2199
+			$wpdb->show_errors($old_show_errors_value);
2200
+			if (! empty($wpdb->last_error)) {
2201
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2202
+			} elseif ($result === false) {
2203
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2204
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2205
+			}
2206
+		} elseif ($result === false) {
2207
+			EE_Error::add_error(
2208
+				sprintf(
2209
+					__('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"',
2210
+						'event_espresso'),
2211
+					$wpdb_method,
2212
+					var_export($arguments_to_provide, true),
2213
+					$wpdb->last_error
2214
+				),
2215
+				__FILE__,
2216
+				__FUNCTION__,
2217
+				__LINE__
2218
+			);
2219
+		}
2220
+		return $result;
2221
+	}
2222
+
2223
+
2224
+
2225
+	/**
2226
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2227
+	 * and if there's an error tries to verify the DB is correct. Uses
2228
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2229
+	 * we should try to fix the EE core db, the addons, or just give up
2230
+	 *
2231
+	 * @param string $wpdb_method
2232
+	 * @param array  $arguments_to_provide
2233
+	 * @return mixed
2234
+	 */
2235
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2236
+	{
2237
+		/** @type WPDB $wpdb */
2238
+		global $wpdb;
2239
+		$wpdb->last_error = null;
2240
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2241
+		// was there an error running the query? but we don't care on new activations
2242
+		// (we're going to setup the DB anyway on new activations)
2243
+		if (($result === false || ! empty($wpdb->last_error))
2244
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2245
+		) {
2246
+			switch (EEM_Base::$_db_verification_level) {
2247
+				case EEM_Base::db_verified_none :
2248
+					// let's double-check core's DB
2249
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2250
+					break;
2251
+				case EEM_Base::db_verified_core :
2252
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2253
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2254
+					break;
2255
+				case EEM_Base::db_verified_addons :
2256
+					// ummmm... you in trouble
2257
+					return $result;
2258
+					break;
2259
+			}
2260
+			if (! empty($error_message)) {
2261
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2262
+				trigger_error($error_message);
2263
+			}
2264
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2265
+		}
2266
+		return $result;
2267
+	}
2268
+
2269
+
2270
+
2271
+	/**
2272
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2273
+	 * EEM_Base::$_db_verification_level
2274
+	 *
2275
+	 * @param string $wpdb_method
2276
+	 * @param array  $arguments_to_provide
2277
+	 * @return string
2278
+	 */
2279
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2280
+	{
2281
+		/** @type WPDB $wpdb */
2282
+		global $wpdb;
2283
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2284
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2285
+		$error_message = sprintf(
2286
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2287
+				'event_espresso'),
2288
+			$wpdb->last_error,
2289
+			$wpdb_method,
2290
+			wp_json_encode($arguments_to_provide)
2291
+		);
2292
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2293
+		return $error_message;
2294
+	}
2295
+
2296
+
2297
+
2298
+	/**
2299
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2300
+	 * EEM_Base::$_db_verification_level
2301
+	 *
2302
+	 * @param $wpdb_method
2303
+	 * @param $arguments_to_provide
2304
+	 * @return string
2305
+	 */
2306
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2307
+	{
2308
+		/** @type WPDB $wpdb */
2309
+		global $wpdb;
2310
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2311
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2312
+		$error_message = sprintf(
2313
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2314
+				'event_espresso'),
2315
+			$wpdb->last_error,
2316
+			$wpdb_method,
2317
+			wp_json_encode($arguments_to_provide)
2318
+		);
2319
+		EE_System::instance()->initialize_addons();
2320
+		return $error_message;
2321
+	}
2322
+
2323
+
2324
+
2325
+	/**
2326
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2327
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2328
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2329
+	 * ..."
2330
+	 *
2331
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2332
+	 * @return string
2333
+	 */
2334
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2335
+	{
2336
+		return " FROM " . $model_query_info->get_full_join_sql() .
2337
+			   $model_query_info->get_where_sql() .
2338
+			   $model_query_info->get_group_by_sql() .
2339
+			   $model_query_info->get_having_sql() .
2340
+			   $model_query_info->get_order_by_sql() .
2341
+			   $model_query_info->get_limit_sql();
2342
+	}
2343
+
2344
+
2345
+
2346
+	/**
2347
+	 * Set to easily debug the next X queries ran from this model.
2348
+	 *
2349
+	 * @param int $count
2350
+	 */
2351
+	public function show_next_x_db_queries($count = 1)
2352
+	{
2353
+		$this->_show_next_x_db_queries = $count;
2354
+	}
2355
+
2356
+
2357
+
2358
+	/**
2359
+	 * @param $sql_query
2360
+	 */
2361
+	public function show_db_query_if_previously_requested($sql_query)
2362
+	{
2363
+		if ($this->_show_next_x_db_queries > 0) {
2364
+			echo $sql_query;
2365
+			$this->_show_next_x_db_queries--;
2366
+		}
2367
+	}
2368
+
2369
+
2370
+
2371
+	/**
2372
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2373
+	 * There are the 3 cases:
2374
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2375
+	 * $otherModelObject has no ID, it is first saved.
2376
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2377
+	 * has no ID, it is first saved.
2378
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2379
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2380
+	 * join table
2381
+	 *
2382
+	 * @param        EE_Base_Class                     /int $thisModelObject
2383
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2384
+	 * @param string $relationName                     , key in EEM_Base::_relations
2385
+	 *                                                 an attendee to a group, you also want to specify which role they
2386
+	 *                                                 will have in that group. So you would use this parameter to
2387
+	 *                                                 specify array('role-column-name'=>'role-id')
2388
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2389
+	 *                                                 to for relation to methods that allow you to further specify
2390
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2391
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2392
+	 *                                                 because these will be inserted in any new rows created as well.
2393
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2394
+	 * @throws \EE_Error
2395
+	 */
2396
+	public function add_relationship_to(
2397
+		$id_or_obj,
2398
+		$other_model_id_or_obj,
2399
+		$relationName,
2400
+		$extra_join_model_fields_n_values = array()
2401
+	) {
2402
+		$relation_obj = $this->related_settings_for($relationName);
2403
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2404
+	}
2405
+
2406
+
2407
+
2408
+	/**
2409
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2410
+	 * There are the 3 cases:
2411
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2412
+	 * error
2413
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2414
+	 * an error
2415
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2416
+	 *
2417
+	 * @param        EE_Base_Class /int $id_or_obj
2418
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2419
+	 * @param string $relationName key in EEM_Base::_relations
2420
+	 * @return boolean of success
2421
+	 * @throws \EE_Error
2422
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2423
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2424
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2425
+	 *                             because these will be inserted in any new rows created as well.
2426
+	 */
2427
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2428
+	{
2429
+		$relation_obj = $this->related_settings_for($relationName);
2430
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2431
+	}
2432
+
2433
+
2434
+
2435
+	/**
2436
+	 * @param mixed           $id_or_obj
2437
+	 * @param string          $relationName
2438
+	 * @param array           $where_query_params
2439
+	 * @param EE_Base_Class[] objects to which relations were removed
2440
+	 * @return \EE_Base_Class[]
2441
+	 * @throws \EE_Error
2442
+	 */
2443
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2444
+	{
2445
+		$relation_obj = $this->related_settings_for($relationName);
2446
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2447
+	}
2448
+
2449
+
2450
+
2451
+	/**
2452
+	 * Gets all the related items of the specified $model_name, using $query_params.
2453
+	 * Note: by default, we remove the "default query params"
2454
+	 * because we want to get even deleted items etc.
2455
+	 *
2456
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2457
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2458
+	 * @param array  $query_params like EEM_Base::get_all
2459
+	 * @return EE_Base_Class[]
2460
+	 * @throws \EE_Error
2461
+	 */
2462
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2463
+	{
2464
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2465
+		$relation_settings = $this->related_settings_for($model_name);
2466
+		return $relation_settings->get_all_related($model_obj, $query_params);
2467
+	}
2468
+
2469
+
2470
+
2471
+	/**
2472
+	 * Deletes all the model objects across the relation indicated by $model_name
2473
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2474
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2475
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2476
+	 *
2477
+	 * @param EE_Base_Class|int|string $id_or_obj
2478
+	 * @param string                   $model_name
2479
+	 * @param array                    $query_params
2480
+	 * @return int how many deleted
2481
+	 * @throws \EE_Error
2482
+	 */
2483
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2484
+	{
2485
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2486
+		$relation_settings = $this->related_settings_for($model_name);
2487
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2488
+	}
2489
+
2490
+
2491
+
2492
+	/**
2493
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2494
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2495
+	 * the model objects can't be hard deleted because of blocking related model objects,
2496
+	 * just does a soft-delete on them instead.
2497
+	 *
2498
+	 * @param EE_Base_Class|int|string $id_or_obj
2499
+	 * @param string                   $model_name
2500
+	 * @param array                    $query_params
2501
+	 * @return int how many deleted
2502
+	 * @throws \EE_Error
2503
+	 */
2504
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2505
+	{
2506
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2507
+		$relation_settings = $this->related_settings_for($model_name);
2508
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2509
+	}
2510
+
2511
+
2512
+
2513
+	/**
2514
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2515
+	 * unless otherwise specified in the $query_params
2516
+	 *
2517
+	 * @param        int             /EE_Base_Class $id_or_obj
2518
+	 * @param string $model_name     like 'Event', or 'Registration'
2519
+	 * @param array  $query_params   like EEM_Base::get_all's
2520
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2521
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2522
+	 *                               that by the setting $distinct to TRUE;
2523
+	 * @return int
2524
+	 * @throws \EE_Error
2525
+	 */
2526
+	public function count_related(
2527
+		$id_or_obj,
2528
+		$model_name,
2529
+		$query_params = array(),
2530
+		$field_to_count = null,
2531
+		$distinct = false
2532
+	) {
2533
+		$related_model = $this->get_related_model_obj($model_name);
2534
+		//we're just going to use the query params on the related model's normal get_all query,
2535
+		//except add a condition to say to match the current mod
2536
+		if (! isset($query_params['default_where_conditions'])) {
2537
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2538
+		}
2539
+		$this_model_name = $this->get_this_model_name();
2540
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2541
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
+		return $related_model->count($query_params, $field_to_count, $distinct);
2543
+	}
2544
+
2545
+
2546
+
2547
+	/**
2548
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2549
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2550
+	 *
2551
+	 * @param        int           /EE_Base_Class $id_or_obj
2552
+	 * @param string $model_name   like 'Event', or 'Registration'
2553
+	 * @param array  $query_params like EEM_Base::get_all's
2554
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2555
+	 * @return float
2556
+	 * @throws \EE_Error
2557
+	 */
2558
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2559
+	{
2560
+		$related_model = $this->get_related_model_obj($model_name);
2561
+		if (! is_array($query_params)) {
2562
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2563
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2564
+					gettype($query_params)), '4.6.0');
2565
+			$query_params = array();
2566
+		}
2567
+		//we're just going to use the query params on the related model's normal get_all query,
2568
+		//except add a condition to say to match the current mod
2569
+		if (! isset($query_params['default_where_conditions'])) {
2570
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2571
+		}
2572
+		$this_model_name = $this->get_this_model_name();
2573
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2574
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
+		return $related_model->sum($query_params, $field_to_sum);
2576
+	}
2577
+
2578
+
2579
+
2580
+	/**
2581
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2582
+	 * $modelObject
2583
+	 *
2584
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2585
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2586
+	 * @param array               $query_params     like EEM_Base::get_all's
2587
+	 * @return EE_Base_Class
2588
+	 * @throws \EE_Error
2589
+	 */
2590
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2591
+	{
2592
+		$query_params['limit'] = 1;
2593
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2594
+		if ($results) {
2595
+			return array_shift($results);
2596
+		} else {
2597
+			return null;
2598
+		}
2599
+	}
2600
+
2601
+
2602
+
2603
+	/**
2604
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2605
+	 *
2606
+	 * @return string
2607
+	 */
2608
+	public function get_this_model_name()
2609
+	{
2610
+		return str_replace("EEM_", "", get_class($this));
2611
+	}
2612
+
2613
+
2614
+
2615
+	/**
2616
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2617
+	 *
2618
+	 * @return EE_Any_Foreign_Model_Name_Field
2619
+	 * @throws EE_Error
2620
+	 */
2621
+	public function get_field_containing_related_model_name()
2622
+	{
2623
+		foreach ($this->field_settings(true) as $field) {
2624
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2625
+				$field_with_model_name = $field;
2626
+			}
2627
+		}
2628
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2630
+				$this->get_this_model_name()));
2631
+		}
2632
+		return $field_with_model_name;
2633
+	}
2634
+
2635
+
2636
+
2637
+	/**
2638
+	 * Inserts a new entry into the database, for each table.
2639
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2640
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2641
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2642
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2643
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2644
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2645
+	 *
2646
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2647
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2648
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2649
+	 *                              of EEM_Base)
2650
+	 * @return int new primary key on main table that got inserted
2651
+	 * @throws EE_Error
2652
+	 */
2653
+	public function insert($field_n_values)
2654
+	{
2655
+		/**
2656
+		 * Filters the fields and their values before inserting an item using the models
2657
+		 *
2658
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2659
+		 * @param EEM_Base $model           the model used
2660
+		 */
2661
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2663
+			$main_table = $this->_get_main_table();
2664
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2665
+			if ($new_id !== false) {
2666
+				foreach ($this->_get_other_tables() as $other_table) {
2667
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2668
+				}
2669
+			}
2670
+			/**
2671
+			 * Done just after attempting to insert a new model object
2672
+			 *
2673
+			 * @param EEM_Base   $model           used
2674
+			 * @param array      $fields_n_values fields and their values
2675
+			 * @param int|string the              ID of the newly-inserted model object
2676
+			 */
2677
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2678
+			return $new_id;
2679
+		} else {
2680
+			return false;
2681
+		}
2682
+	}
2683
+
2684
+
2685
+
2686
+	/**
2687
+	 * Checks that the result would satisfy the unique indexes on this model
2688
+	 *
2689
+	 * @param array  $field_n_values
2690
+	 * @param string $action
2691
+	 * @return boolean
2692
+	 * @throws \EE_Error
2693
+	 */
2694
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2695
+	{
2696
+		foreach ($this->unique_indexes() as $index_name => $index) {
2697
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2698
+			if ($this->exists(array($uniqueness_where_params))) {
2699
+				EE_Error::add_error(
2700
+					sprintf(
2701
+						__(
2702
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2703
+							"event_espresso"
2704
+						),
2705
+						$action,
2706
+						$this->_get_class_name(),
2707
+						$index_name,
2708
+						implode(",", $index->field_names()),
2709
+						http_build_query($uniqueness_where_params)
2710
+					),
2711
+					__FILE__,
2712
+					__FUNCTION__,
2713
+					__LINE__
2714
+				);
2715
+				return false;
2716
+			}
2717
+		}
2718
+		return true;
2719
+	}
2720
+
2721
+
2722
+
2723
+	/**
2724
+	 * Checks the database for an item that conflicts (ie, if this item were
2725
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2726
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2727
+	 * can be either an EE_Base_Class or an array of fields n values
2728
+	 *
2729
+	 * @param EE_Base_Class|array $obj_or_fields_array
2730
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2731
+	 *                                                 when looking for conflicts
2732
+	 *                                                 (ie, if false, we ignore the model object's primary key
2733
+	 *                                                 when finding "conflicts". If true, it's also considered).
2734
+	 *                                                 Only works for INT primary key,
2735
+	 *                                                 STRING primary keys cannot be ignored
2736
+	 * @throws EE_Error
2737
+	 * @return EE_Base_Class|array
2738
+	 */
2739
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2740
+	{
2741
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2742
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2743
+		} elseif (is_array($obj_or_fields_array)) {
2744
+			$fields_n_values = $obj_or_fields_array;
2745
+		} else {
2746
+			throw new EE_Error(
2747
+				sprintf(
2748
+					__(
2749
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2750
+						"event_espresso"
2751
+					),
2752
+					get_class($this),
2753
+					$obj_or_fields_array
2754
+				)
2755
+			);
2756
+		}
2757
+		$query_params = array();
2758
+		if ($this->has_primary_key_field()
2759
+			&& ($include_primary_key
2760
+				|| $this->get_primary_key_field()
2761
+				   instanceof
2762
+				   EE_Primary_Key_String_Field)
2763
+			&& isset($fields_n_values[$this->primary_key_name()])
2764
+		) {
2765
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2766
+		}
2767
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2768
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2769
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
+		}
2771
+		//if there is nothing to base this search on, then we shouldn't find anything
2772
+		if (empty($query_params)) {
2773
+			return array();
2774
+		} else {
2775
+			return $this->get_one($query_params);
2776
+		}
2777
+	}
2778
+
2779
+
2780
+
2781
+	/**
2782
+	 * Like count, but is optimized and returns a boolean instead of an int
2783
+	 *
2784
+	 * @param array $query_params
2785
+	 * @return boolean
2786
+	 * @throws \EE_Error
2787
+	 */
2788
+	public function exists($query_params)
2789
+	{
2790
+		$query_params['limit'] = 1;
2791
+		return $this->count($query_params) > 0;
2792
+	}
2793
+
2794
+
2795
+
2796
+	/**
2797
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2798
+	 *
2799
+	 * @param int|string $id
2800
+	 * @return boolean
2801
+	 * @throws \EE_Error
2802
+	 */
2803
+	public function exists_by_ID($id)
2804
+	{
2805
+		return $this->exists(
2806
+			array(
2807
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2808
+				array(
2809
+					$this->primary_key_name() => $id,
2810
+				),
2811
+			)
2812
+		);
2813
+	}
2814
+
2815
+
2816
+
2817
+	/**
2818
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2819
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2820
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2821
+	 * on the main table)
2822
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2823
+	 * cases where we want to call it directly rather than via insert().
2824
+	 *
2825
+	 * @access   protected
2826
+	 * @param EE_Table_Base $table
2827
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2828
+	 *                                       float
2829
+	 * @param int           $new_id          for now we assume only int keys
2830
+	 * @throws EE_Error
2831
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2832
+	 * @return int ID of new row inserted, or FALSE on failure
2833
+	 */
2834
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2835
+	{
2836
+		global $wpdb;
2837
+		$insertion_col_n_values = array();
2838
+		$format_for_insertion = array();
2839
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2840
+		foreach ($fields_on_table as $field_name => $field_obj) {
2841
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2842
+			if ($field_obj->is_auto_increment()) {
2843
+				continue;
2844
+			}
2845
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2846
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2847
+			if ($prepared_value !== null) {
2848
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2849
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2850
+			}
2851
+		}
2852
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2853
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2854
+			//so add the fk to the main table as a column
2855
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2856
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
+		}
2858
+		//insert the new entry
2859
+		$result = $this->_do_wpdb_query('insert',
2860
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2861
+		if ($result === false) {
2862
+			return false;
2863
+		}
2864
+		//ok, now what do we return for the ID of the newly-inserted thing?
2865
+		if ($this->has_primary_key_field()) {
2866
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2867
+				return $wpdb->insert_id;
2868
+			} else {
2869
+				//it's not an auto-increment primary key, so
2870
+				//it must have been supplied
2871
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2872
+			}
2873
+		} else {
2874
+			//we can't return a  primary key because there is none. instead return
2875
+			//a unique string indicating this model
2876
+			return $this->get_index_primary_key_string($fields_n_values);
2877
+		}
2878
+	}
2879
+
2880
+
2881
+
2882
+	/**
2883
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2884
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2885
+	 * and there is no default, we pass it along. WPDB will take care of it)
2886
+	 *
2887
+	 * @param EE_Model_Field_Base $field_obj
2888
+	 * @param array               $fields_n_values
2889
+	 * @return mixed string|int|float depending on what the table column will be expecting
2890
+	 * @throws \EE_Error
2891
+	 */
2892
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2893
+	{
2894
+		//if this field doesn't allow nullable, don't allow it
2895
+		if (! $field_obj->is_nullable()
2896
+			&& (
2897
+				! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2898
+		) {
2899
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2900
+		}
2901
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2902
+			: null;
2903
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2904
+	}
2905
+
2906
+
2907
+
2908
+	/**
2909
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2910
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2911
+	 * the field's prepare_for_set() method.
2912
+	 *
2913
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2914
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2915
+	 *                                   top of file)
2916
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2917
+	 *                                   $value is a custom selection
2918
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2919
+	 */
2920
+	private function _prepare_value_for_use_in_db($value, $field)
2921
+	{
2922
+		if ($field && $field instanceof EE_Model_Field_Base) {
2923
+			switch ($this->_values_already_prepared_by_model_object) {
2924
+				/** @noinspection PhpMissingBreakStatementInspection */
2925
+				case self::not_prepared_by_model_object:
2926
+					$value = $field->prepare_for_set($value);
2927
+				//purposefully left out "return"
2928
+				case self::prepared_by_model_object:
2929
+					$value = $field->prepare_for_use_in_db($value);
2930
+				case self::prepared_for_use_in_db:
2931
+					//leave the value alone
2932
+			}
2933
+			return $value;
2934
+		} else {
2935
+			return $value;
2936
+		}
2937
+	}
2938
+
2939
+
2940
+
2941
+	/**
2942
+	 * Returns the main table on this model
2943
+	 *
2944
+	 * @return EE_Primary_Table
2945
+	 * @throws EE_Error
2946
+	 */
2947
+	protected function _get_main_table()
2948
+	{
2949
+		foreach ($this->_tables as $table) {
2950
+			if ($table instanceof EE_Primary_Table) {
2951
+				return $table;
2952
+			}
2953
+		}
2954
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2955
+			'event_espresso'), get_class($this)));
2956
+	}
2957
+
2958
+
2959
+
2960
+	/**
2961
+	 * table
2962
+	 * returns EE_Primary_Table table name
2963
+	 *
2964
+	 * @return string
2965
+	 * @throws \EE_Error
2966
+	 */
2967
+	public function table()
2968
+	{
2969
+		return $this->_get_main_table()->get_table_name();
2970
+	}
2971
+
2972
+
2973
+
2974
+	/**
2975
+	 * table
2976
+	 * returns first EE_Secondary_Table table name
2977
+	 *
2978
+	 * @return string
2979
+	 */
2980
+	public function second_table()
2981
+	{
2982
+		// grab second table from tables array
2983
+		$second_table = end($this->_tables);
2984
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2985
+	}
2986
+
2987
+
2988
+
2989
+	/**
2990
+	 * get_table_obj_by_alias
2991
+	 * returns table name given it's alias
2992
+	 *
2993
+	 * @param string $table_alias
2994
+	 * @return EE_Primary_Table | EE_Secondary_Table
2995
+	 */
2996
+	public function get_table_obj_by_alias($table_alias = '')
2997
+	{
2998
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2999
+	}
3000
+
3001
+
3002
+
3003
+	/**
3004
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3005
+	 *
3006
+	 * @return EE_Secondary_Table[]
3007
+	 */
3008
+	protected function _get_other_tables()
3009
+	{
3010
+		$other_tables = array();
3011
+		foreach ($this->_tables as $table_alias => $table) {
3012
+			if ($table instanceof EE_Secondary_Table) {
3013
+				$other_tables[$table_alias] = $table;
3014
+			}
3015
+		}
3016
+		return $other_tables;
3017
+	}
3018
+
3019
+
3020
+
3021
+	/**
3022
+	 * Finds all the fields that correspond to the given table
3023
+	 *
3024
+	 * @param string $table_alias , array key in EEM_Base::_tables
3025
+	 * @return EE_Model_Field_Base[]
3026
+	 */
3027
+	public function _get_fields_for_table($table_alias)
3028
+	{
3029
+		return $this->_fields[$table_alias];
3030
+	}
3031
+
3032
+
3033
+
3034
+	/**
3035
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3036
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3037
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3038
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3039
+	 * related Registration, Transaction, and Payment models.
3040
+	 *
3041
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3042
+	 * @return EE_Model_Query_Info_Carrier
3043
+	 * @throws \EE_Error
3044
+	 */
3045
+	public function _extract_related_models_from_query($query_params)
3046
+	{
3047
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3048
+		if (array_key_exists(0, $query_params)) {
3049
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3050
+		}
3051
+		if (array_key_exists('group_by', $query_params)) {
3052
+			if (is_array($query_params['group_by'])) {
3053
+				$this->_extract_related_models_from_sub_params_array_values(
3054
+					$query_params['group_by'],
3055
+					$query_info_carrier,
3056
+					'group_by'
3057
+				);
3058
+			} elseif (! empty ($query_params['group_by'])) {
3059
+				$this->_extract_related_model_info_from_query_param(
3060
+					$query_params['group_by'],
3061
+					$query_info_carrier,
3062
+					'group_by'
3063
+				);
3064
+			}
3065
+		}
3066
+		if (array_key_exists('having', $query_params)) {
3067
+			$this->_extract_related_models_from_sub_params_array_keys(
3068
+				$query_params[0],
3069
+				$query_info_carrier,
3070
+				'having'
3071
+			);
3072
+		}
3073
+		if (array_key_exists('order_by', $query_params)) {
3074
+			if (is_array($query_params['order_by'])) {
3075
+				$this->_extract_related_models_from_sub_params_array_keys(
3076
+					$query_params['order_by'],
3077
+					$query_info_carrier,
3078
+					'order_by'
3079
+				);
3080
+			} elseif (! empty($query_params['order_by'])) {
3081
+				$this->_extract_related_model_info_from_query_param(
3082
+					$query_params['order_by'],
3083
+					$query_info_carrier,
3084
+					'order_by'
3085
+				);
3086
+			}
3087
+		}
3088
+		if (array_key_exists('force_join', $query_params)) {
3089
+			$this->_extract_related_models_from_sub_params_array_values(
3090
+				$query_params['force_join'],
3091
+				$query_info_carrier,
3092
+				'force_join'
3093
+			);
3094
+		}
3095
+		return $query_info_carrier;
3096
+	}
3097
+
3098
+
3099
+
3100
+	/**
3101
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3102
+	 *
3103
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3104
+	 *                                                      $query_params['having']
3105
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3106
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3107
+	 * @throws EE_Error
3108
+	 * @return \EE_Model_Query_Info_Carrier
3109
+	 */
3110
+	private function _extract_related_models_from_sub_params_array_keys(
3111
+		$sub_query_params,
3112
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3113
+		$query_param_type
3114
+	) {
3115
+		if (! empty($sub_query_params)) {
3116
+			$sub_query_params = (array)$sub_query_params;
3117
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3118
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3119
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3120
+					$query_param_type);
3121
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3122
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3123
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3124
+				//of array('Registration.TXN_ID'=>23)
3125
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3126
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3127
+					if (! is_array($possibly_array_of_params)) {
3128
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3129
+							"event_espresso"),
3130
+							$param, $possibly_array_of_params));
3131
+					} else {
3132
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3133
+							$model_query_info_carrier, $query_param_type);
3134
+					}
3135
+				} elseif ($query_param_type === 0 //ie WHERE
3136
+						  && is_array($possibly_array_of_params)
3137
+						  && isset($possibly_array_of_params[2])
3138
+						  && $possibly_array_of_params[2] == true
3139
+				) {
3140
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3141
+					//indicating that $possible_array_of_params[1] is actually a field name,
3142
+					//from which we should extract query parameters!
3143
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3144
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3145
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3146
+					}
3147
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3148
+						$model_query_info_carrier, $query_param_type);
3149
+				}
3150
+			}
3151
+		}
3152
+		return $model_query_info_carrier;
3153
+	}
3154
+
3155
+
3156
+
3157
+	/**
3158
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3159
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3160
+	 *
3161
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3162
+	 *                                                      $query_params['having']
3163
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3164
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3165
+	 * @throws EE_Error
3166
+	 * @return \EE_Model_Query_Info_Carrier
3167
+	 */
3168
+	private function _extract_related_models_from_sub_params_array_values(
3169
+		$sub_query_params,
3170
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3171
+		$query_param_type
3172
+	) {
3173
+		if (! empty($sub_query_params)) {
3174
+			if (! is_array($sub_query_params)) {
3175
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3176
+					$sub_query_params));
3177
+			}
3178
+			foreach ($sub_query_params as $param) {
3179
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3180
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3181
+					$query_param_type);
3182
+			}
3183
+		}
3184
+		return $model_query_info_carrier;
3185
+	}
3186
+
3187
+
3188
+
3189
+	/**
3190
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3191
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3192
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3193
+	 * but use them in a different order. Eg, we need to know what models we are querying
3194
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3195
+	 * other models before we can finalize the where clause SQL.
3196
+	 *
3197
+	 * @param array $query_params
3198
+	 * @throws EE_Error
3199
+	 * @return EE_Model_Query_Info_Carrier
3200
+	 */
3201
+	public function _create_model_query_info_carrier($query_params)
3202
+	{
3203
+		if (! is_array($query_params)) {
3204
+			EE_Error::doing_it_wrong(
3205
+				'EEM_Base::_create_model_query_info_carrier',
3206
+				sprintf(
3207
+					__(
3208
+						'$query_params should be an array, you passed a variable of type %s',
3209
+						'event_espresso'
3210
+					),
3211
+					gettype($query_params)
3212
+				),
3213
+				'4.6.0'
3214
+			);
3215
+			$query_params = array();
3216
+		}
3217
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3218
+		//first check if we should alter the query to account for caps or not
3219
+		//because the caps might require us to do extra joins
3220
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3221
+			$query_params[0] = $where_query_params = array_replace_recursive(
3222
+				$where_query_params,
3223
+				$this->caps_where_conditions(
3224
+					$query_params['caps']
3225
+				)
3226
+			);
3227
+		}
3228
+		$query_object = $this->_extract_related_models_from_query($query_params);
3229
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3230
+		foreach ($where_query_params as $key => $value) {
3231
+			if (is_int($key)) {
3232
+				throw new EE_Error(
3233
+					sprintf(
3234
+						__(
3235
+							"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.",
3236
+							"event_espresso"
3237
+						),
3238
+						$key,
3239
+						var_export($value, true),
3240
+						var_export($query_params, true),
3241
+						get_class($this)
3242
+					)
3243
+				);
3244
+			}
3245
+		}
3246
+		if (
3247
+			array_key_exists('default_where_conditions', $query_params)
3248
+			&& ! empty($query_params['default_where_conditions'])
3249
+		) {
3250
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3251
+		} else {
3252
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3253
+		}
3254
+		$where_query_params = array_merge(
3255
+			$this->_get_default_where_conditions_for_models_in_query(
3256
+				$query_object,
3257
+				$use_default_where_conditions,
3258
+				$where_query_params
3259
+			),
3260
+			$where_query_params
3261
+		);
3262
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3263
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3264
+		// So we need to setup a subquery and use that for the main join.
3265
+		// Note for now this only works on the primary table for the model.
3266
+		// So for instance, you could set the limit array like this:
3267
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3268
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3269
+			$query_object->set_main_model_join_sql(
3270
+				$this->_construct_limit_join_select(
3271
+					$query_params['on_join_limit'][0],
3272
+					$query_params['on_join_limit'][1]
3273
+				)
3274
+			);
3275
+		}
3276
+		//set limit
3277
+		if (array_key_exists('limit', $query_params)) {
3278
+			if (is_array($query_params['limit'])) {
3279
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3280
+					$e = sprintf(
3281
+						__(
3282
+							"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)",
3283
+							"event_espresso"
3284
+						),
3285
+						http_build_query($query_params['limit'])
3286
+					);
3287
+					throw new EE_Error($e . "|" . $e);
3288
+				}
3289
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3290
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3291
+			} elseif (! empty ($query_params['limit'])) {
3292
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3293
+			}
3294
+		}
3295
+		//set order by
3296
+		if (array_key_exists('order_by', $query_params)) {
3297
+			if (is_array($query_params['order_by'])) {
3298
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3299
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3300
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3301
+				if (array_key_exists('order', $query_params)) {
3302
+					throw new EE_Error(
3303
+						sprintf(
3304
+							__(
3305
+								"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 ",
3306
+								"event_espresso"
3307
+							),
3308
+							get_class($this),
3309
+							implode(", ", array_keys($query_params['order_by'])),
3310
+							implode(", ", $query_params['order_by']),
3311
+							$query_params['order']
3312
+						)
3313
+					);
3314
+				}
3315
+				$this->_extract_related_models_from_sub_params_array_keys(
3316
+					$query_params['order_by'],
3317
+					$query_object,
3318
+					'order_by'
3319
+				);
3320
+				//assume it's an array of fields to order by
3321
+				$order_array = array();
3322
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3323
+					$order = $this->_extract_order($order);
3324
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3325
+				}
3326
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3327
+			} elseif (! empty ($query_params['order_by'])) {
3328
+				$this->_extract_related_model_info_from_query_param(
3329
+					$query_params['order_by'],
3330
+					$query_object,
3331
+					'order',
3332
+					$query_params['order_by']
3333
+				);
3334
+				$order = isset($query_params['order'])
3335
+					? $this->_extract_order($query_params['order'])
3336
+					: 'DESC';
3337
+				$query_object->set_order_by_sql(
3338
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3339
+				);
3340
+			}
3341
+		}
3342
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3343
+		if (! array_key_exists('order_by', $query_params)
3344
+			&& array_key_exists('order', $query_params)
3345
+			&& ! empty($query_params['order'])
3346
+		) {
3347
+			$pk_field = $this->get_primary_key_field();
3348
+			$order = $this->_extract_order($query_params['order']);
3349
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3350
+		}
3351
+		//set group by
3352
+		if (array_key_exists('group_by', $query_params)) {
3353
+			if (is_array($query_params['group_by'])) {
3354
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3355
+				$group_by_array = array();
3356
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3357
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3358
+				}
3359
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3360
+			} elseif (! empty ($query_params['group_by'])) {
3361
+				$query_object->set_group_by_sql(
3362
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3363
+				);
3364
+			}
3365
+		}
3366
+		//set having
3367
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3368
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3369
+		}
3370
+		//now, just verify they didn't pass anything wack
3371
+		foreach ($query_params as $query_key => $query_value) {
3372
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3373
+				throw new EE_Error(
3374
+					sprintf(
3375
+						__(
3376
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3377
+							'event_espresso'
3378
+						),
3379
+						$query_key,
3380
+						get_class($this),
3381
+						//						print_r( $this->_allowed_query_params, TRUE )
3382
+						implode(',', $this->_allowed_query_params)
3383
+					)
3384
+				);
3385
+			}
3386
+		}
3387
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3388
+		if (empty($main_model_join_sql)) {
3389
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3390
+		}
3391
+		return $query_object;
3392
+	}
3393
+
3394
+
3395
+
3396
+	/**
3397
+	 * Gets the where conditions that should be imposed on the query based on the
3398
+	 * context (eg reading frontend, backend, edit or delete).
3399
+	 *
3400
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3401
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3402
+	 * @throws \EE_Error
3403
+	 */
3404
+	public function caps_where_conditions($context = self::caps_read)
3405
+	{
3406
+		EEM_Base::verify_is_valid_cap_context($context);
3407
+		$cap_where_conditions = array();
3408
+		$cap_restrictions = $this->caps_missing($context);
3409
+		/**
3410
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3411
+		 */
3412
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3413
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3414
+				$restriction_if_no_cap->get_default_where_conditions());
3415
+		}
3416
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3417
+			$cap_restrictions);
3418
+	}
3419
+
3420
+
3421
+
3422
+	/**
3423
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3424
+	 * otherwise throws an exception
3425
+	 *
3426
+	 * @param string $should_be_order_string
3427
+	 * @return string either ASC, asc, DESC or desc
3428
+	 * @throws EE_Error
3429
+	 */
3430
+	private function _extract_order($should_be_order_string)
3431
+	{
3432
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3433
+			return $should_be_order_string;
3434
+		} else {
3435
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3436
+				"event_espresso"), get_class($this), $should_be_order_string));
3437
+		}
3438
+	}
3439
+
3440
+
3441
+
3442
+	/**
3443
+	 * Looks at all the models which are included in this query, and asks each
3444
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3445
+	 * so they can be merged
3446
+	 *
3447
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3448
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3449
+	 *                                                                  'none' means NO default where conditions will
3450
+	 *                                                                  be used AT ALL during this query.
3451
+	 *                                                                  'other_models_only' means default where
3452
+	 *                                                                  conditions from other models will be used, but
3453
+	 *                                                                  not for this primary model. 'all', the default,
3454
+	 *                                                                  means default where conditions will apply as
3455
+	 *                                                                  normal
3456
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3457
+	 * @throws EE_Error
3458
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3459
+	 */
3460
+	private function _get_default_where_conditions_for_models_in_query(
3461
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3462
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3463
+		$where_query_params = array()
3464
+	) {
3465
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3466
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3467
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3468
+				"event_espresso"), $use_default_where_conditions,
3469
+				implode(", ", $allowed_used_default_where_conditions_values)));
3470
+		}
3471
+		$universal_query_params = array();
3472
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3473
+			$universal_query_params = $this->_get_default_where_conditions();
3474
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3475
+			$universal_query_params = $this->_get_minimum_where_conditions();
3476
+		}
3477
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3478
+			$related_model = $this->get_related_model_obj($model_name);
3479
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3480
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3481
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3482
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3483
+			} else {
3484
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3485
+				continue;
3486
+			}
3487
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3488
+				$related_model_universal_where_params,
3489
+				$where_query_params,
3490
+				$related_model,
3491
+				$model_relation_path
3492
+			);
3493
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3494
+				$universal_query_params,
3495
+				$overrides
3496
+			);
3497
+		}
3498
+		return $universal_query_params;
3499
+	}
3500
+
3501
+
3502
+
3503
+	/**
3504
+	 * Determines whether or not we should use default where conditions for the model in question
3505
+	 * (this model, or other related models).
3506
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3507
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3508
+	 * We should use default where conditions on related models when they requested to use default where conditions
3509
+	 * on all models, or specifically just on other related models
3510
+	 * @param      $default_where_conditions_value
3511
+	 * @param bool $for_this_model false means this is for OTHER related models
3512
+	 * @return bool
3513
+	 */
3514
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3515
+	{
3516
+		return (
3517
+				   $for_this_model
3518
+				   && in_array(
3519
+					   $default_where_conditions_value,
3520
+					   array(
3521
+						   EEM_Base::default_where_conditions_all,
3522
+						   EEM_Base::default_where_conditions_this_only,
3523
+						   EEM_Base::default_where_conditions_minimum_others,
3524
+					   ),
3525
+					   true
3526
+				   )
3527
+			   )
3528
+			   || (
3529
+				   ! $for_this_model
3530
+				   && in_array(
3531
+					   $default_where_conditions_value,
3532
+					   array(
3533
+						   EEM_Base::default_where_conditions_all,
3534
+						   EEM_Base::default_where_conditions_others_only,
3535
+					   ),
3536
+					   true
3537
+				   )
3538
+			   );
3539
+	}
3540
+
3541
+	/**
3542
+	 * Determines whether or not we should use default minimum conditions for the model in question
3543
+	 * (this model, or other related models).
3544
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3545
+	 * where conditions.
3546
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3547
+	 * on this model or others
3548
+	 * @param      $default_where_conditions_value
3549
+	 * @param bool $for_this_model false means this is for OTHER related models
3550
+	 * @return bool
3551
+	 */
3552
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3553
+	{
3554
+		return (
3555
+				   $for_this_model
3556
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3557
+			   )
3558
+			   || (
3559
+				   ! $for_this_model
3560
+				   && in_array(
3561
+					   $default_where_conditions_value,
3562
+					   array(
3563
+						   EEM_Base::default_where_conditions_minimum_others,
3564
+						   EEM_Base::default_where_conditions_minimum_all,
3565
+					   ),
3566
+					   true
3567
+				   )
3568
+			   );
3569
+	}
3570
+
3571
+
3572
+	/**
3573
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3574
+	 * then we also add a special where condition which allows for that model's primary key
3575
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3576
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3577
+	 *
3578
+	 * @param array    $default_where_conditions
3579
+	 * @param array    $provided_where_conditions
3580
+	 * @param EEM_Base $model
3581
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3582
+	 * @return array like EEM_Base::get_all's $query_params[0]
3583
+	 * @throws \EE_Error
3584
+	 */
3585
+	private function _override_defaults_or_make_null_friendly(
3586
+		$default_where_conditions,
3587
+		$provided_where_conditions,
3588
+		$model,
3589
+		$model_relation_path
3590
+	) {
3591
+		$null_friendly_where_conditions = array();
3592
+		$none_overridden = true;
3593
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3594
+		foreach ($default_where_conditions as $key => $val) {
3595
+			if (isset($provided_where_conditions[$key])) {
3596
+				$none_overridden = false;
3597
+			} else {
3598
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3599
+			}
3600
+		}
3601
+		if ($none_overridden && $default_where_conditions) {
3602
+			if ($model->has_primary_key_field()) {
3603
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3604
+																				. "."
3605
+																				. $model->primary_key_name()] = array('IS NULL');
3606
+			}/*else{
3607 3607
 				//@todo NO PK, use other defaults
3608 3608
 			}*/
3609
-        }
3610
-        return $null_friendly_where_conditions;
3611
-    }
3612
-
3613
-
3614
-
3615
-    /**
3616
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3617
-     * default where conditions on all get_all, update, and delete queries done by this model.
3618
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3619
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3620
-     *
3621
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3622
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3623
-     */
3624
-    private function _get_default_where_conditions($model_relation_path = null)
3625
-    {
3626
-        if ($this->_ignore_where_strategy) {
3627
-            return array();
3628
-        }
3629
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3630
-    }
3631
-
3632
-
3633
-
3634
-    /**
3635
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3636
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3637
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3638
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3639
-     * Similar to _get_default_where_conditions
3640
-     *
3641
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3642
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3643
-     */
3644
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3645
-    {
3646
-        if ($this->_ignore_where_strategy) {
3647
-            return array();
3648
-        }
3649
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3650
-    }
3651
-
3652
-
3653
-
3654
-    /**
3655
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3656
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3657
-     *
3658
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3659
-     * @return string
3660
-     * @throws \EE_Error
3661
-     */
3662
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3663
-    {
3664
-        $selects = $this->_get_columns_to_select_for_this_model();
3665
-        foreach (
3666
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3667
-            $name_of_other_model_included
3668
-        ) {
3669
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3670
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3671
-            foreach ($other_model_selects as $key => $value) {
3672
-                $selects[] = $value;
3673
-            }
3674
-        }
3675
-        return implode(", ", $selects);
3676
-    }
3677
-
3678
-
3679
-
3680
-    /**
3681
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3682
-     * So that's going to be the columns for all the fields on the model
3683
-     *
3684
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3685
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3686
-     */
3687
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3688
-    {
3689
-        $fields = $this->field_settings();
3690
-        $selects = array();
3691
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3692
-            $this->get_this_model_name());
3693
-        foreach ($fields as $field_obj) {
3694
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3695
-                         . $field_obj->get_table_alias()
3696
-                         . "."
3697
-                         . $field_obj->get_table_column()
3698
-                         . " AS '"
3699
-                         . $table_alias_with_model_relation_chain_prefix
3700
-                         . $field_obj->get_table_alias()
3701
-                         . "."
3702
-                         . $field_obj->get_table_column()
3703
-                         . "'";
3704
-        }
3705
-        //make sure we are also getting the PKs of each table
3706
-        $tables = $this->get_tables();
3707
-        if (count($tables) > 1) {
3708
-            foreach ($tables as $table_obj) {
3709
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3710
-                                       . $table_obj->get_fully_qualified_pk_column();
3711
-                if (! in_array($qualified_pk_column, $selects)) {
3712
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3713
-                }
3714
-            }
3715
-        }
3716
-        return $selects;
3717
-    }
3718
-
3719
-
3720
-
3721
-    /**
3722
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3723
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3724
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3725
-     * SQL for joining, and the data types
3726
-     *
3727
-     * @param null|string                 $original_query_param
3728
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3729
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3730
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3731
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3732
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3733
-     *                                                          or 'Registration's
3734
-     * @param string                      $original_query_param what it originally was (eg
3735
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3736
-     *                                                          matches $query_param
3737
-     * @throws EE_Error
3738
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3739
-     */
3740
-    private function _extract_related_model_info_from_query_param(
3741
-        $query_param,
3742
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3743
-        $query_param_type,
3744
-        $original_query_param = null
3745
-    ) {
3746
-        if ($original_query_param === null) {
3747
-            $original_query_param = $query_param;
3748
-        }
3749
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3750
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3751
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3752
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3753
-        //check to see if we have a field on this model
3754
-        $this_model_fields = $this->field_settings(true);
3755
-        if (array_key_exists($query_param, $this_model_fields)) {
3756
-            if ($allow_fields) {
3757
-                return;
3758
-            } else {
3759
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3760
-                    "event_espresso"),
3761
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3762
-            }
3763
-        } //check if this is a special logic query param
3764
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3765
-            if ($allow_logic_query_params) {
3766
-                return;
3767
-            } else {
3768
-                throw new EE_Error(
3769
-                    sprintf(
3770
-                        __('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',
3771
-                            'event_espresso'),
3772
-                        implode('", "', $this->_logic_query_param_keys),
3773
-                        $query_param,
3774
-                        get_class($this),
3775
-                        '<br />',
3776
-                        "\t"
3777
-                        . ' $passed_in_query_info = <pre>'
3778
-                        . print_r($passed_in_query_info, true)
3779
-                        . '</pre>'
3780
-                        . "\n\t"
3781
-                        . ' $query_param_type = '
3782
-                        . $query_param_type
3783
-                        . "\n\t"
3784
-                        . ' $original_query_param = '
3785
-                        . $original_query_param
3786
-                    )
3787
-                );
3788
-            }
3789
-        } //check if it's a custom selection
3790
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3791
-            return;
3792
-        }
3793
-        //check if has a model name at the beginning
3794
-        //and
3795
-        //check if it's a field on a related model
3796
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3797
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3798
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3799
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3800
-                if ($query_param === '') {
3801
-                    //nothing left to $query_param
3802
-                    //we should actually end in a field name, not a model like this!
3803
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3804
-                        "event_espresso"),
3805
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3806
-                } else {
3807
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3808
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3809
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3810
-                    return;
3811
-                }
3812
-            } elseif ($query_param === $valid_related_model_name) {
3813
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3814
-                return;
3815
-            }
3816
-        }
3817
-        //ok so $query_param didn't start with a model name
3818
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3819
-        //it's wack, that's what it is
3820
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3821
-            "event_espresso"),
3822
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3823
-    }
3824
-
3825
-
3826
-
3827
-    /**
3828
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3829
-     * and store it on $passed_in_query_info
3830
-     *
3831
-     * @param string                      $model_name
3832
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3833
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3834
-     *                                                          model and $model_name. Eg, if we are querying Event,
3835
-     *                                                          and are adding a join to 'Payment' with the original
3836
-     *                                                          query param key
3837
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3838
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3839
-     *                                                          Payment wants to add default query params so that it
3840
-     *                                                          will know what models to prepend onto its default query
3841
-     *                                                          params or in case it wants to rename tables (in case
3842
-     *                                                          there are multiple joins to the same table)
3843
-     * @return void
3844
-     * @throws \EE_Error
3845
-     */
3846
-    private function _add_join_to_model(
3847
-        $model_name,
3848
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3849
-        $original_query_param
3850
-    ) {
3851
-        $relation_obj = $this->related_settings_for($model_name);
3852
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3853
-        //check if the relation is HABTM, because then we're essentially doing two joins
3854
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3855
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3856
-            $join_model_obj = $relation_obj->get_join_model();
3857
-            //replace the model specified with the join model for this relation chain, whi
3858
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3859
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3860
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3861
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3862
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3863
-            $passed_in_query_info->merge($new_query_info);
3864
-        }
3865
-        //now just join to the other table pointed to by the relation object, and add its data types
3866
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3867
-            array($model_relation_chain => $model_name),
3868
-            $relation_obj->get_join_statement($model_relation_chain));
3869
-        $passed_in_query_info->merge($new_query_info);
3870
-    }
3871
-
3872
-
3873
-
3874
-    /**
3875
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3876
-     *
3877
-     * @param array $where_params like EEM_Base::get_all
3878
-     * @return string of SQL
3879
-     * @throws \EE_Error
3880
-     */
3881
-    private function _construct_where_clause($where_params)
3882
-    {
3883
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3884
-        if ($SQL) {
3885
-            return " WHERE " . $SQL;
3886
-        } else {
3887
-            return '';
3888
-        }
3889
-    }
3890
-
3891
-
3892
-
3893
-    /**
3894
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3895
-     * and should be passed HAVING parameters, not WHERE parameters
3896
-     *
3897
-     * @param array $having_params
3898
-     * @return string
3899
-     * @throws \EE_Error
3900
-     */
3901
-    private function _construct_having_clause($having_params)
3902
-    {
3903
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3904
-        if ($SQL) {
3905
-            return " HAVING " . $SQL;
3906
-        } else {
3907
-            return '';
3908
-        }
3909
-    }
3910
-
3911
-
3912
-
3913
-    /**
3914
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3915
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3916
-     * EEM_Attendee.
3917
-     *
3918
-     * @param string $field_name
3919
-     * @param string $model_name
3920
-     * @return EE_Model_Field_Base
3921
-     * @throws EE_Error
3922
-     */
3923
-    protected function _get_field_on_model($field_name, $model_name)
3924
-    {
3925
-        $model_class = 'EEM_' . $model_name;
3926
-        $model_filepath = $model_class . ".model.php";
3927
-        if (is_readable($model_filepath)) {
3928
-            require_once($model_filepath);
3929
-            $model_instance = call_user_func($model_name . "::instance");
3930
-            /* @var $model_instance EEM_Base */
3931
-            return $model_instance->field_settings_for($field_name);
3932
-        } else {
3933
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3934
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3935
-        }
3936
-    }
3937
-
3938
-
3939
-
3940
-    /**
3941
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3942
-     * Event_Meta.meta_value = 'foo'))"
3943
-     *
3944
-     * @param array  $where_params see EEM_Base::get_all for documentation
3945
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3946
-     * @throws EE_Error
3947
-     * @return string of SQL
3948
-     */
3949
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3950
-    {
3951
-        $where_clauses = array();
3952
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3953
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3954
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3955
-                switch ($query_param) {
3956
-                    case 'not':
3957
-                    case 'NOT':
3958
-                        $where_clauses[] = "! ("
3959
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3960
-                                $glue)
3961
-                                           . ")";
3962
-                        break;
3963
-                    case 'and':
3964
-                    case 'AND':
3965
-                        $where_clauses[] = " ("
3966
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3967
-                                ' AND ')
3968
-                                           . ")";
3969
-                        break;
3970
-                    case 'or':
3971
-                    case 'OR':
3972
-                        $where_clauses[] = " ("
3973
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3974
-                                ' OR ')
3975
-                                           . ")";
3976
-                        break;
3977
-                }
3978
-            } else {
3979
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3980
-                //if it's not a normal field, maybe it's a custom selection?
3981
-                if (! $field_obj) {
3982
-                    if (isset($this->_custom_selections[$query_param][1])) {
3983
-                        $field_obj = $this->_custom_selections[$query_param][1];
3984
-                    } else {
3985
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3986
-                            "event_espresso"), $query_param));
3987
-                    }
3988
-                }
3989
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3990
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3991
-            }
3992
-        }
3993
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3994
-    }
3995
-
3996
-
3997
-
3998
-    /**
3999
-     * Takes the input parameter and extract the table name (alias) and column name
4000
-     *
4001
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4002
-     * @throws EE_Error
4003
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4004
-     */
4005
-    private function _deduce_column_name_from_query_param($query_param)
4006
-    {
4007
-        $field = $this->_deduce_field_from_query_param($query_param);
4008
-        if ($field) {
4009
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4010
-                $query_param);
4011
-            return $table_alias_prefix . $field->get_qualified_column();
4012
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4013
-            //maybe it's custom selection item?
4014
-            //if so, just use it as the "column name"
4015
-            return $query_param;
4016
-        } else {
4017
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4018
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4019
-        }
4020
-    }
4021
-
4022
-
4023
-
4024
-    /**
4025
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4026
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4027
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4028
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4029
-     *
4030
-     * @param string $condition_query_param_key
4031
-     * @return string
4032
-     */
4033
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4034
-    {
4035
-        $pos_of_star = strpos($condition_query_param_key, '*');
4036
-        if ($pos_of_star === false) {
4037
-            return $condition_query_param_key;
4038
-        } else {
4039
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4040
-            return $condition_query_param_sans_star;
4041
-        }
4042
-    }
4043
-
4044
-
4045
-
4046
-    /**
4047
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4048
-     *
4049
-     * @param                            mixed      array | string    $op_and_value
4050
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4051
-     * @throws EE_Error
4052
-     * @return string
4053
-     */
4054
-    private function _construct_op_and_value($op_and_value, $field_obj)
4055
-    {
4056
-        if (is_array($op_and_value)) {
4057
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4058
-            if (! $operator) {
4059
-                $php_array_like_string = array();
4060
-                foreach ($op_and_value as $key => $value) {
4061
-                    $php_array_like_string[] = "$key=>$value";
4062
-                }
4063
-                throw new EE_Error(
4064
-                    sprintf(
4065
-                        __(
4066
-                            "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))",
4067
-                            "event_espresso"
4068
-                        ),
4069
-                        implode(",", $php_array_like_string)
4070
-                    )
4071
-                );
4072
-            }
4073
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4074
-        } else {
4075
-            $operator = '=';
4076
-            $value = $op_and_value;
4077
-        }
4078
-        //check to see if the value is actually another field
4079
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4080
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4081
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4082
-            //in this case, the value should be an array, or at least a comma-separated list
4083
-            //it will need to handle a little differently
4084
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4085
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4086
-            return $operator . SP . $cleaned_value;
4087
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4088
-            //the value should be an array with count of two.
4089
-            if (count($value) !== 2) {
4090
-                throw new EE_Error(
4091
-                    sprintf(
4092
-                        __(
4093
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4094
-                            'event_espresso'
4095
-                        ),
4096
-                        "BETWEEN"
4097
-                    )
4098
-                );
4099
-            }
4100
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4101
-            return $operator . SP . $cleaned_value;
4102
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4103
-            if ($value !== null) {
4104
-                throw new EE_Error(
4105
-                    sprintf(
4106
-                        __(
4107
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4108
-                            "event_espresso"
4109
-                        ),
4110
-                        $value,
4111
-                        $operator
4112
-                    )
4113
-                );
4114
-            }
4115
-            return $operator;
4116
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4117
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4118
-            //remove other junk. So just treat it as a string.
4119
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4120
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4121
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4122
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4123
-            throw new EE_Error(
4124
-                sprintf(
4125
-                    __(
4126
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4127
-                        'event_espresso'
4128
-                    ),
4129
-                    $operator,
4130
-                    $operator
4131
-                )
4132
-            );
4133
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4134
-            throw new EE_Error(
4135
-                sprintf(
4136
-                    __(
4137
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4138
-                        'event_espresso'
4139
-                    ),
4140
-                    $operator,
4141
-                    $operator
4142
-                )
4143
-            );
4144
-        } else {
4145
-            throw new EE_Error(
4146
-                sprintf(
4147
-                    __(
4148
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4149
-                        "event_espresso"
4150
-                    ),
4151
-                    http_build_query($op_and_value)
4152
-                )
4153
-            );
4154
-        }
4155
-    }
4156
-
4157
-
4158
-
4159
-    /**
4160
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4161
-     *
4162
-     * @param array                      $values
4163
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4164
-     *                                              '%s'
4165
-     * @return string
4166
-     * @throws \EE_Error
4167
-     */
4168
-    public function _construct_between_value($values, $field_obj)
4169
-    {
4170
-        $cleaned_values = array();
4171
-        foreach ($values as $value) {
4172
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4173
-        }
4174
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4175
-    }
4176
-
4177
-
4178
-
4179
-    /**
4180
-     * Takes an array or a comma-separated list of $values and cleans them
4181
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4182
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4183
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4184
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4185
-     *
4186
-     * @param mixed                      $values    array or comma-separated string
4187
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4188
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4189
-     * @throws \EE_Error
4190
-     */
4191
-    public function _construct_in_value($values, $field_obj)
4192
-    {
4193
-        //check if the value is a CSV list
4194
-        if (is_string($values)) {
4195
-            //in which case, turn it into an array
4196
-            $values = explode(",", $values);
4197
-        }
4198
-        $cleaned_values = array();
4199
-        foreach ($values as $value) {
4200
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4201
-        }
4202
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4203
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4204
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4205
-        if (empty($cleaned_values)) {
4206
-            $all_fields = $this->field_settings();
4207
-            $a_field = array_shift($all_fields);
4208
-            $main_table = $this->_get_main_table();
4209
-            $cleaned_values[] = "SELECT "
4210
-                                . $a_field->get_table_column()
4211
-                                . " FROM "
4212
-                                . $main_table->get_table_name()
4213
-                                . " WHERE FALSE";
4214
-        }
4215
-        return "(" . implode(",", $cleaned_values) . ")";
4216
-    }
4217
-
4218
-
4219
-
4220
-    /**
4221
-     * @param mixed                      $value
4222
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4223
-     * @throws EE_Error
4224
-     * @return false|null|string
4225
-     */
4226
-    private function _wpdb_prepare_using_field($value, $field_obj)
4227
-    {
4228
-        /** @type WPDB $wpdb */
4229
-        global $wpdb;
4230
-        if ($field_obj instanceof EE_Model_Field_Base) {
4231
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4232
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4233
-        } else {//$field_obj should really just be a data type
4234
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4235
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4236
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4237
-            }
4238
-            return $wpdb->prepare($field_obj, $value);
4239
-        }
4240
-    }
4241
-
4242
-
4243
-
4244
-    /**
4245
-     * Takes the input parameter and finds the model field that it indicates.
4246
-     *
4247
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4248
-     * @throws EE_Error
4249
-     * @return EE_Model_Field_Base
4250
-     */
4251
-    protected function _deduce_field_from_query_param($query_param_name)
4252
-    {
4253
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4254
-        //which will help us find the database table and column
4255
-        $query_param_parts = explode(".", $query_param_name);
4256
-        if (empty($query_param_parts)) {
4257
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4258
-                'event_espresso'), $query_param_name));
4259
-        }
4260
-        $number_of_parts = count($query_param_parts);
4261
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4262
-        if ($number_of_parts === 1) {
4263
-            $field_name = $last_query_param_part;
4264
-            $model_obj = $this;
4265
-        } else {// $number_of_parts >= 2
4266
-            //the last part is the column name, and there are only 2parts. therefore...
4267
-            $field_name = $last_query_param_part;
4268
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4269
-        }
4270
-        try {
4271
-            return $model_obj->field_settings_for($field_name);
4272
-        } catch (EE_Error $e) {
4273
-            return null;
4274
-        }
4275
-    }
4276
-
4277
-
4278
-
4279
-    /**
4280
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4281
-     * alias and column which corresponds to it
4282
-     *
4283
-     * @param string $field_name
4284
-     * @throws EE_Error
4285
-     * @return string
4286
-     */
4287
-    public function _get_qualified_column_for_field($field_name)
4288
-    {
4289
-        $all_fields = $this->field_settings();
4290
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4291
-        if ($field) {
4292
-            return $field->get_qualified_column();
4293
-        } else {
4294
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4295
-                'event_espresso'), $field_name, get_class($this)));
4296
-        }
4297
-    }
4298
-
4299
-
4300
-
4301
-    /**
4302
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4303
-     * Example usage:
4304
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4305
-     *      array(),
4306
-     *      ARRAY_A,
4307
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4308
-     *  );
4309
-     * is equivalent to
4310
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4311
-     * and
4312
-     *  EEM_Event::instance()->get_all_wpdb_results(
4313
-     *      array(
4314
-     *          array(
4315
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4316
-     *          ),
4317
-     *          ARRAY_A,
4318
-     *          implode(
4319
-     *              ', ',
4320
-     *              array_merge(
4321
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4322
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4323
-     *              )
4324
-     *          )
4325
-     *      )
4326
-     *  );
4327
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4328
-     *
4329
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4330
-     *                                            and the one whose fields you are selecting for example: when querying
4331
-     *                                            tickets model and selecting fields from the tickets model you would
4332
-     *                                            leave this parameter empty, because no models are needed to join
4333
-     *                                            between the queried model and the selected one. Likewise when
4334
-     *                                            querying the datetime model and selecting fields from the tickets
4335
-     *                                            model, it would also be left empty, because there is a direct
4336
-     *                                            relation from datetimes to tickets, so no model is needed to join
4337
-     *                                            them together. However, when querying from the event model and
4338
-     *                                            selecting fields from the ticket model, you should provide the string
4339
-     *                                            'Datetime', indicating that the event model must first join to the
4340
-     *                                            datetime model in order to find its relation to ticket model.
4341
-     *                                            Also, when querying from the venue model and selecting fields from
4342
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4343
-     *                                            indicating you need to join the venue model to the event model,
4344
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4345
-     *                                            This string is used to deduce the prefix that gets added onto the
4346
-     *                                            models' tables qualified columns
4347
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4348
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4349
-     *                                            qualified column names
4350
-     * @return array|string
4351
-     */
4352
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4353
-    {
4354
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4355
-        $qualified_columns = array();
4356
-        foreach ($this->field_settings() as $field_name => $field) {
4357
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4358
-        }
4359
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4360
-    }
4361
-
4362
-
4363
-
4364
-    /**
4365
-     * constructs the select use on special limit joins
4366
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4367
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4368
-     * (as that is typically where the limits would be set).
4369
-     *
4370
-     * @param  string       $table_alias The table the select is being built for
4371
-     * @param  mixed|string $limit       The limit for this select
4372
-     * @return string                The final select join element for the query.
4373
-     */
4374
-    public function _construct_limit_join_select($table_alias, $limit)
4375
-    {
4376
-        $SQL = '';
4377
-        foreach ($this->_tables as $table_obj) {
4378
-            if ($table_obj instanceof EE_Primary_Table) {
4379
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4380
-                    ? $table_obj->get_select_join_limit($limit)
4381
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4382
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4383
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4384
-                    ? $table_obj->get_select_join_limit_join($limit)
4385
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4386
-            }
4387
-        }
4388
-        return $SQL;
4389
-    }
4390
-
4391
-
4392
-
4393
-    /**
4394
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4395
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4396
-     *
4397
-     * @return string SQL
4398
-     * @throws \EE_Error
4399
-     */
4400
-    public function _construct_internal_join()
4401
-    {
4402
-        $SQL = $this->_get_main_table()->get_table_sql();
4403
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4404
-        return $SQL;
4405
-    }
4406
-
4407
-
4408
-
4409
-    /**
4410
-     * Constructs the SQL for joining all the tables on this model.
4411
-     * Normally $alias should be the primary table's alias, but in cases where
4412
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4413
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4414
-     * alias, this will construct SQL like:
4415
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4416
-     * With $alias being a secondary table's alias, this will construct SQL like:
4417
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4418
-     *
4419
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4420
-     * @return string
4421
-     */
4422
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4423
-    {
4424
-        $SQL = '';
4425
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4426
-        foreach ($this->_tables as $table_obj) {
4427
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4428
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4429
-                    //so we're joining to this table, meaning the table is already in
4430
-                    //the FROM statement, BUT the primary table isn't. So we want
4431
-                    //to add the inverse join sql
4432
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4433
-                } else {
4434
-                    //just add a regular JOIN to this table from the primary table
4435
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4436
-                }
4437
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4438
-        }
4439
-        return $SQL;
4440
-    }
4441
-
4442
-
4443
-
4444
-    /**
4445
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4446
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4447
-     * their data type (eg, '%s', '%d', etc)
4448
-     *
4449
-     * @return array
4450
-     */
4451
-    public function _get_data_types()
4452
-    {
4453
-        $data_types = array();
4454
-        foreach ($this->field_settings() as $field_obj) {
4455
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4456
-            /** @var $field_obj EE_Model_Field_Base */
4457
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4458
-        }
4459
-        return $data_types;
4460
-    }
4461
-
4462
-
4463
-
4464
-    /**
4465
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4466
-     *
4467
-     * @param string $model_name
4468
-     * @throws EE_Error
4469
-     * @return EEM_Base
4470
-     */
4471
-    public function get_related_model_obj($model_name)
4472
-    {
4473
-        $model_classname = "EEM_" . $model_name;
4474
-        if (! class_exists($model_classname)) {
4475
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4476
-                'event_espresso'), $model_name, $model_classname));
4477
-        }
4478
-        return call_user_func($model_classname . "::instance");
4479
-    }
4480
-
4481
-
4482
-
4483
-    /**
4484
-     * Returns the array of EE_ModelRelations for this model.
4485
-     *
4486
-     * @return EE_Model_Relation_Base[]
4487
-     */
4488
-    public function relation_settings()
4489
-    {
4490
-        return $this->_model_relations;
4491
-    }
4492
-
4493
-
4494
-
4495
-    /**
4496
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4497
-     * because without THOSE models, this model probably doesn't have much purpose.
4498
-     * (Eg, without an event, datetimes have little purpose.)
4499
-     *
4500
-     * @return EE_Belongs_To_Relation[]
4501
-     */
4502
-    public function belongs_to_relations()
4503
-    {
4504
-        $belongs_to_relations = array();
4505
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4506
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4507
-                $belongs_to_relations[$model_name] = $relation_obj;
4508
-            }
4509
-        }
4510
-        return $belongs_to_relations;
4511
-    }
4512
-
4513
-
4514
-
4515
-    /**
4516
-     * Returns the specified EE_Model_Relation, or throws an exception
4517
-     *
4518
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4519
-     * @throws EE_Error
4520
-     * @return EE_Model_Relation_Base
4521
-     */
4522
-    public function related_settings_for($relation_name)
4523
-    {
4524
-        $relatedModels = $this->relation_settings();
4525
-        if (! array_key_exists($relation_name, $relatedModels)) {
4526
-            throw new EE_Error(
4527
-                sprintf(
4528
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4529
-                        'event_espresso'),
4530
-                    $relation_name,
4531
-                    $this->_get_class_name(),
4532
-                    implode(', ', array_keys($relatedModels))
4533
-                )
4534
-            );
4535
-        }
4536
-        return $relatedModels[$relation_name];
4537
-    }
4538
-
4539
-
4540
-
4541
-    /**
4542
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4543
-     * fields
4544
-     *
4545
-     * @param string $fieldName
4546
-     * @throws EE_Error
4547
-     * @return EE_Model_Field_Base
4548
-     */
4549
-    public function field_settings_for($fieldName)
4550
-    {
4551
-        $fieldSettings = $this->field_settings(true);
4552
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4553
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4554
-                get_class($this)));
4555
-        }
4556
-        return $fieldSettings[$fieldName];
4557
-    }
4558
-
4559
-
4560
-
4561
-    /**
4562
-     * Checks if this field exists on this model
4563
-     *
4564
-     * @param string $fieldName a key in the model's _field_settings array
4565
-     * @return boolean
4566
-     */
4567
-    public function has_field($fieldName)
4568
-    {
4569
-        $fieldSettings = $this->field_settings(true);
4570
-        if (isset($fieldSettings[$fieldName])) {
4571
-            return true;
4572
-        } else {
4573
-            return false;
4574
-        }
4575
-    }
4576
-
4577
-
4578
-
4579
-    /**
4580
-     * Returns whether or not this model has a relation to the specified model
4581
-     *
4582
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4583
-     * @return boolean
4584
-     */
4585
-    public function has_relation($relation_name)
4586
-    {
4587
-        $relations = $this->relation_settings();
4588
-        if (isset($relations[$relation_name])) {
4589
-            return true;
4590
-        } else {
4591
-            return false;
4592
-        }
4593
-    }
4594
-
4595
-
4596
-
4597
-    /**
4598
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4599
-     * Eg, on EE_Answer that would be ANS_ID field object
4600
-     *
4601
-     * @param $field_obj
4602
-     * @return boolean
4603
-     */
4604
-    public function is_primary_key_field($field_obj)
4605
-    {
4606
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4607
-    }
4608
-
4609
-
4610
-
4611
-    /**
4612
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4613
-     * Eg, on EE_Answer that would be ANS_ID field object
4614
-     *
4615
-     * @return EE_Model_Field_Base
4616
-     * @throws EE_Error
4617
-     */
4618
-    public function get_primary_key_field()
4619
-    {
4620
-        if ($this->_primary_key_field === null) {
4621
-            foreach ($this->field_settings(true) as $field_obj) {
4622
-                if ($this->is_primary_key_field($field_obj)) {
4623
-                    $this->_primary_key_field = $field_obj;
4624
-                    break;
4625
-                }
4626
-            }
4627
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4628
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4629
-                    get_class($this)));
4630
-            }
4631
-        }
4632
-        return $this->_primary_key_field;
4633
-    }
4634
-
4635
-
4636
-
4637
-    /**
4638
-     * Returns whether or not not there is a primary key on this model.
4639
-     * Internally does some caching.
4640
-     *
4641
-     * @return boolean
4642
-     */
4643
-    public function has_primary_key_field()
4644
-    {
4645
-        if ($this->_has_primary_key_field === null) {
4646
-            try {
4647
-                $this->get_primary_key_field();
4648
-                $this->_has_primary_key_field = true;
4649
-            } catch (EE_Error $e) {
4650
-                $this->_has_primary_key_field = false;
4651
-            }
4652
-        }
4653
-        return $this->_has_primary_key_field;
4654
-    }
4655
-
4656
-
4657
-
4658
-    /**
4659
-     * Finds the first field of type $field_class_name.
4660
-     *
4661
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4662
-     *                                 EE_Foreign_Key_Field, etc
4663
-     * @return EE_Model_Field_Base or null if none is found
4664
-     */
4665
-    public function get_a_field_of_type($field_class_name)
4666
-    {
4667
-        foreach ($this->field_settings() as $field) {
4668
-            if ($field instanceof $field_class_name) {
4669
-                return $field;
4670
-            }
4671
-        }
4672
-        return null;
4673
-    }
4674
-
4675
-
4676
-
4677
-    /**
4678
-     * Gets a foreign key field pointing to model.
4679
-     *
4680
-     * @param string $model_name eg Event, Registration, not EEM_Event
4681
-     * @return EE_Foreign_Key_Field_Base
4682
-     * @throws EE_Error
4683
-     */
4684
-    public function get_foreign_key_to($model_name)
4685
-    {
4686
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4687
-            foreach ($this->field_settings() as $field) {
4688
-                if (
4689
-                    $field instanceof EE_Foreign_Key_Field_Base
4690
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4691
-                ) {
4692
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4693
-                    break;
4694
-                }
4695
-            }
4696
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4697
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4698
-                    'event_espresso'), $model_name, get_class($this)));
4699
-            }
4700
-        }
4701
-        return $this->_cache_foreign_key_to_fields[$model_name];
4702
-    }
4703
-
4704
-
4705
-
4706
-    /**
4707
-     * Gets the actual table for the table alias
4708
-     *
4709
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4710
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4711
-     *                            Either one works
4712
-     * @return EE_Table_Base
4713
-     */
4714
-    public function get_table_for_alias($table_alias)
4715
-    {
4716
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4717
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4718
-    }
4719
-
4720
-
4721
-
4722
-    /**
4723
-     * Returns a flat array of all field son this model, instead of organizing them
4724
-     * by table_alias as they are in the constructor.
4725
-     *
4726
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4727
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4728
-     */
4729
-    public function field_settings($include_db_only_fields = false)
4730
-    {
4731
-        if ($include_db_only_fields) {
4732
-            if ($this->_cached_fields === null) {
4733
-                $this->_cached_fields = array();
4734
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4735
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4736
-                        $this->_cached_fields[$field_name] = $field_obj;
4737
-                    }
4738
-                }
4739
-            }
4740
-            return $this->_cached_fields;
4741
-        } else {
4742
-            if ($this->_cached_fields_non_db_only === null) {
4743
-                $this->_cached_fields_non_db_only = array();
4744
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4745
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4746
-                        /** @var $field_obj EE_Model_Field_Base */
4747
-                        if (! $field_obj->is_db_only_field()) {
4748
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4749
-                        }
4750
-                    }
4751
-                }
4752
-            }
4753
-            return $this->_cached_fields_non_db_only;
4754
-        }
4755
-    }
4756
-
4757
-
4758
-
4759
-    /**
4760
-     *        cycle though array of attendees and create objects out of each item
4761
-     *
4762
-     * @access        private
4763
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4764
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4765
-     *                           numerically indexed)
4766
-     * @throws \EE_Error
4767
-     */
4768
-    protected function _create_objects($rows = array())
4769
-    {
4770
-        $array_of_objects = array();
4771
-        if (empty($rows)) {
4772
-            return array();
4773
-        }
4774
-        $count_if_model_has_no_primary_key = 0;
4775
-        $has_primary_key = $this->has_primary_key_field();
4776
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4777
-        foreach ((array)$rows as $row) {
4778
-            if (empty($row)) {
4779
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4780
-                return array();
4781
-            }
4782
-            //check if we've already set this object in the results array,
4783
-            //in which case there's no need to process it further (again)
4784
-            if ($has_primary_key) {
4785
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4786
-                    $row,
4787
-                    $primary_key_field->get_qualified_column(),
4788
-                    $primary_key_field->get_table_column()
4789
-                );
4790
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4791
-                    continue;
4792
-                }
4793
-            }
4794
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4795
-            if (! $classInstance) {
4796
-                throw new EE_Error(
4797
-                    sprintf(
4798
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4799
-                        $this->get_this_model_name(),
4800
-                        http_build_query($row)
4801
-                    )
4802
-                );
4803
-            }
4804
-            //set the timezone on the instantiated objects
4805
-            $classInstance->set_timezone($this->_timezone);
4806
-            //make sure if there is any timezone setting present that we set the timezone for the object
4807
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4808
-            $array_of_objects[$key] = $classInstance;
4809
-            //also, for all the relations of type BelongsTo, see if we can cache
4810
-            //those related models
4811
-            //(we could do this for other relations too, but if there are conditions
4812
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4813
-            //so it requires a little more thought than just caching them immediately...)
4814
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4815
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4816
-                    //check if this model's INFO is present. If so, cache it on the model
4817
-                    $other_model = $relation_obj->get_other_model();
4818
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4819
-                    //if we managed to make a model object from the results, cache it on the main model object
4820
-                    if ($other_model_obj_maybe) {
4821
-                        //set timezone on these other model objects if they are present
4822
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4823
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4824
-                    }
4825
-                }
4826
-            }
4827
-        }
4828
-        return $array_of_objects;
4829
-    }
4830
-
4831
-
4832
-
4833
-    /**
4834
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4835
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4836
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4837
-     * object (as set in the model_field!).
4838
-     *
4839
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4840
-     */
4841
-    public function create_default_object()
4842
-    {
4843
-        $this_model_fields_and_values = array();
4844
-        //setup the row using default values;
4845
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4846
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4847
-        }
4848
-        $className = $this->_get_class_name();
4849
-        $classInstance = EE_Registry::instance()
4850
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4851
-        return $classInstance;
4852
-    }
4853
-
4854
-
4855
-
4856
-    /**
4857
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4858
-     *                             or an stdClass where each property is the name of a column,
4859
-     * @return EE_Base_Class
4860
-     * @throws \EE_Error
4861
-     */
4862
-    public function instantiate_class_from_array_or_object($cols_n_values)
4863
-    {
4864
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4865
-            $cols_n_values = get_object_vars($cols_n_values);
4866
-        }
4867
-        $primary_key = null;
4868
-        //make sure the array only has keys that are fields/columns on this model
4869
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4870
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4871
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4872
-        }
4873
-        $className = $this->_get_class_name();
4874
-        //check we actually found results that we can use to build our model object
4875
-        //if not, return null
4876
-        if ($this->has_primary_key_field()) {
4877
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4878
-                return null;
4879
-            }
4880
-        } else if ($this->unique_indexes()) {
4881
-            $first_column = reset($this_model_fields_n_values);
4882
-            if (empty($first_column)) {
4883
-                return null;
4884
-            }
4885
-        }
4886
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4887
-        if ($primary_key) {
4888
-            $classInstance = $this->get_from_entity_map($primary_key);
4889
-            if (! $classInstance) {
4890
-                $classInstance = EE_Registry::instance()
4891
-                                            ->load_class($className,
4892
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4893
-                // add this new object to the entity map
4894
-                $classInstance = $this->add_to_entity_map($classInstance);
4895
-            }
4896
-        } else {
4897
-            $classInstance = EE_Registry::instance()
4898
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4899
-                                            true, false);
4900
-        }
4901
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4902
-        $this->set_timezone($classInstance->get_timezone());
4903
-        return $classInstance;
4904
-    }
4905
-
4906
-
4907
-
4908
-    /**
4909
-     * Gets the model object from the  entity map if it exists
4910
-     *
4911
-     * @param int|string $id the ID of the model object
4912
-     * @return EE_Base_Class
4913
-     */
4914
-    public function get_from_entity_map($id)
4915
-    {
4916
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4917
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4918
-    }
4919
-
4920
-
4921
-
4922
-    /**
4923
-     * add_to_entity_map
4924
-     * Adds the object to the model's entity mappings
4925
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4926
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4927
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4928
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4929
-     *        then this method should be called immediately after the update query
4930
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4931
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4932
-     *
4933
-     * @param    EE_Base_Class $object
4934
-     * @throws EE_Error
4935
-     * @return \EE_Base_Class
4936
-     */
4937
-    public function add_to_entity_map(EE_Base_Class $object)
4938
-    {
4939
-        $className = $this->_get_class_name();
4940
-        if (! $object instanceof $className) {
4941
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4942
-                is_object($object) ? get_class($object) : $object, $className));
4943
-        }
4944
-        /** @var $object EE_Base_Class */
4945
-        if (! $object->ID()) {
4946
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4947
-                "event_espresso"), get_class($this)));
4948
-        }
4949
-        // double check it's not already there
4950
-        $classInstance = $this->get_from_entity_map($object->ID());
4951
-        if ($classInstance) {
4952
-            return $classInstance;
4953
-        } else {
4954
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4955
-            return $object;
4956
-        }
4957
-    }
4958
-
4959
-
4960
-
4961
-    /**
4962
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4963
-     * if no identifier is provided, then the entire entity map is emptied
4964
-     *
4965
-     * @param int|string $id the ID of the model object
4966
-     * @return boolean
4967
-     */
4968
-    public function clear_entity_map($id = null)
4969
-    {
4970
-        if (empty($id)) {
4971
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4972
-            return true;
4973
-        }
4974
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4975
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4976
-            return true;
4977
-        }
4978
-        return false;
4979
-    }
4980
-
4981
-
4982
-
4983
-    /**
4984
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4985
-     * Given an array where keys are column (or column alias) names and values,
4986
-     * returns an array of their corresponding field names and database values
4987
-     *
4988
-     * @param array $cols_n_values
4989
-     * @return array
4990
-     */
4991
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4992
-    {
4993
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4994
-    }
4995
-
4996
-
4997
-
4998
-    /**
4999
-     * _deduce_fields_n_values_from_cols_n_values
5000
-     * Given an array where keys are column (or column alias) names and values,
5001
-     * returns an array of their corresponding field names and database values
5002
-     *
5003
-     * @param string $cols_n_values
5004
-     * @return array
5005
-     */
5006
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5007
-    {
5008
-        $this_model_fields_n_values = array();
5009
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5010
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5011
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5012
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5013
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5014
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5015
-                    if (! $field_obj->is_db_only_field()) {
5016
-                        //prepare field as if its coming from db
5017
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5018
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5019
-                    }
5020
-                }
5021
-            } else {
5022
-                //the table's rows existed. Use their values
5023
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5024
-                    if (! $field_obj->is_db_only_field()) {
5025
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5026
-                            $cols_n_values, $field_obj->get_qualified_column(),
5027
-                            $field_obj->get_table_column()
5028
-                        );
5029
-                    }
5030
-                }
5031
-            }
5032
-        }
5033
-        return $this_model_fields_n_values;
5034
-    }
5035
-
5036
-
5037
-
5038
-    /**
5039
-     * @param $cols_n_values
5040
-     * @param $qualified_column
5041
-     * @param $regular_column
5042
-     * @return null
5043
-     */
5044
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5045
-    {
5046
-        $value = null;
5047
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5048
-        //does the field on the model relate to this column retrieved from the db?
5049
-        //or is it a db-only field? (not relating to the model)
5050
-        if (isset($cols_n_values[$qualified_column])) {
5051
-            $value = $cols_n_values[$qualified_column];
5052
-        } elseif (isset($cols_n_values[$regular_column])) {
5053
-            $value = $cols_n_values[$regular_column];
5054
-        }
5055
-        return $value;
5056
-    }
5057
-
5058
-
5059
-
5060
-    /**
5061
-     * refresh_entity_map_from_db
5062
-     * Makes sure the model object in the entity map at $id assumes the values
5063
-     * of the database (opposite of EE_base_Class::save())
5064
-     *
5065
-     * @param int|string $id
5066
-     * @return EE_Base_Class
5067
-     * @throws \EE_Error
5068
-     */
5069
-    public function refresh_entity_map_from_db($id)
5070
-    {
5071
-        $obj_in_map = $this->get_from_entity_map($id);
5072
-        if ($obj_in_map) {
5073
-            $wpdb_results = $this->_get_all_wpdb_results(
5074
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5075
-            );
5076
-            if ($wpdb_results && is_array($wpdb_results)) {
5077
-                $one_row = reset($wpdb_results);
5078
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5079
-                    $obj_in_map->set_from_db($field_name, $db_value);
5080
-                }
5081
-                //clear the cache of related model objects
5082
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5083
-                    $obj_in_map->clear_cache($relation_name, null, true);
5084
-                }
5085
-            }
5086
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5087
-            return $obj_in_map;
5088
-        } else {
5089
-            return $this->get_one_by_ID($id);
5090
-        }
5091
-    }
5092
-
5093
-
5094
-
5095
-    /**
5096
-     * refresh_entity_map_with
5097
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5098
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5099
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5100
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5101
-     *
5102
-     * @param int|string    $id
5103
-     * @param EE_Base_Class $replacing_model_obj
5104
-     * @return \EE_Base_Class
5105
-     * @throws \EE_Error
5106
-     */
5107
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5108
-    {
5109
-        $obj_in_map = $this->get_from_entity_map($id);
5110
-        if ($obj_in_map) {
5111
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5112
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5113
-                    $obj_in_map->set($field_name, $value);
5114
-                }
5115
-                //make the model object in the entity map's cache match the $replacing_model_obj
5116
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5117
-                    $obj_in_map->clear_cache($relation_name, null, true);
5118
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5119
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5120
-                    }
5121
-                }
5122
-            }
5123
-            return $obj_in_map;
5124
-        } else {
5125
-            $this->add_to_entity_map($replacing_model_obj);
5126
-            return $replacing_model_obj;
5127
-        }
5128
-    }
5129
-
5130
-
5131
-
5132
-    /**
5133
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5134
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5135
-     * require_once($this->_getClassName().".class.php");
5136
-     *
5137
-     * @return string
5138
-     */
5139
-    private function _get_class_name()
5140
-    {
5141
-        return "EE_" . $this->get_this_model_name();
5142
-    }
5143
-
5144
-
5145
-
5146
-    /**
5147
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5148
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5149
-     * it would be 'Events'.
5150
-     *
5151
-     * @param int $quantity
5152
-     * @return string
5153
-     */
5154
-    public function item_name($quantity = 1)
5155
-    {
5156
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5157
-    }
5158
-
5159
-
5160
-
5161
-    /**
5162
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5163
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5164
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5165
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5166
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5167
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5168
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5169
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5170
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5171
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5172
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5173
-     *        return $previousReturnValue.$returnString;
5174
-     * }
5175
-     * require('EEM_Answer.model.php');
5176
-     * $answer=EEM_Answer::instance();
5177
-     * echo $answer->my_callback('monkeys',100);
5178
-     * //will output "you called my_callback! and passed args:monkeys,100"
5179
-     *
5180
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5181
-     * @param array  $args       array of original arguments passed to the function
5182
-     * @throws EE_Error
5183
-     * @return mixed whatever the plugin which calls add_filter decides
5184
-     */
5185
-    public function __call($methodName, $args)
5186
-    {
5187
-        $className = get_class($this);
5188
-        $tagName = "FHEE__{$className}__{$methodName}";
5189
-        if (! has_filter($tagName)) {
5190
-            throw new EE_Error(
5191
-                sprintf(
5192
-                    __('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 );',
5193
-                        'event_espresso'),
5194
-                    $methodName,
5195
-                    $className,
5196
-                    $tagName,
5197
-                    '<br />'
5198
-                )
5199
-            );
5200
-        }
5201
-        return apply_filters($tagName, null, $this, $args);
5202
-    }
5203
-
5204
-
5205
-
5206
-    /**
5207
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5208
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5209
-     *
5210
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5211
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5212
-     *                                                       the object's class name
5213
-     *                                                       or object's ID
5214
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5215
-     *                                                       exists in the database. If it does not, we add it
5216
-     * @throws EE_Error
5217
-     * @return EE_Base_Class
5218
-     */
5219
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5220
-    {
5221
-        $className = $this->_get_class_name();
5222
-        if ($base_class_obj_or_id instanceof $className) {
5223
-            $model_object = $base_class_obj_or_id;
5224
-        } else {
5225
-            $primary_key_field = $this->get_primary_key_field();
5226
-            if (
5227
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5228
-                && (
5229
-                    is_int($base_class_obj_or_id)
5230
-                    || is_string($base_class_obj_or_id)
5231
-                )
5232
-            ) {
5233
-                // assume it's an ID.
5234
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5235
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5236
-            } else if (
5237
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5238
-                && is_string($base_class_obj_or_id)
5239
-            ) {
5240
-                // assume its a string representation of the object
5241
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5242
-            } else {
5243
-                throw new EE_Error(
5244
-                    sprintf(
5245
-                        __(
5246
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5247
-                            'event_espresso'
5248
-                        ),
5249
-                        $base_class_obj_or_id,
5250
-                        $this->_get_class_name(),
5251
-                        print_r($base_class_obj_or_id, true)
5252
-                    )
5253
-                );
5254
-            }
5255
-        }
5256
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5257
-            $model_object->save();
5258
-        }
5259
-        return $model_object;
5260
-    }
5261
-
5262
-
5263
-
5264
-    /**
5265
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5266
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5267
-     * returns it ID.
5268
-     *
5269
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5270
-     * @return int|string depending on the type of this model object's ID
5271
-     * @throws EE_Error
5272
-     */
5273
-    public function ensure_is_ID($base_class_obj_or_id)
5274
-    {
5275
-        $className = $this->_get_class_name();
5276
-        if ($base_class_obj_or_id instanceof $className) {
5277
-            /** @var $base_class_obj_or_id EE_Base_Class */
5278
-            $id = $base_class_obj_or_id->ID();
5279
-        } elseif (is_int($base_class_obj_or_id)) {
5280
-            //assume it's an ID
5281
-            $id = $base_class_obj_or_id;
5282
-        } elseif (is_string($base_class_obj_or_id)) {
5283
-            //assume its a string representation of the object
5284
-            $id = $base_class_obj_or_id;
5285
-        } else {
5286
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5287
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5288
-                print_r($base_class_obj_or_id, true)));
5289
-        }
5290
-        return $id;
5291
-    }
5292
-
5293
-
5294
-
5295
-    /**
5296
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5297
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5298
-     * been sanitized and converted into the appropriate domain.
5299
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5300
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5301
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5302
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5303
-     * $EVT = EEM_Event::instance(); $old_setting =
5304
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5305
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5306
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5307
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5308
-     *
5309
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5310
-     * @return void
5311
-     */
5312
-    public function assume_values_already_prepared_by_model_object(
5313
-        $values_already_prepared = self::not_prepared_by_model_object
5314
-    ) {
5315
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5316
-    }
5317
-
5318
-
5319
-
5320
-    /**
5321
-     * Read comments for assume_values_already_prepared_by_model_object()
5322
-     *
5323
-     * @return int
5324
-     */
5325
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5326
-    {
5327
-        return $this->_values_already_prepared_by_model_object;
5328
-    }
5329
-
5330
-
5331
-
5332
-    /**
5333
-     * Gets all the indexes on this model
5334
-     *
5335
-     * @return EE_Index[]
5336
-     */
5337
-    public function indexes()
5338
-    {
5339
-        return $this->_indexes;
5340
-    }
5341
-
5342
-
5343
-
5344
-    /**
5345
-     * Gets all the Unique Indexes on this model
5346
-     *
5347
-     * @return EE_Unique_Index[]
5348
-     */
5349
-    public function unique_indexes()
5350
-    {
5351
-        $unique_indexes = array();
5352
-        foreach ($this->_indexes as $name => $index) {
5353
-            if ($index instanceof EE_Unique_Index) {
5354
-                $unique_indexes [$name] = $index;
5355
-            }
5356
-        }
5357
-        return $unique_indexes;
5358
-    }
5359
-
5360
-
5361
-
5362
-    /**
5363
-     * Gets all the fields which, when combined, make the primary key.
5364
-     * This is usually just an array with 1 element (the primary key), but in cases
5365
-     * where there is no primary key, it's a combination of fields as defined
5366
-     * on a primary index
5367
-     *
5368
-     * @return EE_Model_Field_Base[] indexed by the field's name
5369
-     * @throws \EE_Error
5370
-     */
5371
-    public function get_combined_primary_key_fields()
5372
-    {
5373
-        foreach ($this->indexes() as $index) {
5374
-            if ($index instanceof EE_Primary_Key_Index) {
5375
-                return $index->fields();
5376
-            }
5377
-        }
5378
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5379
-    }
5380
-
5381
-
5382
-
5383
-    /**
5384
-     * Used to build a primary key string (when the model has no primary key),
5385
-     * which can be used a unique string to identify this model object.
5386
-     *
5387
-     * @param array $cols_n_values keys are field names, values are their values
5388
-     * @return string
5389
-     * @throws \EE_Error
5390
-     */
5391
-    public function get_index_primary_key_string($cols_n_values)
5392
-    {
5393
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5394
-            $this->get_combined_primary_key_fields());
5395
-        return http_build_query($cols_n_values_for_primary_key_index);
5396
-    }
5397
-
5398
-
5399
-
5400
-    /**
5401
-     * Gets the field values from the primary key string
5402
-     *
5403
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5404
-     * @param string $index_primary_key_string
5405
-     * @return null|array
5406
-     * @throws \EE_Error
5407
-     */
5408
-    public function parse_index_primary_key_string($index_primary_key_string)
5409
-    {
5410
-        $key_fields = $this->get_combined_primary_key_fields();
5411
-        //check all of them are in the $id
5412
-        $key_vals_in_combined_pk = array();
5413
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5414
-        foreach ($key_fields as $key_field_name => $field_obj) {
5415
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5416
-                return null;
5417
-            }
5418
-        }
5419
-        return $key_vals_in_combined_pk;
5420
-    }
5421
-
5422
-
5423
-
5424
-    /**
5425
-     * verifies that an array of key-value pairs for model fields has a key
5426
-     * for each field comprising the primary key index
5427
-     *
5428
-     * @param array $key_vals
5429
-     * @return boolean
5430
-     * @throws \EE_Error
5431
-     */
5432
-    public function has_all_combined_primary_key_fields($key_vals)
5433
-    {
5434
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5435
-        foreach ($keys_it_should_have as $key) {
5436
-            if (! isset($key_vals[$key])) {
5437
-                return false;
5438
-            }
5439
-        }
5440
-        return true;
5441
-    }
5442
-
5443
-
5444
-
5445
-    /**
5446
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5447
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5448
-     *
5449
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5450
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5451
-     * @throws EE_Error
5452
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5453
-     *                                                              indexed)
5454
-     */
5455
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5456
-    {
5457
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5458
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5459
-        } elseif (is_array($model_object_or_attributes_array)) {
5460
-            $attributes_array = $model_object_or_attributes_array;
5461
-        } else {
5462
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5463
-                "event_espresso"), $model_object_or_attributes_array));
5464
-        }
5465
-        //even copies obviously won't have the same ID, so remove the primary key
5466
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5467
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5468
-            unset($attributes_array[$this->primary_key_name()]);
5469
-        }
5470
-        if (isset($query_params[0])) {
5471
-            $query_params[0] = array_merge($attributes_array, $query_params);
5472
-        } else {
5473
-            $query_params[0] = $attributes_array;
5474
-        }
5475
-        return $this->get_all($query_params);
5476
-    }
5477
-
5478
-
5479
-
5480
-    /**
5481
-     * Gets the first copy we find. See get_all_copies for more details
5482
-     *
5483
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5484
-     * @param array $query_params
5485
-     * @return EE_Base_Class
5486
-     * @throws \EE_Error
5487
-     */
5488
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5489
-    {
5490
-        if (! is_array($query_params)) {
5491
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5492
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5493
-                    gettype($query_params)), '4.6.0');
5494
-            $query_params = array();
5495
-        }
5496
-        $query_params['limit'] = 1;
5497
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5498
-        if (is_array($copies)) {
5499
-            return array_shift($copies);
5500
-        } else {
5501
-            return null;
5502
-        }
5503
-    }
5504
-
5505
-
5506
-
5507
-    /**
5508
-     * Updates the item with the specified id. Ignores default query parameters because
5509
-     * we have specified the ID, and its assumed we KNOW what we're doing
5510
-     *
5511
-     * @param array      $fields_n_values keys are field names, values are their new values
5512
-     * @param int|string $id              the value of the primary key to update
5513
-     * @return int number of rows updated
5514
-     * @throws \EE_Error
5515
-     */
5516
-    public function update_by_ID($fields_n_values, $id)
5517
-    {
5518
-        $query_params = array(
5519
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5520
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5521
-        );
5522
-        return $this->update($fields_n_values, $query_params);
5523
-    }
5524
-
5525
-
5526
-
5527
-    /**
5528
-     * Changes an operator which was supplied to the models into one usable in SQL
5529
-     *
5530
-     * @param string $operator_supplied
5531
-     * @return string an operator which can be used in SQL
5532
-     * @throws EE_Error
5533
-     */
5534
-    private function _prepare_operator_for_sql($operator_supplied)
5535
-    {
5536
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5537
-            : null;
5538
-        if ($sql_operator) {
5539
-            return $sql_operator;
5540
-        } else {
5541
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5542
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5543
-        }
5544
-    }
5545
-
5546
-
5547
-
5548
-    /**
5549
-     * Gets an array where keys are the primary keys and values are their 'names'
5550
-     * (as determined by the model object's name() function, which is often overridden)
5551
-     *
5552
-     * @param array $query_params like get_all's
5553
-     * @return string[]
5554
-     * @throws \EE_Error
5555
-     */
5556
-    public function get_all_names($query_params = array())
5557
-    {
5558
-        $objs = $this->get_all($query_params);
5559
-        $names = array();
5560
-        foreach ($objs as $obj) {
5561
-            $names[$obj->ID()] = $obj->name();
5562
-        }
5563
-        return $names;
5564
-    }
5565
-
5566
-
5567
-
5568
-    /**
5569
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5570
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5571
-     * this is duplicated effort and reduces efficiency) you would be better to use
5572
-     * array_keys() on $model_objects.
5573
-     *
5574
-     * @param \EE_Base_Class[] $model_objects
5575
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5576
-     *                                               in the returned array
5577
-     * @return array
5578
-     * @throws \EE_Error
5579
-     */
5580
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5581
-    {
5582
-        if (! $this->has_primary_key_field()) {
5583
-            if (WP_DEBUG) {
5584
-                EE_Error::add_error(
5585
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5586
-                    __FILE__,
5587
-                    __FUNCTION__,
5588
-                    __LINE__
5589
-                );
5590
-            }
5591
-        }
5592
-        $IDs = array();
5593
-        foreach ($model_objects as $model_object) {
5594
-            $id = $model_object->ID();
5595
-            if (! $id) {
5596
-                if ($filter_out_empty_ids) {
5597
-                    continue;
5598
-                }
5599
-                if (WP_DEBUG) {
5600
-                    EE_Error::add_error(
5601
-                        __(
5602
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5603
-                            'event_espresso'
5604
-                        ),
5605
-                        __FILE__,
5606
-                        __FUNCTION__,
5607
-                        __LINE__
5608
-                    );
5609
-                }
5610
-            }
5611
-            $IDs[] = $id;
5612
-        }
5613
-        return $IDs;
5614
-    }
5615
-
5616
-
5617
-
5618
-    /**
5619
-     * Returns the string used in capabilities relating to this model. If there
5620
-     * are no capabilities that relate to this model returns false
5621
-     *
5622
-     * @return string|false
5623
-     */
5624
-    public function cap_slug()
5625
-    {
5626
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5627
-    }
5628
-
5629
-
5630
-
5631
-    /**
5632
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5633
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5634
-     * only returns the cap restrictions array in that context (ie, the array
5635
-     * at that key)
5636
-     *
5637
-     * @param string $context
5638
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5639
-     * @throws \EE_Error
5640
-     */
5641
-    public function cap_restrictions($context = EEM_Base::caps_read)
5642
-    {
5643
-        EEM_Base::verify_is_valid_cap_context($context);
5644
-        //check if we ought to run the restriction generator first
5645
-        if (
5646
-            isset($this->_cap_restriction_generators[$context])
5647
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5648
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5649
-        ) {
5650
-            $this->_cap_restrictions[$context] = array_merge(
5651
-                $this->_cap_restrictions[$context],
5652
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5653
-            );
5654
-        }
5655
-        //and make sure we've finalized the construction of each restriction
5656
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5657
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5658
-                $where_conditions_obj->_finalize_construct($this);
5659
-            }
5660
-        }
5661
-        return $this->_cap_restrictions[$context];
5662
-    }
5663
-
5664
-
5665
-
5666
-    /**
5667
-     * Indicating whether or not this model thinks its a wp core model
5668
-     *
5669
-     * @return boolean
5670
-     */
5671
-    public function is_wp_core_model()
5672
-    {
5673
-        return $this->_wp_core_model;
5674
-    }
5675
-
5676
-
5677
-
5678
-    /**
5679
-     * Gets all the caps that are missing which impose a restriction on
5680
-     * queries made in this context
5681
-     *
5682
-     * @param string $context one of EEM_Base::caps_ constants
5683
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5684
-     * @throws \EE_Error
5685
-     */
5686
-    public function caps_missing($context = EEM_Base::caps_read)
5687
-    {
5688
-        $missing_caps = array();
5689
-        $cap_restrictions = $this->cap_restrictions($context);
5690
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5691
-            if (! EE_Capabilities::instance()
5692
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5693
-            ) {
5694
-                $missing_caps[$cap] = $restriction_if_no_cap;
5695
-            }
5696
-        }
5697
-        return $missing_caps;
5698
-    }
5699
-
5700
-
5701
-
5702
-    /**
5703
-     * Gets the mapping from capability contexts to action strings used in capability names
5704
-     *
5705
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5706
-     * one of 'read', 'edit', or 'delete'
5707
-     */
5708
-    public function cap_contexts_to_cap_action_map()
5709
-    {
5710
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5711
-            $this);
5712
-    }
5713
-
5714
-
5715
-
5716
-    /**
5717
-     * Gets the action string for the specified capability context
5718
-     *
5719
-     * @param string $context
5720
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5721
-     * @throws \EE_Error
5722
-     */
5723
-    public function cap_action_for_context($context)
5724
-    {
5725
-        $mapping = $this->cap_contexts_to_cap_action_map();
5726
-        if (isset($mapping[$context])) {
5727
-            return $mapping[$context];
5728
-        }
5729
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5730
-            return $action;
5731
-        }
5732
-        throw new EE_Error(
5733
-            sprintf(
5734
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5735
-                $context,
5736
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5737
-            )
5738
-        );
5739
-    }
5740
-
5741
-
5742
-
5743
-    /**
5744
-     * Returns all the capability contexts which are valid when querying models
5745
-     *
5746
-     * @return array
5747
-     */
5748
-    public static function valid_cap_contexts()
5749
-    {
5750
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5751
-            self::caps_read,
5752
-            self::caps_read_admin,
5753
-            self::caps_edit,
5754
-            self::caps_delete,
5755
-        ));
5756
-    }
5757
-
5758
-
5759
-
5760
-    /**
5761
-     * Returns all valid options for 'default_where_conditions'
5762
-     *
5763
-     * @return array
5764
-     */
5765
-    public static function valid_default_where_conditions()
5766
-    {
5767
-        return array(
5768
-            EEM_Base::default_where_conditions_all,
5769
-            EEM_Base::default_where_conditions_this_only,
5770
-            EEM_Base::default_where_conditions_others_only,
5771
-            EEM_Base::default_where_conditions_minimum_all,
5772
-            EEM_Base::default_where_conditions_minimum_others,
5773
-            EEM_Base::default_where_conditions_none
5774
-        );
5775
-    }
5776
-
5777
-    // public static function default_where_conditions_full
5778
-    /**
5779
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5780
-     *
5781
-     * @param string $context
5782
-     * @return bool
5783
-     * @throws \EE_Error
5784
-     */
5785
-    static public function verify_is_valid_cap_context($context)
5786
-    {
5787
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5788
-        if (in_array($context, $valid_cap_contexts)) {
5789
-            return true;
5790
-        } else {
5791
-            throw new EE_Error(
5792
-                sprintf(
5793
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5794
-                        'event_espresso'),
5795
-                    $context,
5796
-                    'EEM_Base',
5797
-                    implode(',', $valid_cap_contexts)
5798
-                )
5799
-            );
5800
-        }
5801
-    }
5802
-
5803
-
5804
-
5805
-    /**
5806
-     * Clears all the models field caches. This is only useful when a sub-class
5807
-     * might have added a field or something and these caches might be invalidated
5808
-     */
5809
-    protected function _invalidate_field_caches()
5810
-    {
5811
-        $this->_cache_foreign_key_to_fields = array();
5812
-        $this->_cached_fields = null;
5813
-        $this->_cached_fields_non_db_only = null;
5814
-    }
5815
-
5816
-
5817
-
5818
-    /**
5819
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5820
-     * (eg "and", "or", "not").
5821
-     *
5822
-     * @return array
5823
-     */
5824
-    public function logic_query_param_keys()
5825
-    {
5826
-        return $this->_logic_query_param_keys;
5827
-    }
5828
-
5829
-
5830
-
5831
-    /**
5832
-     * Determines whether or not the where query param array key is for a logic query param.
5833
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5834
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5835
-     *
5836
-     * @param $query_param_key
5837
-     * @return bool
5838
-     */
5839
-    public function is_logic_query_param_key($query_param_key)
5840
-    {
5841
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5842
-            if ($query_param_key === $logic_query_param_key
5843
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5844
-            ) {
5845
-                return true;
5846
-            }
5847
-        }
5848
-        return false;
5849
-    }
3609
+		}
3610
+		return $null_friendly_where_conditions;
3611
+	}
3612
+
3613
+
3614
+
3615
+	/**
3616
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3617
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3618
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3619
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3620
+	 *
3621
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3622
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3623
+	 */
3624
+	private function _get_default_where_conditions($model_relation_path = null)
3625
+	{
3626
+		if ($this->_ignore_where_strategy) {
3627
+			return array();
3628
+		}
3629
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3630
+	}
3631
+
3632
+
3633
+
3634
+	/**
3635
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3636
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3637
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3638
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3639
+	 * Similar to _get_default_where_conditions
3640
+	 *
3641
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3642
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3643
+	 */
3644
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3645
+	{
3646
+		if ($this->_ignore_where_strategy) {
3647
+			return array();
3648
+		}
3649
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3650
+	}
3651
+
3652
+
3653
+
3654
+	/**
3655
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3656
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3657
+	 *
3658
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3659
+	 * @return string
3660
+	 * @throws \EE_Error
3661
+	 */
3662
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3663
+	{
3664
+		$selects = $this->_get_columns_to_select_for_this_model();
3665
+		foreach (
3666
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3667
+			$name_of_other_model_included
3668
+		) {
3669
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3670
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3671
+			foreach ($other_model_selects as $key => $value) {
3672
+				$selects[] = $value;
3673
+			}
3674
+		}
3675
+		return implode(", ", $selects);
3676
+	}
3677
+
3678
+
3679
+
3680
+	/**
3681
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3682
+	 * So that's going to be the columns for all the fields on the model
3683
+	 *
3684
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3685
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3686
+	 */
3687
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3688
+	{
3689
+		$fields = $this->field_settings();
3690
+		$selects = array();
3691
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3692
+			$this->get_this_model_name());
3693
+		foreach ($fields as $field_obj) {
3694
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3695
+						 . $field_obj->get_table_alias()
3696
+						 . "."
3697
+						 . $field_obj->get_table_column()
3698
+						 . " AS '"
3699
+						 . $table_alias_with_model_relation_chain_prefix
3700
+						 . $field_obj->get_table_alias()
3701
+						 . "."
3702
+						 . $field_obj->get_table_column()
3703
+						 . "'";
3704
+		}
3705
+		//make sure we are also getting the PKs of each table
3706
+		$tables = $this->get_tables();
3707
+		if (count($tables) > 1) {
3708
+			foreach ($tables as $table_obj) {
3709
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3710
+									   . $table_obj->get_fully_qualified_pk_column();
3711
+				if (! in_array($qualified_pk_column, $selects)) {
3712
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3713
+				}
3714
+			}
3715
+		}
3716
+		return $selects;
3717
+	}
3718
+
3719
+
3720
+
3721
+	/**
3722
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3723
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3724
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3725
+	 * SQL for joining, and the data types
3726
+	 *
3727
+	 * @param null|string                 $original_query_param
3728
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3729
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3730
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3731
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3732
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3733
+	 *                                                          or 'Registration's
3734
+	 * @param string                      $original_query_param what it originally was (eg
3735
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3736
+	 *                                                          matches $query_param
3737
+	 * @throws EE_Error
3738
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3739
+	 */
3740
+	private function _extract_related_model_info_from_query_param(
3741
+		$query_param,
3742
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3743
+		$query_param_type,
3744
+		$original_query_param = null
3745
+	) {
3746
+		if ($original_query_param === null) {
3747
+			$original_query_param = $query_param;
3748
+		}
3749
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3750
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3751
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3752
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3753
+		//check to see if we have a field on this model
3754
+		$this_model_fields = $this->field_settings(true);
3755
+		if (array_key_exists($query_param, $this_model_fields)) {
3756
+			if ($allow_fields) {
3757
+				return;
3758
+			} else {
3759
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3760
+					"event_espresso"),
3761
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3762
+			}
3763
+		} //check if this is a special logic query param
3764
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3765
+			if ($allow_logic_query_params) {
3766
+				return;
3767
+			} else {
3768
+				throw new EE_Error(
3769
+					sprintf(
3770
+						__('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',
3771
+							'event_espresso'),
3772
+						implode('", "', $this->_logic_query_param_keys),
3773
+						$query_param,
3774
+						get_class($this),
3775
+						'<br />',
3776
+						"\t"
3777
+						. ' $passed_in_query_info = <pre>'
3778
+						. print_r($passed_in_query_info, true)
3779
+						. '</pre>'
3780
+						. "\n\t"
3781
+						. ' $query_param_type = '
3782
+						. $query_param_type
3783
+						. "\n\t"
3784
+						. ' $original_query_param = '
3785
+						. $original_query_param
3786
+					)
3787
+				);
3788
+			}
3789
+		} //check if it's a custom selection
3790
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3791
+			return;
3792
+		}
3793
+		//check if has a model name at the beginning
3794
+		//and
3795
+		//check if it's a field on a related model
3796
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3797
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3798
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3799
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3800
+				if ($query_param === '') {
3801
+					//nothing left to $query_param
3802
+					//we should actually end in a field name, not a model like this!
3803
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3804
+						"event_espresso"),
3805
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3806
+				} else {
3807
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3808
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3809
+						$passed_in_query_info, $query_param_type, $original_query_param);
3810
+					return;
3811
+				}
3812
+			} elseif ($query_param === $valid_related_model_name) {
3813
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3814
+				return;
3815
+			}
3816
+		}
3817
+		//ok so $query_param didn't start with a model name
3818
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3819
+		//it's wack, that's what it is
3820
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3821
+			"event_espresso"),
3822
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3823
+	}
3824
+
3825
+
3826
+
3827
+	/**
3828
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3829
+	 * and store it on $passed_in_query_info
3830
+	 *
3831
+	 * @param string                      $model_name
3832
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3833
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3834
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3835
+	 *                                                          and are adding a join to 'Payment' with the original
3836
+	 *                                                          query param key
3837
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3838
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3839
+	 *                                                          Payment wants to add default query params so that it
3840
+	 *                                                          will know what models to prepend onto its default query
3841
+	 *                                                          params or in case it wants to rename tables (in case
3842
+	 *                                                          there are multiple joins to the same table)
3843
+	 * @return void
3844
+	 * @throws \EE_Error
3845
+	 */
3846
+	private function _add_join_to_model(
3847
+		$model_name,
3848
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3849
+		$original_query_param
3850
+	) {
3851
+		$relation_obj = $this->related_settings_for($model_name);
3852
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3853
+		//check if the relation is HABTM, because then we're essentially doing two joins
3854
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3855
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3856
+			$join_model_obj = $relation_obj->get_join_model();
3857
+			//replace the model specified with the join model for this relation chain, whi
3858
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3859
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3860
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3861
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3862
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3863
+			$passed_in_query_info->merge($new_query_info);
3864
+		}
3865
+		//now just join to the other table pointed to by the relation object, and add its data types
3866
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3867
+			array($model_relation_chain => $model_name),
3868
+			$relation_obj->get_join_statement($model_relation_chain));
3869
+		$passed_in_query_info->merge($new_query_info);
3870
+	}
3871
+
3872
+
3873
+
3874
+	/**
3875
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3876
+	 *
3877
+	 * @param array $where_params like EEM_Base::get_all
3878
+	 * @return string of SQL
3879
+	 * @throws \EE_Error
3880
+	 */
3881
+	private function _construct_where_clause($where_params)
3882
+	{
3883
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3884
+		if ($SQL) {
3885
+			return " WHERE " . $SQL;
3886
+		} else {
3887
+			return '';
3888
+		}
3889
+	}
3890
+
3891
+
3892
+
3893
+	/**
3894
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3895
+	 * and should be passed HAVING parameters, not WHERE parameters
3896
+	 *
3897
+	 * @param array $having_params
3898
+	 * @return string
3899
+	 * @throws \EE_Error
3900
+	 */
3901
+	private function _construct_having_clause($having_params)
3902
+	{
3903
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3904
+		if ($SQL) {
3905
+			return " HAVING " . $SQL;
3906
+		} else {
3907
+			return '';
3908
+		}
3909
+	}
3910
+
3911
+
3912
+
3913
+	/**
3914
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3915
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3916
+	 * EEM_Attendee.
3917
+	 *
3918
+	 * @param string $field_name
3919
+	 * @param string $model_name
3920
+	 * @return EE_Model_Field_Base
3921
+	 * @throws EE_Error
3922
+	 */
3923
+	protected function _get_field_on_model($field_name, $model_name)
3924
+	{
3925
+		$model_class = 'EEM_' . $model_name;
3926
+		$model_filepath = $model_class . ".model.php";
3927
+		if (is_readable($model_filepath)) {
3928
+			require_once($model_filepath);
3929
+			$model_instance = call_user_func($model_name . "::instance");
3930
+			/* @var $model_instance EEM_Base */
3931
+			return $model_instance->field_settings_for($field_name);
3932
+		} else {
3933
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3934
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3935
+		}
3936
+	}
3937
+
3938
+
3939
+
3940
+	/**
3941
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3942
+	 * Event_Meta.meta_value = 'foo'))"
3943
+	 *
3944
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3945
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3946
+	 * @throws EE_Error
3947
+	 * @return string of SQL
3948
+	 */
3949
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3950
+	{
3951
+		$where_clauses = array();
3952
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3953
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3954
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3955
+				switch ($query_param) {
3956
+					case 'not':
3957
+					case 'NOT':
3958
+						$where_clauses[] = "! ("
3959
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3960
+								$glue)
3961
+										   . ")";
3962
+						break;
3963
+					case 'and':
3964
+					case 'AND':
3965
+						$where_clauses[] = " ("
3966
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3967
+								' AND ')
3968
+										   . ")";
3969
+						break;
3970
+					case 'or':
3971
+					case 'OR':
3972
+						$where_clauses[] = " ("
3973
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3974
+								' OR ')
3975
+										   . ")";
3976
+						break;
3977
+				}
3978
+			} else {
3979
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3980
+				//if it's not a normal field, maybe it's a custom selection?
3981
+				if (! $field_obj) {
3982
+					if (isset($this->_custom_selections[$query_param][1])) {
3983
+						$field_obj = $this->_custom_selections[$query_param][1];
3984
+					} else {
3985
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3986
+							"event_espresso"), $query_param));
3987
+					}
3988
+				}
3989
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3990
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3991
+			}
3992
+		}
3993
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3994
+	}
3995
+
3996
+
3997
+
3998
+	/**
3999
+	 * Takes the input parameter and extract the table name (alias) and column name
4000
+	 *
4001
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4002
+	 * @throws EE_Error
4003
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4004
+	 */
4005
+	private function _deduce_column_name_from_query_param($query_param)
4006
+	{
4007
+		$field = $this->_deduce_field_from_query_param($query_param);
4008
+		if ($field) {
4009
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4010
+				$query_param);
4011
+			return $table_alias_prefix . $field->get_qualified_column();
4012
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4013
+			//maybe it's custom selection item?
4014
+			//if so, just use it as the "column name"
4015
+			return $query_param;
4016
+		} else {
4017
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4018
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4019
+		}
4020
+	}
4021
+
4022
+
4023
+
4024
+	/**
4025
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4026
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4027
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4028
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4029
+	 *
4030
+	 * @param string $condition_query_param_key
4031
+	 * @return string
4032
+	 */
4033
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4034
+	{
4035
+		$pos_of_star = strpos($condition_query_param_key, '*');
4036
+		if ($pos_of_star === false) {
4037
+			return $condition_query_param_key;
4038
+		} else {
4039
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4040
+			return $condition_query_param_sans_star;
4041
+		}
4042
+	}
4043
+
4044
+
4045
+
4046
+	/**
4047
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4048
+	 *
4049
+	 * @param                            mixed      array | string    $op_and_value
4050
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4051
+	 * @throws EE_Error
4052
+	 * @return string
4053
+	 */
4054
+	private function _construct_op_and_value($op_and_value, $field_obj)
4055
+	{
4056
+		if (is_array($op_and_value)) {
4057
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4058
+			if (! $operator) {
4059
+				$php_array_like_string = array();
4060
+				foreach ($op_and_value as $key => $value) {
4061
+					$php_array_like_string[] = "$key=>$value";
4062
+				}
4063
+				throw new EE_Error(
4064
+					sprintf(
4065
+						__(
4066
+							"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))",
4067
+							"event_espresso"
4068
+						),
4069
+						implode(",", $php_array_like_string)
4070
+					)
4071
+				);
4072
+			}
4073
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4074
+		} else {
4075
+			$operator = '=';
4076
+			$value = $op_and_value;
4077
+		}
4078
+		//check to see if the value is actually another field
4079
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4080
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4081
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4082
+			//in this case, the value should be an array, or at least a comma-separated list
4083
+			//it will need to handle a little differently
4084
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4085
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4086
+			return $operator . SP . $cleaned_value;
4087
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4088
+			//the value should be an array with count of two.
4089
+			if (count($value) !== 2) {
4090
+				throw new EE_Error(
4091
+					sprintf(
4092
+						__(
4093
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4094
+							'event_espresso'
4095
+						),
4096
+						"BETWEEN"
4097
+					)
4098
+				);
4099
+			}
4100
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4101
+			return $operator . SP . $cleaned_value;
4102
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4103
+			if ($value !== null) {
4104
+				throw new EE_Error(
4105
+					sprintf(
4106
+						__(
4107
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4108
+							"event_espresso"
4109
+						),
4110
+						$value,
4111
+						$operator
4112
+					)
4113
+				);
4114
+			}
4115
+			return $operator;
4116
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4117
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4118
+			//remove other junk. So just treat it as a string.
4119
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4120
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4121
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4122
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4123
+			throw new EE_Error(
4124
+				sprintf(
4125
+					__(
4126
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4127
+						'event_espresso'
4128
+					),
4129
+					$operator,
4130
+					$operator
4131
+				)
4132
+			);
4133
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4134
+			throw new EE_Error(
4135
+				sprintf(
4136
+					__(
4137
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4138
+						'event_espresso'
4139
+					),
4140
+					$operator,
4141
+					$operator
4142
+				)
4143
+			);
4144
+		} else {
4145
+			throw new EE_Error(
4146
+				sprintf(
4147
+					__(
4148
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4149
+						"event_espresso"
4150
+					),
4151
+					http_build_query($op_and_value)
4152
+				)
4153
+			);
4154
+		}
4155
+	}
4156
+
4157
+
4158
+
4159
+	/**
4160
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4161
+	 *
4162
+	 * @param array                      $values
4163
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4164
+	 *                                              '%s'
4165
+	 * @return string
4166
+	 * @throws \EE_Error
4167
+	 */
4168
+	public function _construct_between_value($values, $field_obj)
4169
+	{
4170
+		$cleaned_values = array();
4171
+		foreach ($values as $value) {
4172
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4173
+		}
4174
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4175
+	}
4176
+
4177
+
4178
+
4179
+	/**
4180
+	 * Takes an array or a comma-separated list of $values and cleans them
4181
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4182
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4183
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4184
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4185
+	 *
4186
+	 * @param mixed                      $values    array or comma-separated string
4187
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4188
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4189
+	 * @throws \EE_Error
4190
+	 */
4191
+	public function _construct_in_value($values, $field_obj)
4192
+	{
4193
+		//check if the value is a CSV list
4194
+		if (is_string($values)) {
4195
+			//in which case, turn it into an array
4196
+			$values = explode(",", $values);
4197
+		}
4198
+		$cleaned_values = array();
4199
+		foreach ($values as $value) {
4200
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4201
+		}
4202
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4203
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4204
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4205
+		if (empty($cleaned_values)) {
4206
+			$all_fields = $this->field_settings();
4207
+			$a_field = array_shift($all_fields);
4208
+			$main_table = $this->_get_main_table();
4209
+			$cleaned_values[] = "SELECT "
4210
+								. $a_field->get_table_column()
4211
+								. " FROM "
4212
+								. $main_table->get_table_name()
4213
+								. " WHERE FALSE";
4214
+		}
4215
+		return "(" . implode(",", $cleaned_values) . ")";
4216
+	}
4217
+
4218
+
4219
+
4220
+	/**
4221
+	 * @param mixed                      $value
4222
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4223
+	 * @throws EE_Error
4224
+	 * @return false|null|string
4225
+	 */
4226
+	private function _wpdb_prepare_using_field($value, $field_obj)
4227
+	{
4228
+		/** @type WPDB $wpdb */
4229
+		global $wpdb;
4230
+		if ($field_obj instanceof EE_Model_Field_Base) {
4231
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4232
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4233
+		} else {//$field_obj should really just be a data type
4234
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4235
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4236
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4237
+			}
4238
+			return $wpdb->prepare($field_obj, $value);
4239
+		}
4240
+	}
4241
+
4242
+
4243
+
4244
+	/**
4245
+	 * Takes the input parameter and finds the model field that it indicates.
4246
+	 *
4247
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4248
+	 * @throws EE_Error
4249
+	 * @return EE_Model_Field_Base
4250
+	 */
4251
+	protected function _deduce_field_from_query_param($query_param_name)
4252
+	{
4253
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4254
+		//which will help us find the database table and column
4255
+		$query_param_parts = explode(".", $query_param_name);
4256
+		if (empty($query_param_parts)) {
4257
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4258
+				'event_espresso'), $query_param_name));
4259
+		}
4260
+		$number_of_parts = count($query_param_parts);
4261
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4262
+		if ($number_of_parts === 1) {
4263
+			$field_name = $last_query_param_part;
4264
+			$model_obj = $this;
4265
+		} else {// $number_of_parts >= 2
4266
+			//the last part is the column name, and there are only 2parts. therefore...
4267
+			$field_name = $last_query_param_part;
4268
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4269
+		}
4270
+		try {
4271
+			return $model_obj->field_settings_for($field_name);
4272
+		} catch (EE_Error $e) {
4273
+			return null;
4274
+		}
4275
+	}
4276
+
4277
+
4278
+
4279
+	/**
4280
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4281
+	 * alias and column which corresponds to it
4282
+	 *
4283
+	 * @param string $field_name
4284
+	 * @throws EE_Error
4285
+	 * @return string
4286
+	 */
4287
+	public function _get_qualified_column_for_field($field_name)
4288
+	{
4289
+		$all_fields = $this->field_settings();
4290
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4291
+		if ($field) {
4292
+			return $field->get_qualified_column();
4293
+		} else {
4294
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4295
+				'event_espresso'), $field_name, get_class($this)));
4296
+		}
4297
+	}
4298
+
4299
+
4300
+
4301
+	/**
4302
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4303
+	 * Example usage:
4304
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4305
+	 *      array(),
4306
+	 *      ARRAY_A,
4307
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4308
+	 *  );
4309
+	 * is equivalent to
4310
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4311
+	 * and
4312
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4313
+	 *      array(
4314
+	 *          array(
4315
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4316
+	 *          ),
4317
+	 *          ARRAY_A,
4318
+	 *          implode(
4319
+	 *              ', ',
4320
+	 *              array_merge(
4321
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4322
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4323
+	 *              )
4324
+	 *          )
4325
+	 *      )
4326
+	 *  );
4327
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4328
+	 *
4329
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4330
+	 *                                            and the one whose fields you are selecting for example: when querying
4331
+	 *                                            tickets model and selecting fields from the tickets model you would
4332
+	 *                                            leave this parameter empty, because no models are needed to join
4333
+	 *                                            between the queried model and the selected one. Likewise when
4334
+	 *                                            querying the datetime model and selecting fields from the tickets
4335
+	 *                                            model, it would also be left empty, because there is a direct
4336
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4337
+	 *                                            them together. However, when querying from the event model and
4338
+	 *                                            selecting fields from the ticket model, you should provide the string
4339
+	 *                                            'Datetime', indicating that the event model must first join to the
4340
+	 *                                            datetime model in order to find its relation to ticket model.
4341
+	 *                                            Also, when querying from the venue model and selecting fields from
4342
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4343
+	 *                                            indicating you need to join the venue model to the event model,
4344
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4345
+	 *                                            This string is used to deduce the prefix that gets added onto the
4346
+	 *                                            models' tables qualified columns
4347
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4348
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4349
+	 *                                            qualified column names
4350
+	 * @return array|string
4351
+	 */
4352
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4353
+	{
4354
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4355
+		$qualified_columns = array();
4356
+		foreach ($this->field_settings() as $field_name => $field) {
4357
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4358
+		}
4359
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4360
+	}
4361
+
4362
+
4363
+
4364
+	/**
4365
+	 * constructs the select use on special limit joins
4366
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4367
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4368
+	 * (as that is typically where the limits would be set).
4369
+	 *
4370
+	 * @param  string       $table_alias The table the select is being built for
4371
+	 * @param  mixed|string $limit       The limit for this select
4372
+	 * @return string                The final select join element for the query.
4373
+	 */
4374
+	public function _construct_limit_join_select($table_alias, $limit)
4375
+	{
4376
+		$SQL = '';
4377
+		foreach ($this->_tables as $table_obj) {
4378
+			if ($table_obj instanceof EE_Primary_Table) {
4379
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4380
+					? $table_obj->get_select_join_limit($limit)
4381
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4382
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4383
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4384
+					? $table_obj->get_select_join_limit_join($limit)
4385
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4386
+			}
4387
+		}
4388
+		return $SQL;
4389
+	}
4390
+
4391
+
4392
+
4393
+	/**
4394
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4395
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4396
+	 *
4397
+	 * @return string SQL
4398
+	 * @throws \EE_Error
4399
+	 */
4400
+	public function _construct_internal_join()
4401
+	{
4402
+		$SQL = $this->_get_main_table()->get_table_sql();
4403
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4404
+		return $SQL;
4405
+	}
4406
+
4407
+
4408
+
4409
+	/**
4410
+	 * Constructs the SQL for joining all the tables on this model.
4411
+	 * Normally $alias should be the primary table's alias, but in cases where
4412
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4413
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4414
+	 * alias, this will construct SQL like:
4415
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4416
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4417
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4418
+	 *
4419
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4420
+	 * @return string
4421
+	 */
4422
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4423
+	{
4424
+		$SQL = '';
4425
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4426
+		foreach ($this->_tables as $table_obj) {
4427
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4428
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4429
+					//so we're joining to this table, meaning the table is already in
4430
+					//the FROM statement, BUT the primary table isn't. So we want
4431
+					//to add the inverse join sql
4432
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4433
+				} else {
4434
+					//just add a regular JOIN to this table from the primary table
4435
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4436
+				}
4437
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4438
+		}
4439
+		return $SQL;
4440
+	}
4441
+
4442
+
4443
+
4444
+	/**
4445
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4446
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4447
+	 * their data type (eg, '%s', '%d', etc)
4448
+	 *
4449
+	 * @return array
4450
+	 */
4451
+	public function _get_data_types()
4452
+	{
4453
+		$data_types = array();
4454
+		foreach ($this->field_settings() as $field_obj) {
4455
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4456
+			/** @var $field_obj EE_Model_Field_Base */
4457
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4458
+		}
4459
+		return $data_types;
4460
+	}
4461
+
4462
+
4463
+
4464
+	/**
4465
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4466
+	 *
4467
+	 * @param string $model_name
4468
+	 * @throws EE_Error
4469
+	 * @return EEM_Base
4470
+	 */
4471
+	public function get_related_model_obj($model_name)
4472
+	{
4473
+		$model_classname = "EEM_" . $model_name;
4474
+		if (! class_exists($model_classname)) {
4475
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4476
+				'event_espresso'), $model_name, $model_classname));
4477
+		}
4478
+		return call_user_func($model_classname . "::instance");
4479
+	}
4480
+
4481
+
4482
+
4483
+	/**
4484
+	 * Returns the array of EE_ModelRelations for this model.
4485
+	 *
4486
+	 * @return EE_Model_Relation_Base[]
4487
+	 */
4488
+	public function relation_settings()
4489
+	{
4490
+		return $this->_model_relations;
4491
+	}
4492
+
4493
+
4494
+
4495
+	/**
4496
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4497
+	 * because without THOSE models, this model probably doesn't have much purpose.
4498
+	 * (Eg, without an event, datetimes have little purpose.)
4499
+	 *
4500
+	 * @return EE_Belongs_To_Relation[]
4501
+	 */
4502
+	public function belongs_to_relations()
4503
+	{
4504
+		$belongs_to_relations = array();
4505
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4506
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4507
+				$belongs_to_relations[$model_name] = $relation_obj;
4508
+			}
4509
+		}
4510
+		return $belongs_to_relations;
4511
+	}
4512
+
4513
+
4514
+
4515
+	/**
4516
+	 * Returns the specified EE_Model_Relation, or throws an exception
4517
+	 *
4518
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4519
+	 * @throws EE_Error
4520
+	 * @return EE_Model_Relation_Base
4521
+	 */
4522
+	public function related_settings_for($relation_name)
4523
+	{
4524
+		$relatedModels = $this->relation_settings();
4525
+		if (! array_key_exists($relation_name, $relatedModels)) {
4526
+			throw new EE_Error(
4527
+				sprintf(
4528
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4529
+						'event_espresso'),
4530
+					$relation_name,
4531
+					$this->_get_class_name(),
4532
+					implode(', ', array_keys($relatedModels))
4533
+				)
4534
+			);
4535
+		}
4536
+		return $relatedModels[$relation_name];
4537
+	}
4538
+
4539
+
4540
+
4541
+	/**
4542
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4543
+	 * fields
4544
+	 *
4545
+	 * @param string $fieldName
4546
+	 * @throws EE_Error
4547
+	 * @return EE_Model_Field_Base
4548
+	 */
4549
+	public function field_settings_for($fieldName)
4550
+	{
4551
+		$fieldSettings = $this->field_settings(true);
4552
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4553
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4554
+				get_class($this)));
4555
+		}
4556
+		return $fieldSettings[$fieldName];
4557
+	}
4558
+
4559
+
4560
+
4561
+	/**
4562
+	 * Checks if this field exists on this model
4563
+	 *
4564
+	 * @param string $fieldName a key in the model's _field_settings array
4565
+	 * @return boolean
4566
+	 */
4567
+	public function has_field($fieldName)
4568
+	{
4569
+		$fieldSettings = $this->field_settings(true);
4570
+		if (isset($fieldSettings[$fieldName])) {
4571
+			return true;
4572
+		} else {
4573
+			return false;
4574
+		}
4575
+	}
4576
+
4577
+
4578
+
4579
+	/**
4580
+	 * Returns whether or not this model has a relation to the specified model
4581
+	 *
4582
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4583
+	 * @return boolean
4584
+	 */
4585
+	public function has_relation($relation_name)
4586
+	{
4587
+		$relations = $this->relation_settings();
4588
+		if (isset($relations[$relation_name])) {
4589
+			return true;
4590
+		} else {
4591
+			return false;
4592
+		}
4593
+	}
4594
+
4595
+
4596
+
4597
+	/**
4598
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4599
+	 * Eg, on EE_Answer that would be ANS_ID field object
4600
+	 *
4601
+	 * @param $field_obj
4602
+	 * @return boolean
4603
+	 */
4604
+	public function is_primary_key_field($field_obj)
4605
+	{
4606
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4607
+	}
4608
+
4609
+
4610
+
4611
+	/**
4612
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4613
+	 * Eg, on EE_Answer that would be ANS_ID field object
4614
+	 *
4615
+	 * @return EE_Model_Field_Base
4616
+	 * @throws EE_Error
4617
+	 */
4618
+	public function get_primary_key_field()
4619
+	{
4620
+		if ($this->_primary_key_field === null) {
4621
+			foreach ($this->field_settings(true) as $field_obj) {
4622
+				if ($this->is_primary_key_field($field_obj)) {
4623
+					$this->_primary_key_field = $field_obj;
4624
+					break;
4625
+				}
4626
+			}
4627
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4628
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4629
+					get_class($this)));
4630
+			}
4631
+		}
4632
+		return $this->_primary_key_field;
4633
+	}
4634
+
4635
+
4636
+
4637
+	/**
4638
+	 * Returns whether or not not there is a primary key on this model.
4639
+	 * Internally does some caching.
4640
+	 *
4641
+	 * @return boolean
4642
+	 */
4643
+	public function has_primary_key_field()
4644
+	{
4645
+		if ($this->_has_primary_key_field === null) {
4646
+			try {
4647
+				$this->get_primary_key_field();
4648
+				$this->_has_primary_key_field = true;
4649
+			} catch (EE_Error $e) {
4650
+				$this->_has_primary_key_field = false;
4651
+			}
4652
+		}
4653
+		return $this->_has_primary_key_field;
4654
+	}
4655
+
4656
+
4657
+
4658
+	/**
4659
+	 * Finds the first field of type $field_class_name.
4660
+	 *
4661
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4662
+	 *                                 EE_Foreign_Key_Field, etc
4663
+	 * @return EE_Model_Field_Base or null if none is found
4664
+	 */
4665
+	public function get_a_field_of_type($field_class_name)
4666
+	{
4667
+		foreach ($this->field_settings() as $field) {
4668
+			if ($field instanceof $field_class_name) {
4669
+				return $field;
4670
+			}
4671
+		}
4672
+		return null;
4673
+	}
4674
+
4675
+
4676
+
4677
+	/**
4678
+	 * Gets a foreign key field pointing to model.
4679
+	 *
4680
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4681
+	 * @return EE_Foreign_Key_Field_Base
4682
+	 * @throws EE_Error
4683
+	 */
4684
+	public function get_foreign_key_to($model_name)
4685
+	{
4686
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4687
+			foreach ($this->field_settings() as $field) {
4688
+				if (
4689
+					$field instanceof EE_Foreign_Key_Field_Base
4690
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4691
+				) {
4692
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4693
+					break;
4694
+				}
4695
+			}
4696
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4697
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4698
+					'event_espresso'), $model_name, get_class($this)));
4699
+			}
4700
+		}
4701
+		return $this->_cache_foreign_key_to_fields[$model_name];
4702
+	}
4703
+
4704
+
4705
+
4706
+	/**
4707
+	 * Gets the actual table for the table alias
4708
+	 *
4709
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4710
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4711
+	 *                            Either one works
4712
+	 * @return EE_Table_Base
4713
+	 */
4714
+	public function get_table_for_alias($table_alias)
4715
+	{
4716
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4717
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4718
+	}
4719
+
4720
+
4721
+
4722
+	/**
4723
+	 * Returns a flat array of all field son this model, instead of organizing them
4724
+	 * by table_alias as they are in the constructor.
4725
+	 *
4726
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4727
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4728
+	 */
4729
+	public function field_settings($include_db_only_fields = false)
4730
+	{
4731
+		if ($include_db_only_fields) {
4732
+			if ($this->_cached_fields === null) {
4733
+				$this->_cached_fields = array();
4734
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4735
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4736
+						$this->_cached_fields[$field_name] = $field_obj;
4737
+					}
4738
+				}
4739
+			}
4740
+			return $this->_cached_fields;
4741
+		} else {
4742
+			if ($this->_cached_fields_non_db_only === null) {
4743
+				$this->_cached_fields_non_db_only = array();
4744
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4745
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4746
+						/** @var $field_obj EE_Model_Field_Base */
4747
+						if (! $field_obj->is_db_only_field()) {
4748
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4749
+						}
4750
+					}
4751
+				}
4752
+			}
4753
+			return $this->_cached_fields_non_db_only;
4754
+		}
4755
+	}
4756
+
4757
+
4758
+
4759
+	/**
4760
+	 *        cycle though array of attendees and create objects out of each item
4761
+	 *
4762
+	 * @access        private
4763
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4764
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4765
+	 *                           numerically indexed)
4766
+	 * @throws \EE_Error
4767
+	 */
4768
+	protected function _create_objects($rows = array())
4769
+	{
4770
+		$array_of_objects = array();
4771
+		if (empty($rows)) {
4772
+			return array();
4773
+		}
4774
+		$count_if_model_has_no_primary_key = 0;
4775
+		$has_primary_key = $this->has_primary_key_field();
4776
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4777
+		foreach ((array)$rows as $row) {
4778
+			if (empty($row)) {
4779
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4780
+				return array();
4781
+			}
4782
+			//check if we've already set this object in the results array,
4783
+			//in which case there's no need to process it further (again)
4784
+			if ($has_primary_key) {
4785
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4786
+					$row,
4787
+					$primary_key_field->get_qualified_column(),
4788
+					$primary_key_field->get_table_column()
4789
+				);
4790
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4791
+					continue;
4792
+				}
4793
+			}
4794
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4795
+			if (! $classInstance) {
4796
+				throw new EE_Error(
4797
+					sprintf(
4798
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4799
+						$this->get_this_model_name(),
4800
+						http_build_query($row)
4801
+					)
4802
+				);
4803
+			}
4804
+			//set the timezone on the instantiated objects
4805
+			$classInstance->set_timezone($this->_timezone);
4806
+			//make sure if there is any timezone setting present that we set the timezone for the object
4807
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4808
+			$array_of_objects[$key] = $classInstance;
4809
+			//also, for all the relations of type BelongsTo, see if we can cache
4810
+			//those related models
4811
+			//(we could do this for other relations too, but if there are conditions
4812
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4813
+			//so it requires a little more thought than just caching them immediately...)
4814
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4815
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4816
+					//check if this model's INFO is present. If so, cache it on the model
4817
+					$other_model = $relation_obj->get_other_model();
4818
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4819
+					//if we managed to make a model object from the results, cache it on the main model object
4820
+					if ($other_model_obj_maybe) {
4821
+						//set timezone on these other model objects if they are present
4822
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4823
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4824
+					}
4825
+				}
4826
+			}
4827
+		}
4828
+		return $array_of_objects;
4829
+	}
4830
+
4831
+
4832
+
4833
+	/**
4834
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4835
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4836
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4837
+	 * object (as set in the model_field!).
4838
+	 *
4839
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4840
+	 */
4841
+	public function create_default_object()
4842
+	{
4843
+		$this_model_fields_and_values = array();
4844
+		//setup the row using default values;
4845
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4846
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4847
+		}
4848
+		$className = $this->_get_class_name();
4849
+		$classInstance = EE_Registry::instance()
4850
+									->load_class($className, array($this_model_fields_and_values), false, false);
4851
+		return $classInstance;
4852
+	}
4853
+
4854
+
4855
+
4856
+	/**
4857
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4858
+	 *                             or an stdClass where each property is the name of a column,
4859
+	 * @return EE_Base_Class
4860
+	 * @throws \EE_Error
4861
+	 */
4862
+	public function instantiate_class_from_array_or_object($cols_n_values)
4863
+	{
4864
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4865
+			$cols_n_values = get_object_vars($cols_n_values);
4866
+		}
4867
+		$primary_key = null;
4868
+		//make sure the array only has keys that are fields/columns on this model
4869
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4870
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4871
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4872
+		}
4873
+		$className = $this->_get_class_name();
4874
+		//check we actually found results that we can use to build our model object
4875
+		//if not, return null
4876
+		if ($this->has_primary_key_field()) {
4877
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4878
+				return null;
4879
+			}
4880
+		} else if ($this->unique_indexes()) {
4881
+			$first_column = reset($this_model_fields_n_values);
4882
+			if (empty($first_column)) {
4883
+				return null;
4884
+			}
4885
+		}
4886
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4887
+		if ($primary_key) {
4888
+			$classInstance = $this->get_from_entity_map($primary_key);
4889
+			if (! $classInstance) {
4890
+				$classInstance = EE_Registry::instance()
4891
+											->load_class($className,
4892
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4893
+				// add this new object to the entity map
4894
+				$classInstance = $this->add_to_entity_map($classInstance);
4895
+			}
4896
+		} else {
4897
+			$classInstance = EE_Registry::instance()
4898
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4899
+											true, false);
4900
+		}
4901
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4902
+		$this->set_timezone($classInstance->get_timezone());
4903
+		return $classInstance;
4904
+	}
4905
+
4906
+
4907
+
4908
+	/**
4909
+	 * Gets the model object from the  entity map if it exists
4910
+	 *
4911
+	 * @param int|string $id the ID of the model object
4912
+	 * @return EE_Base_Class
4913
+	 */
4914
+	public function get_from_entity_map($id)
4915
+	{
4916
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4917
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4918
+	}
4919
+
4920
+
4921
+
4922
+	/**
4923
+	 * add_to_entity_map
4924
+	 * Adds the object to the model's entity mappings
4925
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4926
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4927
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4928
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4929
+	 *        then this method should be called immediately after the update query
4930
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4931
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4932
+	 *
4933
+	 * @param    EE_Base_Class $object
4934
+	 * @throws EE_Error
4935
+	 * @return \EE_Base_Class
4936
+	 */
4937
+	public function add_to_entity_map(EE_Base_Class $object)
4938
+	{
4939
+		$className = $this->_get_class_name();
4940
+		if (! $object instanceof $className) {
4941
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4942
+				is_object($object) ? get_class($object) : $object, $className));
4943
+		}
4944
+		/** @var $object EE_Base_Class */
4945
+		if (! $object->ID()) {
4946
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4947
+				"event_espresso"), get_class($this)));
4948
+		}
4949
+		// double check it's not already there
4950
+		$classInstance = $this->get_from_entity_map($object->ID());
4951
+		if ($classInstance) {
4952
+			return $classInstance;
4953
+		} else {
4954
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4955
+			return $object;
4956
+		}
4957
+	}
4958
+
4959
+
4960
+
4961
+	/**
4962
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4963
+	 * if no identifier is provided, then the entire entity map is emptied
4964
+	 *
4965
+	 * @param int|string $id the ID of the model object
4966
+	 * @return boolean
4967
+	 */
4968
+	public function clear_entity_map($id = null)
4969
+	{
4970
+		if (empty($id)) {
4971
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4972
+			return true;
4973
+		}
4974
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4975
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4976
+			return true;
4977
+		}
4978
+		return false;
4979
+	}
4980
+
4981
+
4982
+
4983
+	/**
4984
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4985
+	 * Given an array where keys are column (or column alias) names and values,
4986
+	 * returns an array of their corresponding field names and database values
4987
+	 *
4988
+	 * @param array $cols_n_values
4989
+	 * @return array
4990
+	 */
4991
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4992
+	{
4993
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4994
+	}
4995
+
4996
+
4997
+
4998
+	/**
4999
+	 * _deduce_fields_n_values_from_cols_n_values
5000
+	 * Given an array where keys are column (or column alias) names and values,
5001
+	 * returns an array of their corresponding field names and database values
5002
+	 *
5003
+	 * @param string $cols_n_values
5004
+	 * @return array
5005
+	 */
5006
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5007
+	{
5008
+		$this_model_fields_n_values = array();
5009
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5010
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5011
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5012
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5013
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5014
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5015
+					if (! $field_obj->is_db_only_field()) {
5016
+						//prepare field as if its coming from db
5017
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5018
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5019
+					}
5020
+				}
5021
+			} else {
5022
+				//the table's rows existed. Use their values
5023
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5024
+					if (! $field_obj->is_db_only_field()) {
5025
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5026
+							$cols_n_values, $field_obj->get_qualified_column(),
5027
+							$field_obj->get_table_column()
5028
+						);
5029
+					}
5030
+				}
5031
+			}
5032
+		}
5033
+		return $this_model_fields_n_values;
5034
+	}
5035
+
5036
+
5037
+
5038
+	/**
5039
+	 * @param $cols_n_values
5040
+	 * @param $qualified_column
5041
+	 * @param $regular_column
5042
+	 * @return null
5043
+	 */
5044
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5045
+	{
5046
+		$value = null;
5047
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5048
+		//does the field on the model relate to this column retrieved from the db?
5049
+		//or is it a db-only field? (not relating to the model)
5050
+		if (isset($cols_n_values[$qualified_column])) {
5051
+			$value = $cols_n_values[$qualified_column];
5052
+		} elseif (isset($cols_n_values[$regular_column])) {
5053
+			$value = $cols_n_values[$regular_column];
5054
+		}
5055
+		return $value;
5056
+	}
5057
+
5058
+
5059
+
5060
+	/**
5061
+	 * refresh_entity_map_from_db
5062
+	 * Makes sure the model object in the entity map at $id assumes the values
5063
+	 * of the database (opposite of EE_base_Class::save())
5064
+	 *
5065
+	 * @param int|string $id
5066
+	 * @return EE_Base_Class
5067
+	 * @throws \EE_Error
5068
+	 */
5069
+	public function refresh_entity_map_from_db($id)
5070
+	{
5071
+		$obj_in_map = $this->get_from_entity_map($id);
5072
+		if ($obj_in_map) {
5073
+			$wpdb_results = $this->_get_all_wpdb_results(
5074
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5075
+			);
5076
+			if ($wpdb_results && is_array($wpdb_results)) {
5077
+				$one_row = reset($wpdb_results);
5078
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5079
+					$obj_in_map->set_from_db($field_name, $db_value);
5080
+				}
5081
+				//clear the cache of related model objects
5082
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5083
+					$obj_in_map->clear_cache($relation_name, null, true);
5084
+				}
5085
+			}
5086
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5087
+			return $obj_in_map;
5088
+		} else {
5089
+			return $this->get_one_by_ID($id);
5090
+		}
5091
+	}
5092
+
5093
+
5094
+
5095
+	/**
5096
+	 * refresh_entity_map_with
5097
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5098
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5099
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5100
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5101
+	 *
5102
+	 * @param int|string    $id
5103
+	 * @param EE_Base_Class $replacing_model_obj
5104
+	 * @return \EE_Base_Class
5105
+	 * @throws \EE_Error
5106
+	 */
5107
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5108
+	{
5109
+		$obj_in_map = $this->get_from_entity_map($id);
5110
+		if ($obj_in_map) {
5111
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5112
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5113
+					$obj_in_map->set($field_name, $value);
5114
+				}
5115
+				//make the model object in the entity map's cache match the $replacing_model_obj
5116
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5117
+					$obj_in_map->clear_cache($relation_name, null, true);
5118
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5119
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5120
+					}
5121
+				}
5122
+			}
5123
+			return $obj_in_map;
5124
+		} else {
5125
+			$this->add_to_entity_map($replacing_model_obj);
5126
+			return $replacing_model_obj;
5127
+		}
5128
+	}
5129
+
5130
+
5131
+
5132
+	/**
5133
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5134
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5135
+	 * require_once($this->_getClassName().".class.php");
5136
+	 *
5137
+	 * @return string
5138
+	 */
5139
+	private function _get_class_name()
5140
+	{
5141
+		return "EE_" . $this->get_this_model_name();
5142
+	}
5143
+
5144
+
5145
+
5146
+	/**
5147
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5148
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5149
+	 * it would be 'Events'.
5150
+	 *
5151
+	 * @param int $quantity
5152
+	 * @return string
5153
+	 */
5154
+	public function item_name($quantity = 1)
5155
+	{
5156
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5157
+	}
5158
+
5159
+
5160
+
5161
+	/**
5162
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5163
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5164
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5165
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5166
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5167
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5168
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5169
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5170
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5171
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5172
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5173
+	 *        return $previousReturnValue.$returnString;
5174
+	 * }
5175
+	 * require('EEM_Answer.model.php');
5176
+	 * $answer=EEM_Answer::instance();
5177
+	 * echo $answer->my_callback('monkeys',100);
5178
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5179
+	 *
5180
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5181
+	 * @param array  $args       array of original arguments passed to the function
5182
+	 * @throws EE_Error
5183
+	 * @return mixed whatever the plugin which calls add_filter decides
5184
+	 */
5185
+	public function __call($methodName, $args)
5186
+	{
5187
+		$className = get_class($this);
5188
+		$tagName = "FHEE__{$className}__{$methodName}";
5189
+		if (! has_filter($tagName)) {
5190
+			throw new EE_Error(
5191
+				sprintf(
5192
+					__('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 );',
5193
+						'event_espresso'),
5194
+					$methodName,
5195
+					$className,
5196
+					$tagName,
5197
+					'<br />'
5198
+				)
5199
+			);
5200
+		}
5201
+		return apply_filters($tagName, null, $this, $args);
5202
+	}
5203
+
5204
+
5205
+
5206
+	/**
5207
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5208
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5209
+	 *
5210
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5211
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5212
+	 *                                                       the object's class name
5213
+	 *                                                       or object's ID
5214
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5215
+	 *                                                       exists in the database. If it does not, we add it
5216
+	 * @throws EE_Error
5217
+	 * @return EE_Base_Class
5218
+	 */
5219
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5220
+	{
5221
+		$className = $this->_get_class_name();
5222
+		if ($base_class_obj_or_id instanceof $className) {
5223
+			$model_object = $base_class_obj_or_id;
5224
+		} else {
5225
+			$primary_key_field = $this->get_primary_key_field();
5226
+			if (
5227
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5228
+				&& (
5229
+					is_int($base_class_obj_or_id)
5230
+					|| is_string($base_class_obj_or_id)
5231
+				)
5232
+			) {
5233
+				// assume it's an ID.
5234
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5235
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5236
+			} else if (
5237
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5238
+				&& is_string($base_class_obj_or_id)
5239
+			) {
5240
+				// assume its a string representation of the object
5241
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5242
+			} else {
5243
+				throw new EE_Error(
5244
+					sprintf(
5245
+						__(
5246
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5247
+							'event_espresso'
5248
+						),
5249
+						$base_class_obj_or_id,
5250
+						$this->_get_class_name(),
5251
+						print_r($base_class_obj_or_id, true)
5252
+					)
5253
+				);
5254
+			}
5255
+		}
5256
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5257
+			$model_object->save();
5258
+		}
5259
+		return $model_object;
5260
+	}
5261
+
5262
+
5263
+
5264
+	/**
5265
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5266
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5267
+	 * returns it ID.
5268
+	 *
5269
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5270
+	 * @return int|string depending on the type of this model object's ID
5271
+	 * @throws EE_Error
5272
+	 */
5273
+	public function ensure_is_ID($base_class_obj_or_id)
5274
+	{
5275
+		$className = $this->_get_class_name();
5276
+		if ($base_class_obj_or_id instanceof $className) {
5277
+			/** @var $base_class_obj_or_id EE_Base_Class */
5278
+			$id = $base_class_obj_or_id->ID();
5279
+		} elseif (is_int($base_class_obj_or_id)) {
5280
+			//assume it's an ID
5281
+			$id = $base_class_obj_or_id;
5282
+		} elseif (is_string($base_class_obj_or_id)) {
5283
+			//assume its a string representation of the object
5284
+			$id = $base_class_obj_or_id;
5285
+		} else {
5286
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5287
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5288
+				print_r($base_class_obj_or_id, true)));
5289
+		}
5290
+		return $id;
5291
+	}
5292
+
5293
+
5294
+
5295
+	/**
5296
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5297
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5298
+	 * been sanitized and converted into the appropriate domain.
5299
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5300
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5301
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5302
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5303
+	 * $EVT = EEM_Event::instance(); $old_setting =
5304
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5305
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5306
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5307
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5308
+	 *
5309
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5310
+	 * @return void
5311
+	 */
5312
+	public function assume_values_already_prepared_by_model_object(
5313
+		$values_already_prepared = self::not_prepared_by_model_object
5314
+	) {
5315
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5316
+	}
5317
+
5318
+
5319
+
5320
+	/**
5321
+	 * Read comments for assume_values_already_prepared_by_model_object()
5322
+	 *
5323
+	 * @return int
5324
+	 */
5325
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5326
+	{
5327
+		return $this->_values_already_prepared_by_model_object;
5328
+	}
5329
+
5330
+
5331
+
5332
+	/**
5333
+	 * Gets all the indexes on this model
5334
+	 *
5335
+	 * @return EE_Index[]
5336
+	 */
5337
+	public function indexes()
5338
+	{
5339
+		return $this->_indexes;
5340
+	}
5341
+
5342
+
5343
+
5344
+	/**
5345
+	 * Gets all the Unique Indexes on this model
5346
+	 *
5347
+	 * @return EE_Unique_Index[]
5348
+	 */
5349
+	public function unique_indexes()
5350
+	{
5351
+		$unique_indexes = array();
5352
+		foreach ($this->_indexes as $name => $index) {
5353
+			if ($index instanceof EE_Unique_Index) {
5354
+				$unique_indexes [$name] = $index;
5355
+			}
5356
+		}
5357
+		return $unique_indexes;
5358
+	}
5359
+
5360
+
5361
+
5362
+	/**
5363
+	 * Gets all the fields which, when combined, make the primary key.
5364
+	 * This is usually just an array with 1 element (the primary key), but in cases
5365
+	 * where there is no primary key, it's a combination of fields as defined
5366
+	 * on a primary index
5367
+	 *
5368
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5369
+	 * @throws \EE_Error
5370
+	 */
5371
+	public function get_combined_primary_key_fields()
5372
+	{
5373
+		foreach ($this->indexes() as $index) {
5374
+			if ($index instanceof EE_Primary_Key_Index) {
5375
+				return $index->fields();
5376
+			}
5377
+		}
5378
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5379
+	}
5380
+
5381
+
5382
+
5383
+	/**
5384
+	 * Used to build a primary key string (when the model has no primary key),
5385
+	 * which can be used a unique string to identify this model object.
5386
+	 *
5387
+	 * @param array $cols_n_values keys are field names, values are their values
5388
+	 * @return string
5389
+	 * @throws \EE_Error
5390
+	 */
5391
+	public function get_index_primary_key_string($cols_n_values)
5392
+	{
5393
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5394
+			$this->get_combined_primary_key_fields());
5395
+		return http_build_query($cols_n_values_for_primary_key_index);
5396
+	}
5397
+
5398
+
5399
+
5400
+	/**
5401
+	 * Gets the field values from the primary key string
5402
+	 *
5403
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5404
+	 * @param string $index_primary_key_string
5405
+	 * @return null|array
5406
+	 * @throws \EE_Error
5407
+	 */
5408
+	public function parse_index_primary_key_string($index_primary_key_string)
5409
+	{
5410
+		$key_fields = $this->get_combined_primary_key_fields();
5411
+		//check all of them are in the $id
5412
+		$key_vals_in_combined_pk = array();
5413
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5414
+		foreach ($key_fields as $key_field_name => $field_obj) {
5415
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5416
+				return null;
5417
+			}
5418
+		}
5419
+		return $key_vals_in_combined_pk;
5420
+	}
5421
+
5422
+
5423
+
5424
+	/**
5425
+	 * verifies that an array of key-value pairs for model fields has a key
5426
+	 * for each field comprising the primary key index
5427
+	 *
5428
+	 * @param array $key_vals
5429
+	 * @return boolean
5430
+	 * @throws \EE_Error
5431
+	 */
5432
+	public function has_all_combined_primary_key_fields($key_vals)
5433
+	{
5434
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5435
+		foreach ($keys_it_should_have as $key) {
5436
+			if (! isset($key_vals[$key])) {
5437
+				return false;
5438
+			}
5439
+		}
5440
+		return true;
5441
+	}
5442
+
5443
+
5444
+
5445
+	/**
5446
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5447
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5448
+	 *
5449
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5450
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5451
+	 * @throws EE_Error
5452
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5453
+	 *                                                              indexed)
5454
+	 */
5455
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5456
+	{
5457
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5458
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5459
+		} elseif (is_array($model_object_or_attributes_array)) {
5460
+			$attributes_array = $model_object_or_attributes_array;
5461
+		} else {
5462
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5463
+				"event_espresso"), $model_object_or_attributes_array));
5464
+		}
5465
+		//even copies obviously won't have the same ID, so remove the primary key
5466
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5467
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5468
+			unset($attributes_array[$this->primary_key_name()]);
5469
+		}
5470
+		if (isset($query_params[0])) {
5471
+			$query_params[0] = array_merge($attributes_array, $query_params);
5472
+		} else {
5473
+			$query_params[0] = $attributes_array;
5474
+		}
5475
+		return $this->get_all($query_params);
5476
+	}
5477
+
5478
+
5479
+
5480
+	/**
5481
+	 * Gets the first copy we find. See get_all_copies for more details
5482
+	 *
5483
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5484
+	 * @param array $query_params
5485
+	 * @return EE_Base_Class
5486
+	 * @throws \EE_Error
5487
+	 */
5488
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5489
+	{
5490
+		if (! is_array($query_params)) {
5491
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5492
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5493
+					gettype($query_params)), '4.6.0');
5494
+			$query_params = array();
5495
+		}
5496
+		$query_params['limit'] = 1;
5497
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5498
+		if (is_array($copies)) {
5499
+			return array_shift($copies);
5500
+		} else {
5501
+			return null;
5502
+		}
5503
+	}
5504
+
5505
+
5506
+
5507
+	/**
5508
+	 * Updates the item with the specified id. Ignores default query parameters because
5509
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5510
+	 *
5511
+	 * @param array      $fields_n_values keys are field names, values are their new values
5512
+	 * @param int|string $id              the value of the primary key to update
5513
+	 * @return int number of rows updated
5514
+	 * @throws \EE_Error
5515
+	 */
5516
+	public function update_by_ID($fields_n_values, $id)
5517
+	{
5518
+		$query_params = array(
5519
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5520
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5521
+		);
5522
+		return $this->update($fields_n_values, $query_params);
5523
+	}
5524
+
5525
+
5526
+
5527
+	/**
5528
+	 * Changes an operator which was supplied to the models into one usable in SQL
5529
+	 *
5530
+	 * @param string $operator_supplied
5531
+	 * @return string an operator which can be used in SQL
5532
+	 * @throws EE_Error
5533
+	 */
5534
+	private function _prepare_operator_for_sql($operator_supplied)
5535
+	{
5536
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5537
+			: null;
5538
+		if ($sql_operator) {
5539
+			return $sql_operator;
5540
+		} else {
5541
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5542
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5543
+		}
5544
+	}
5545
+
5546
+
5547
+
5548
+	/**
5549
+	 * Gets an array where keys are the primary keys and values are their 'names'
5550
+	 * (as determined by the model object's name() function, which is often overridden)
5551
+	 *
5552
+	 * @param array $query_params like get_all's
5553
+	 * @return string[]
5554
+	 * @throws \EE_Error
5555
+	 */
5556
+	public function get_all_names($query_params = array())
5557
+	{
5558
+		$objs = $this->get_all($query_params);
5559
+		$names = array();
5560
+		foreach ($objs as $obj) {
5561
+			$names[$obj->ID()] = $obj->name();
5562
+		}
5563
+		return $names;
5564
+	}
5565
+
5566
+
5567
+
5568
+	/**
5569
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5570
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5571
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5572
+	 * array_keys() on $model_objects.
5573
+	 *
5574
+	 * @param \EE_Base_Class[] $model_objects
5575
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5576
+	 *                                               in the returned array
5577
+	 * @return array
5578
+	 * @throws \EE_Error
5579
+	 */
5580
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5581
+	{
5582
+		if (! $this->has_primary_key_field()) {
5583
+			if (WP_DEBUG) {
5584
+				EE_Error::add_error(
5585
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5586
+					__FILE__,
5587
+					__FUNCTION__,
5588
+					__LINE__
5589
+				);
5590
+			}
5591
+		}
5592
+		$IDs = array();
5593
+		foreach ($model_objects as $model_object) {
5594
+			$id = $model_object->ID();
5595
+			if (! $id) {
5596
+				if ($filter_out_empty_ids) {
5597
+					continue;
5598
+				}
5599
+				if (WP_DEBUG) {
5600
+					EE_Error::add_error(
5601
+						__(
5602
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5603
+							'event_espresso'
5604
+						),
5605
+						__FILE__,
5606
+						__FUNCTION__,
5607
+						__LINE__
5608
+					);
5609
+				}
5610
+			}
5611
+			$IDs[] = $id;
5612
+		}
5613
+		return $IDs;
5614
+	}
5615
+
5616
+
5617
+
5618
+	/**
5619
+	 * Returns the string used in capabilities relating to this model. If there
5620
+	 * are no capabilities that relate to this model returns false
5621
+	 *
5622
+	 * @return string|false
5623
+	 */
5624
+	public function cap_slug()
5625
+	{
5626
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5627
+	}
5628
+
5629
+
5630
+
5631
+	/**
5632
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5633
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5634
+	 * only returns the cap restrictions array in that context (ie, the array
5635
+	 * at that key)
5636
+	 *
5637
+	 * @param string $context
5638
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5639
+	 * @throws \EE_Error
5640
+	 */
5641
+	public function cap_restrictions($context = EEM_Base::caps_read)
5642
+	{
5643
+		EEM_Base::verify_is_valid_cap_context($context);
5644
+		//check if we ought to run the restriction generator first
5645
+		if (
5646
+			isset($this->_cap_restriction_generators[$context])
5647
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5648
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5649
+		) {
5650
+			$this->_cap_restrictions[$context] = array_merge(
5651
+				$this->_cap_restrictions[$context],
5652
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5653
+			);
5654
+		}
5655
+		//and make sure we've finalized the construction of each restriction
5656
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5657
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5658
+				$where_conditions_obj->_finalize_construct($this);
5659
+			}
5660
+		}
5661
+		return $this->_cap_restrictions[$context];
5662
+	}
5663
+
5664
+
5665
+
5666
+	/**
5667
+	 * Indicating whether or not this model thinks its a wp core model
5668
+	 *
5669
+	 * @return boolean
5670
+	 */
5671
+	public function is_wp_core_model()
5672
+	{
5673
+		return $this->_wp_core_model;
5674
+	}
5675
+
5676
+
5677
+
5678
+	/**
5679
+	 * Gets all the caps that are missing which impose a restriction on
5680
+	 * queries made in this context
5681
+	 *
5682
+	 * @param string $context one of EEM_Base::caps_ constants
5683
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5684
+	 * @throws \EE_Error
5685
+	 */
5686
+	public function caps_missing($context = EEM_Base::caps_read)
5687
+	{
5688
+		$missing_caps = array();
5689
+		$cap_restrictions = $this->cap_restrictions($context);
5690
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5691
+			if (! EE_Capabilities::instance()
5692
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5693
+			) {
5694
+				$missing_caps[$cap] = $restriction_if_no_cap;
5695
+			}
5696
+		}
5697
+		return $missing_caps;
5698
+	}
5699
+
5700
+
5701
+
5702
+	/**
5703
+	 * Gets the mapping from capability contexts to action strings used in capability names
5704
+	 *
5705
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5706
+	 * one of 'read', 'edit', or 'delete'
5707
+	 */
5708
+	public function cap_contexts_to_cap_action_map()
5709
+	{
5710
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5711
+			$this);
5712
+	}
5713
+
5714
+
5715
+
5716
+	/**
5717
+	 * Gets the action string for the specified capability context
5718
+	 *
5719
+	 * @param string $context
5720
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5721
+	 * @throws \EE_Error
5722
+	 */
5723
+	public function cap_action_for_context($context)
5724
+	{
5725
+		$mapping = $this->cap_contexts_to_cap_action_map();
5726
+		if (isset($mapping[$context])) {
5727
+			return $mapping[$context];
5728
+		}
5729
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5730
+			return $action;
5731
+		}
5732
+		throw new EE_Error(
5733
+			sprintf(
5734
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5735
+				$context,
5736
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5737
+			)
5738
+		);
5739
+	}
5740
+
5741
+
5742
+
5743
+	/**
5744
+	 * Returns all the capability contexts which are valid when querying models
5745
+	 *
5746
+	 * @return array
5747
+	 */
5748
+	public static function valid_cap_contexts()
5749
+	{
5750
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5751
+			self::caps_read,
5752
+			self::caps_read_admin,
5753
+			self::caps_edit,
5754
+			self::caps_delete,
5755
+		));
5756
+	}
5757
+
5758
+
5759
+
5760
+	/**
5761
+	 * Returns all valid options for 'default_where_conditions'
5762
+	 *
5763
+	 * @return array
5764
+	 */
5765
+	public static function valid_default_where_conditions()
5766
+	{
5767
+		return array(
5768
+			EEM_Base::default_where_conditions_all,
5769
+			EEM_Base::default_where_conditions_this_only,
5770
+			EEM_Base::default_where_conditions_others_only,
5771
+			EEM_Base::default_where_conditions_minimum_all,
5772
+			EEM_Base::default_where_conditions_minimum_others,
5773
+			EEM_Base::default_where_conditions_none
5774
+		);
5775
+	}
5776
+
5777
+	// public static function default_where_conditions_full
5778
+	/**
5779
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5780
+	 *
5781
+	 * @param string $context
5782
+	 * @return bool
5783
+	 * @throws \EE_Error
5784
+	 */
5785
+	static public function verify_is_valid_cap_context($context)
5786
+	{
5787
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5788
+		if (in_array($context, $valid_cap_contexts)) {
5789
+			return true;
5790
+		} else {
5791
+			throw new EE_Error(
5792
+				sprintf(
5793
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5794
+						'event_espresso'),
5795
+					$context,
5796
+					'EEM_Base',
5797
+					implode(',', $valid_cap_contexts)
5798
+				)
5799
+			);
5800
+		}
5801
+	}
5802
+
5803
+
5804
+
5805
+	/**
5806
+	 * Clears all the models field caches. This is only useful when a sub-class
5807
+	 * might have added a field or something and these caches might be invalidated
5808
+	 */
5809
+	protected function _invalidate_field_caches()
5810
+	{
5811
+		$this->_cache_foreign_key_to_fields = array();
5812
+		$this->_cached_fields = null;
5813
+		$this->_cached_fields_non_db_only = null;
5814
+	}
5815
+
5816
+
5817
+
5818
+	/**
5819
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5820
+	 * (eg "and", "or", "not").
5821
+	 *
5822
+	 * @return array
5823
+	 */
5824
+	public function logic_query_param_keys()
5825
+	{
5826
+		return $this->_logic_query_param_keys;
5827
+	}
5828
+
5829
+
5830
+
5831
+	/**
5832
+	 * Determines whether or not the where query param array key is for a logic query param.
5833
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5834
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5835
+	 *
5836
+	 * @param $query_param_key
5837
+	 * @return bool
5838
+	 */
5839
+	public function is_logic_query_param_key($query_param_key)
5840
+	{
5841
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5842
+			if ($query_param_key === $logic_query_param_key
5843
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5844
+			) {
5845
+				return true;
5846
+			}
5847
+		}
5848
+		return false;
5849
+	}
5850 5850
 
5851 5851
 
5852 5852
 
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 1 patch
Indentation   +745 added lines, -745 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\interfaces\ResettableInterface;
2 2
 
3 3
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 EE_Registry::instance()->load_class('Processor_Base');
7 7
 
@@ -18,748 +18,748 @@  discard block
 block discarded – undo
18 18
 class EE_Payment_Processor extends EE_Processor_Base implements ResettableInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @var EE_Payment_Processor $_instance
23
-     * @access    private
24
-     */
25
-    private static $_instance;
26
-
27
-
28
-
29
-    /**
30
-     * @singleton method used to instantiate class object
31
-     * @access    public
32
-     * @return EE_Payment_Processor instance
33
-     */
34
-    public static function instance()
35
-    {
36
-        // check if class object is instantiated
37
-        if ( ! self::$_instance instanceof EE_Payment_Processor) {
38
-            self::$_instance = new self();
39
-        }
40
-        return self::$_instance;
41
-    }
42
-
43
-
44
-
45
-    /**
46
-     * @return EE_Payment_Processor
47
-     */
48
-    public static function reset()
49
-    {
50
-        self::$_instance = null;
51
-        return self::instance();
52
-    }
53
-
54
-
55
-
56
-    /**
57
-     *private constructor to prevent direct creation
58
-     *
59
-     * @Constructor
60
-     * @access private
61
-     */
62
-    private function __construct()
63
-    {
64
-        do_action('AHEE__EE_Payment_Processor__construct');
65
-        add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
66
-    }
67
-
68
-
69
-
70
-    /**
71
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction
72
-     * appropriately. Saves the payment that is generated
73
-     *
74
-     * @param EE_Payment_Method    $payment_method
75
-     * @param EE_Transaction       $transaction
76
-     * @param float                $amount       if only part of the transaction is to be paid for, how much.
77
-     *                                           Leave null if payment is for the full amount owing
78
-     * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
79
-     *                                           Receive_form_submission() should have
80
-     *                                           already been called on the billing form
81
-     *                                           (ie, its inputs should have their normalized values set).
82
-     * @param string               $return_url   string used mostly by offsite gateways to specify
83
-     *                                           where to go AFTER the offsite gateway
84
-     * @param string               $method       like 'CART', indicates who the client who called this was
85
-     * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
86
-     * @param boolean              $update_txn   whether or not to call
87
-     *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
88
-     * @param string               $cancel_url   URL to return to if off-site payments are cancelled
89
-     * @return \EE_Payment
90
-     * @throws \EE_Error
91
-     */
92
-    public function process_payment(
93
-        EE_Payment_Method $payment_method,
94
-        EE_Transaction $transaction,
95
-        $amount = null,
96
-        $billing_form = null,
97
-        $return_url = null,
98
-        $method = 'CART',
99
-        $by_admin = false,
100
-        $update_txn = true,
101
-        $cancel_url = ''
102
-    ) {
103
-        if ((float)$amount < 0) {
104
-            throw new EE_Error(
105
-                sprintf(
106
-                    __(
107
-                        'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
108
-                        'event_espresso'
109
-                    ),
110
-                    $amount,
111
-                    $transaction->ID()
112
-                )
113
-            );
114
-        }
115
-        // verify payment method
116
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
117
-        // verify transaction
118
-        EEM_Transaction::instance()->ensure_is_obj($transaction);
119
-        $transaction->set_payment_method_ID($payment_method->ID());
120
-        // verify payment method type
121
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
122
-            $payment = $payment_method->type_obj()->process_payment(
123
-                $transaction,
124
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
125
-                $billing_form,
126
-                $return_url,
127
-                add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
128
-                $method,
129
-                $by_admin
130
-            );
131
-            // check if payment method uses an off-site gateway
132
-            if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
133
-                // don't process payments for off-site gateways yet because no payment has occurred yet
134
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
135
-            }
136
-            return $payment;
137
-        } else {
138
-            EE_Error::add_error(
139
-                sprintf(
140
-                    __('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
141
-                    '<br/>',
142
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
143
-                ), __FILE__, __FUNCTION__, __LINE__
144
-            );
145
-            return null;
146
-        }
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @param EE_Transaction|int $transaction
153
-     * @param EE_Payment_Method  $payment_method
154
-     * @throws EE_Error
155
-     * @return string
156
-     */
157
-    public function get_ipn_url_for_payment_method($transaction, $payment_method)
158
-    {
159
-        /** @type \EE_Transaction $transaction */
160
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
161
-        $primary_reg = $transaction->primary_registration();
162
-        if ( ! $primary_reg instanceof EE_Registration) {
163
-            throw new EE_Error(
164
-                sprintf(
165
-                    __(
166
-                        "Cannot get IPN URL for transaction with ID %d because it has no primary registration",
167
-                        "event_espresso"
168
-                    ),
169
-                    $transaction->ID()
170
-                )
171
-            );
172
-        }
173
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
174
-        $url = add_query_arg(
175
-            array(
176
-                'e_reg_url_link'    => $primary_reg->reg_url_link(),
177
-                'ee_payment_method' => $payment_method->slug(),
178
-            ),
179
-            EE_Registry::instance()->CFG->core->txn_page_url()
180
-        );
181
-        return $url;
182
-    }
183
-
184
-
185
-
186
-    /**
187
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
188
-     * we can easily find what registration the IPN is for and what payment method.
189
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
190
-     * If a payment is found for the IPN info, it is saved.
191
-     *
192
-     * @param array              $_req_data            eg $_REQUEST
193
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
194
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
195
-     * @param boolean            $update_txn           whether or not to call
196
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
197
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
198
-     *                                                 or is processed manually ( false like Mijireh )
199
-     * @throws EE_Error
200
-     * @throws Exception
201
-     * @return EE_Payment
202
-     */
203
-    public function process_ipn(
204
-        $_req_data,
205
-        $transaction = null,
206
-        $payment_method = null,
207
-        $update_txn = true,
208
-        $separate_IPN_request = true
209
-    ) {
210
-        EE_Registry::instance()->load_model('Change_Log');
211
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
212
-        EE_Processor_Base::set_IPN($separate_IPN_request);
213
-        $obj_for_log = null;
214
-        if ($transaction instanceof EE_Transaction) {
215
-            $obj_for_log = $transaction;
216
-            if ($payment_method instanceof EE_Payment_Method) {
217
-                $obj_for_log = EEM_Payment::instance()->get_one(
218
-                    array(
219
-                        array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
220
-                        'order_by' => array('PAY_timestamp' => 'desc'),
221
-                    )
222
-                );
223
-            }
224
-        } else if ($payment_method instanceof EE_Payment) {
225
-            $obj_for_log = $payment_method;
226
-        }
227
-        $log = EEM_Change_Log::instance()->log(
228
-            EEM_Change_Log::type_gateway,
229
-            array('IPN data received' => $_req_data),
230
-            $obj_for_log
231
-        );
232
-        try {
233
-            /**
234
-             * @var EE_Payment $payment
235
-             */
236
-            $payment = null;
237
-            if ($transaction && $payment_method) {
238
-                /** @type EE_Transaction $transaction */
239
-                $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
240
-                /** @type EE_Payment_Method $payment_method */
241
-                $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
242
-                if ($payment_method->type_obj() instanceof EE_PMT_Base) {
243
-                    try {
244
-                        $payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
245
-                        $log->set_object($payment);
246
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
247
-                        EEM_Change_Log::instance()->log(
248
-                            EEM_Change_Log::type_gateway,
249
-                            array(
250
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
251
-                                'current_url' => EEH_URL::current_url(),
252
-                                'payment'     => $e->getPaymentProperties(),
253
-                                'IPN_data'    => $e->getIpnData(),
254
-                            ),
255
-                            $obj_for_log
256
-                        );
257
-                        return $e->getPayment();
258
-                    }
259
-                } else {
260
-                    // not a payment
261
-                    EE_Error::add_error(
262
-                        sprintf(
263
-                            __('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
264
-                            '<br/>',
265
-                            EE_Registry::instance()->CFG->organization->get_pretty('email')
266
-                        ),
267
-                        __FILE__, __FUNCTION__, __LINE__
268
-                    );
269
-                }
270
-            } else {
271
-                //that's actually pretty ok. The IPN just wasn't able
272
-                //to identify which transaction or payment method this was for
273
-                // give all active payment methods a chance to claim it
274
-                $active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
275
-                foreach ($active_payment_methods as $active_payment_method) {
276
-                    try {
277
-                        $payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
278
-                        $payment_method = $active_payment_method;
279
-                        EEM_Change_Log::instance()->log(
280
-                            EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
281
-                        );
282
-                        break;
283
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
284
-                        EEM_Change_Log::instance()->log(
285
-                            EEM_Change_Log::type_gateway,
286
-                            array(
287
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
288
-                                'current_url' => EEH_URL::current_url(),
289
-                                'payment'     => $e->getPaymentProperties(),
290
-                                'IPN_data'    => $e->getIpnData(),
291
-                            ),
292
-                            $obj_for_log
293
-                        );
294
-                        return $e->getPayment();
295
-                    } catch (EE_Error $e) {
296
-                        //that's fine- it apparently couldn't handle the IPN
297
-                    }
298
-                }
299
-            }
300
-            // 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
301
-            if ($payment instanceof EE_Payment) {
302
-                $payment->save();
303
-                //  update the TXN
304
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
305
-            } else {
306
-                //we couldn't find the payment for this IPN... let's try and log at least SOMETHING
307
-                if ($payment_method) {
308
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
309
-                } elseif ($transaction) {
310
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
311
-                }
312
-            }
313
-            return $payment;
314
-        } catch (EE_Error $e) {
315
-            do_action(
316
-                'AHEE__log', __FILE__, __FUNCTION__, sprintf(
317
-                    __('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
318
-                    print_r($transaction, true),
319
-                    print_r($_req_data, true),
320
-                    $e->getMessage()
321
-                )
322
-            );
323
-            throw $e;
324
-        }
325
-    }
326
-
327
-
328
-
329
-    /**
330
-     * Removes any non-printable illegal characters from the input,
331
-     * which might cause a raucous when trying to insert into the database
332
-     *
333
-     * @param  array $request_data
334
-     * @return array
335
-     */
336
-    protected function _remove_unusable_characters_from_array(array $request_data)
337
-    {
338
-        $return_data = array();
339
-        foreach ($request_data as $key => $value) {
340
-            $return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
341
-        }
342
-        return $return_data;
343
-    }
344
-
345
-
346
-
347
-    /**
348
-     * Removes any non-printable illegal characters from the input,
349
-     * which might cause a raucous when trying to insert into the database
350
-     *
351
-     * @param string $request_data
352
-     * @return string
353
-     */
354
-    protected function _remove_unusable_characters($request_data)
355
-    {
356
-        return preg_replace('/[^[:print:]]/', '', $request_data);
357
-    }
358
-
359
-
360
-
361
-    /**
362
-     * Should be called just before displaying the payment attempt results to the user,
363
-     * when the payment attempt has finished. Some payment methods may have special
364
-     * logic to perform here. For example, if process_payment() happens on a special request
365
-     * and then the user is redirected to a page that displays the payment's status, this
366
-     * should be called while loading the page that displays the payment's status. If the user is
367
-     * sent to an offsite payment provider, this should be called upon returning from that offsite payment
368
-     * provider.
369
-     *
370
-     * @param EE_Transaction|int $transaction
371
-     * @param bool               $update_txn whether or not to call
372
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
373
-     * @throws \EE_Error
374
-     * @return EE_Payment
375
-     * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
376
-     *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
377
-     */
378
-    public function finalize_payment_for($transaction, $update_txn = true)
379
-    {
380
-        /** @var $transaction EE_Transaction */
381
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
382
-        $last_payment_method = $transaction->payment_method();
383
-        if ($last_payment_method instanceof EE_Payment_Method) {
384
-            $payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
385
-            $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
386
-            return $payment;
387
-        } else {
388
-            return null;
389
-        }
390
-    }
391
-
392
-
393
-
394
-    /**
395
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
396
-     *
397
-     * @param EE_Payment_Method $payment_method
398
-     * @param EE_Payment        $payment_to_refund
399
-     * @param array             $refund_info
400
-     * @return EE_Payment
401
-     * @throws \EE_Error
402
-     */
403
-    public function process_refund(
404
-        EE_Payment_Method $payment_method,
405
-        EE_Payment $payment_to_refund,
406
-        $refund_info = array()
407
-    ) {
408
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
409
-            $payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
410
-            $this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
411
-        }
412
-        return $payment_to_refund;
413
-    }
414
-
415
-
416
-
417
-    /**
418
-     * This should be called each time there may have been an update to a
419
-     * payment on a transaction (ie, we asked for a payment to process a
420
-     * payment for a transaction, or we told a payment method about an IPN, or
421
-     * we told a payment method to
422
-     * "finalize_payment_for" (a transaction), or we told a payment method to
423
-     * process a refund. This should handle firing the correct hooks to
424
-     * indicate
425
-     * what exactly happened and updating the transaction appropriately). This
426
-     * could be integrated directly into EE_Transaction upon save, but we want
427
-     * this logic to be separate from 'normal' plain-jane saving and updating
428
-     * of transactions and payments, and to be tied to payment processing.
429
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
430
-     * of previous code to decide whether or not to save (because the payment passed into
431
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
432
-     * in which case we only want that payment object for some temporary usage during this request,
433
-     * but we don't want it to be saved).
434
-     *
435
-     * @param EE_Transaction|int $transaction
436
-     * @param EE_Payment         $payment
437
-     * @param boolean            $update_txn
438
-     *                        whether or not to call
439
-     *                        EE_Transaction_Processor::
440
-     *                        update_transaction_and_registrations_after_checkout_or_payment()
441
-     *                        (you can save 1 DB query if you know you're going
442
-     *                        to save it later instead)
443
-     * @param bool               $IPN
444
-     *                        if processing IPNs or other similar payment
445
-     *                        related activities that occur in alternate
446
-     *                        requests than the main one that is processing the
447
-     *                        TXN, then set this to true to check whether the
448
-     *                        TXN is locked before updating
449
-     * @throws \EE_Error
450
-     */
451
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
452
-    {
453
-        $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
454
-        /** @type EE_Transaction $transaction */
455
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
456
-        // can we freely update the TXN at this moment?
457
-        if ($IPN && $transaction->is_locked()) {
458
-            // don't update the transaction at this exact moment
459
-            // because the TXN is active in another request
460
-            EE_Cron_Tasks::schedule_update_transaction_with_payment(
461
-                time(),
462
-                $transaction->ID(),
463
-                $payment->ID()
464
-            );
465
-        } else {
466
-            // verify payment and that it has been saved
467
-            if ($payment instanceof EE_Payment && $payment->ID()) {
468
-                if (
469
-                    $payment->payment_method() instanceof EE_Payment_Method
470
-                    && $payment->payment_method()->type_obj() instanceof EE_PMT_Base
471
-                ) {
472
-                    $payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
473
-                    // update TXN registrations with payment info
474
-                    $this->process_registration_payments($transaction, $payment);
475
-                }
476
-                $do_action = $payment->just_approved()
477
-                    ? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
478
-                    : $do_action;
479
-            } else {
480
-                // send out notifications
481
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
482
-                $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
483
-            }
484
-            if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
485
-                /** @type EE_Transaction_Payments $transaction_payments */
486
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
487
-                // set new value for total paid
488
-                $transaction_payments->calculate_total_payments_and_update_status($transaction);
489
-                // call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
490
-                if ($update_txn) {
491
-                    $this->_post_payment_processing($transaction, $payment, $IPN);
492
-                }
493
-            }
494
-            // granular hook for others to use.
495
-            do_action($do_action, $transaction, $payment);
496
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
497
-            //global hook for others to use.
498
-            do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
499
-        }
500
-    }
501
-
502
-
503
-
504
-    /**
505
-     * update registrations REG_paid field after successful payment and link registrations with payment
506
-     *
507
-     * @param EE_Transaction    $transaction
508
-     * @param EE_Payment        $payment
509
-     * @param EE_Registration[] $registrations
510
-     * @throws \EE_Error
511
-     */
512
-    public function process_registration_payments(
513
-        EE_Transaction $transaction,
514
-        EE_Payment $payment,
515
-        $registrations = array()
516
-    ) {
517
-        // only process if payment was successful
518
-        if ($payment->status() !== EEM_Payment::status_id_approved) {
519
-            return;
520
-        }
521
-        //EEM_Registration::instance()->show_next_x_db_queries();
522
-        if (empty($registrations)) {
523
-            // find registrations with monies owing that can receive a payment
524
-            $registrations = $transaction->registrations(
525
-                array(
526
-                    array(
527
-                        // only these reg statuses can receive payments
528
-                        'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
529
-                        'REG_final_price'  => array('!=', 0),
530
-                        'REG_final_price*' => array('!=', 'REG_paid', true),
531
-                    ),
532
-                )
533
-            );
534
-        }
535
-        // still nothing ??!??
536
-        if (empty($registrations)) {
537
-            return;
538
-        }
539
-        // todo: break out the following logic into a separate strategy class
540
-        // todo: named something like "Sequential_Reg_Payment_Strategy"
541
-        // todo: which would apply payments using the capitalist "first come first paid" approach
542
-        // todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
543
-        // todo: which would be the socialist "everybody gets a piece of pie" approach,
544
-        // todo: which would be better for deposits, where you want a bit of the payment applied to each registration
545
-        $refund = $payment->is_a_refund();
546
-        // how much is available to apply to registrations?
547
-        $available_payment_amount = abs($payment->amount());
548
-        foreach ($registrations as $registration) {
549
-            if ($registration instanceof EE_Registration) {
550
-                // nothing left?
551
-                if ($available_payment_amount <= 0) {
552
-                    break;
553
-                }
554
-                if ($refund) {
555
-                    $available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
556
-                } else {
557
-                    $available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
558
-                }
559
-            }
560
-        }
561
-        if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
562
-            EE_Error::add_attention(
563
-                sprintf(
564
-                    __('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
565
-                        'event_espresso'),
566
-                    EEH_Template::format_currency($available_payment_amount),
567
-                    implode(', ', array_keys($registrations)),
568
-                    '<br/>',
569
-                    EEH_Template::format_currency($payment->amount())
570
-                ),
571
-                __FILE__, __FUNCTION__, __LINE__
572
-            );
573
-        }
574
-    }
575
-
576
-
577
-
578
-    /**
579
-     * update registration REG_paid field after successful payment and link registration with payment
580
-     *
581
-     * @param EE_Registration $registration
582
-     * @param EE_Payment      $payment
583
-     * @param float           $available_payment_amount
584
-     * @return float
585
-     * @throws \EE_Error
586
-     */
587
-    public function process_registration_payment(
588
-        EE_Registration $registration,
589
-        EE_Payment $payment,
590
-        $available_payment_amount = 0.00
591
-    ) {
592
-        $owing = $registration->final_price() - $registration->paid();
593
-        if ($owing > 0) {
594
-            // don't allow payment amount to exceed the available payment amount, OR the amount owing
595
-            $payment_amount = min($available_payment_amount, $owing);
596
-            // update $available_payment_amount
597
-            $available_payment_amount -= $payment_amount;
598
-            //calculate and set new REG_paid
599
-            $registration->set_paid($registration->paid() + $payment_amount);
600
-            // now save it
601
-            $this->_apply_registration_payment($registration, $payment, $payment_amount);
602
-        }
603
-        return $available_payment_amount;
604
-    }
605
-
606
-
607
-
608
-    /**
609
-     * update registration REG_paid field after successful payment and link registration with payment
610
-     *
611
-     * @param EE_Registration $registration
612
-     * @param EE_Payment      $payment
613
-     * @param float           $payment_amount
614
-     * @return void
615
-     * @throws \EE_Error
616
-     */
617
-    protected function _apply_registration_payment(
618
-        EE_Registration $registration,
619
-        EE_Payment $payment,
620
-        $payment_amount = 0.00
621
-    ) {
622
-        // find any existing reg payment records for this registration and payment
623
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
624
-            array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
625
-        );
626
-        // if existing registration payment exists
627
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
628
-            // then update that record
629
-            $existing_reg_payment->set_amount($payment_amount);
630
-            $existing_reg_payment->save();
631
-        } else {
632
-            // or add new relation between registration and payment and set amount
633
-            $registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
634
-            // make it stick
635
-            $registration->save();
636
-        }
637
-    }
638
-
639
-
640
-
641
-    /**
642
-     * update registration REG_paid field after refund and link registration with payment
643
-     *
644
-     * @param EE_Registration $registration
645
-     * @param EE_Payment      $payment
646
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
647
-     * @return float
648
-     * @throws \EE_Error
649
-     */
650
-    public function process_registration_refund(
651
-        EE_Registration $registration,
652
-        EE_Payment $payment,
653
-        $available_refund_amount = 0.00
654
-    ) {
655
-        //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
656
-        if ($registration->paid() > 0) {
657
-            // ensure $available_refund_amount is NOT negative
658
-            $available_refund_amount = (float)abs($available_refund_amount);
659
-            // don't allow refund amount to exceed the available payment amount, OR the amount paid
660
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
661
-            // update $available_payment_amount
662
-            $available_refund_amount -= $refund_amount;
663
-            //calculate and set new REG_paid
664
-            $registration->set_paid($registration->paid() - $refund_amount);
665
-            // convert payment amount back to a negative value for storage in the db
666
-            $refund_amount = (float)abs($refund_amount) * -1;
667
-            // now save it
668
-            $this->_apply_registration_payment($registration, $payment, $refund_amount);
669
-        }
670
-        return $available_refund_amount;
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * Process payments and transaction after payment process completed.
677
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
678
-     * if this request happens to be processing an IPN,
679
-     * then we will also set the Payment Options Reg Step to completed,
680
-     * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
681
-     *
682
-     * @param EE_Transaction $transaction
683
-     * @param EE_Payment     $payment
684
-     * @param bool           $IPN
685
-     * @throws \EE_Error
686
-     */
687
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
688
-    {
689
-        /** @type EE_Transaction_Processor $transaction_processor */
690
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
691
-        // is the Payment Options Reg Step completed ?
692
-        $payment_options_step_completed = $transaction->reg_step_completed('payment_options');
693
-        // if the Payment Options Reg Step is completed...
694
-        $revisit = $payment_options_step_completed === true ? true : false;
695
-        // then this is kinda sorta a revisit with regards to payments at least
696
-        $transaction_processor->set_revisit($revisit);
697
-        // if this is an IPN, let's consider the Payment Options Reg Step completed if not already
698
-        if (
699
-            $IPN
700
-            && $payment_options_step_completed !== true
701
-            && ($payment->is_approved() || $payment->is_pending())
702
-        ) {
703
-            $payment_options_step_completed = $transaction->set_reg_step_completed(
704
-                'payment_options'
705
-            );
706
-        }
707
-        // maybe update status, but don't save transaction just yet
708
-        $transaction->update_status_based_on_total_paid(false);
709
-        // check if 'finalize_registration' step has been completed...
710
-        $finalized = $transaction->reg_step_completed('finalize_registration');
711
-        //  if this is an IPN and the final step has not been initiated
712
-        if ($IPN && $payment_options_step_completed && $finalized === false) {
713
-            // and if it hasn't already been set as being started...
714
-            $finalized = $transaction->set_reg_step_initiated('finalize_registration');
715
-        }
716
-        $transaction->save();
717
-        // because the above will return false if the final step was not fully completed, we need to check again...
718
-        if ($IPN && $finalized !== false) {
719
-            // and if we are all good to go, then send out notifications
720
-            add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
721
-            //ok, now process the transaction according to the payment
722
-            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
723
-        }
724
-        // DEBUG LOG
725
-        $payment_method = $payment->payment_method();
726
-        if ($payment_method instanceof EE_Payment_Method) {
727
-            $payment_method_type_obj = $payment_method->type_obj();
728
-            if ($payment_method_type_obj instanceof EE_PMT_Base) {
729
-                $gateway = $payment_method_type_obj->get_gateway();
730
-                if ($gateway instanceof EE_Gateway) {
731
-                    $gateway->log(
732
-                        array(
733
-                            'message'               => __('Post Payment Transaction Details', 'event_espresso'),
734
-                            'transaction'           => $transaction->model_field_array(),
735
-                            'finalized'             => $finalized,
736
-                            'IPN'                   => $IPN,
737
-                            'deliver_notifications' => has_filter(
738
-                                'FHEE__EED_Messages___maybe_registration__deliver_notifications'
739
-                            ),
740
-                        ),
741
-                        $payment
742
-                    );
743
-                }
744
-            }
745
-        }
746
-    }
747
-
748
-
749
-
750
-    /**
751
-     * Force posts to PayPal to use TLS v1.2. See:
752
-     * https://core.trac.wordpress.org/ticket/36320
753
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
754
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
755
-     * This will affect paypal standard, pro, express, and payflow.
756
-     */
757
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
758
-    {
759
-        if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
760
-            //Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
761
-            //instead of the constant because it might not be defined
762
-            curl_setopt($handle, CURLOPT_SSLVERSION, 1);
763
-        }
764
-    }
21
+	/**
22
+	 * @var EE_Payment_Processor $_instance
23
+	 * @access    private
24
+	 */
25
+	private static $_instance;
26
+
27
+
28
+
29
+	/**
30
+	 * @singleton method used to instantiate class object
31
+	 * @access    public
32
+	 * @return EE_Payment_Processor instance
33
+	 */
34
+	public static function instance()
35
+	{
36
+		// check if class object is instantiated
37
+		if ( ! self::$_instance instanceof EE_Payment_Processor) {
38
+			self::$_instance = new self();
39
+		}
40
+		return self::$_instance;
41
+	}
42
+
43
+
44
+
45
+	/**
46
+	 * @return EE_Payment_Processor
47
+	 */
48
+	public static function reset()
49
+	{
50
+		self::$_instance = null;
51
+		return self::instance();
52
+	}
53
+
54
+
55
+
56
+	/**
57
+	 *private constructor to prevent direct creation
58
+	 *
59
+	 * @Constructor
60
+	 * @access private
61
+	 */
62
+	private function __construct()
63
+	{
64
+		do_action('AHEE__EE_Payment_Processor__construct');
65
+		add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
66
+	}
67
+
68
+
69
+
70
+	/**
71
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction
72
+	 * appropriately. Saves the payment that is generated
73
+	 *
74
+	 * @param EE_Payment_Method    $payment_method
75
+	 * @param EE_Transaction       $transaction
76
+	 * @param float                $amount       if only part of the transaction is to be paid for, how much.
77
+	 *                                           Leave null if payment is for the full amount owing
78
+	 * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
79
+	 *                                           Receive_form_submission() should have
80
+	 *                                           already been called on the billing form
81
+	 *                                           (ie, its inputs should have their normalized values set).
82
+	 * @param string               $return_url   string used mostly by offsite gateways to specify
83
+	 *                                           where to go AFTER the offsite gateway
84
+	 * @param string               $method       like 'CART', indicates who the client who called this was
85
+	 * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
86
+	 * @param boolean              $update_txn   whether or not to call
87
+	 *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
88
+	 * @param string               $cancel_url   URL to return to if off-site payments are cancelled
89
+	 * @return \EE_Payment
90
+	 * @throws \EE_Error
91
+	 */
92
+	public function process_payment(
93
+		EE_Payment_Method $payment_method,
94
+		EE_Transaction $transaction,
95
+		$amount = null,
96
+		$billing_form = null,
97
+		$return_url = null,
98
+		$method = 'CART',
99
+		$by_admin = false,
100
+		$update_txn = true,
101
+		$cancel_url = ''
102
+	) {
103
+		if ((float)$amount < 0) {
104
+			throw new EE_Error(
105
+				sprintf(
106
+					__(
107
+						'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
108
+						'event_espresso'
109
+					),
110
+					$amount,
111
+					$transaction->ID()
112
+				)
113
+			);
114
+		}
115
+		// verify payment method
116
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
117
+		// verify transaction
118
+		EEM_Transaction::instance()->ensure_is_obj($transaction);
119
+		$transaction->set_payment_method_ID($payment_method->ID());
120
+		// verify payment method type
121
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
122
+			$payment = $payment_method->type_obj()->process_payment(
123
+				$transaction,
124
+				min($amount, $transaction->remaining()),//make sure we don't overcharge
125
+				$billing_form,
126
+				$return_url,
127
+				add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
128
+				$method,
129
+				$by_admin
130
+			);
131
+			// check if payment method uses an off-site gateway
132
+			if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
133
+				// don't process payments for off-site gateways yet because no payment has occurred yet
134
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
135
+			}
136
+			return $payment;
137
+		} else {
138
+			EE_Error::add_error(
139
+				sprintf(
140
+					__('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
141
+					'<br/>',
142
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
143
+				), __FILE__, __FUNCTION__, __LINE__
144
+			);
145
+			return null;
146
+		}
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @param EE_Transaction|int $transaction
153
+	 * @param EE_Payment_Method  $payment_method
154
+	 * @throws EE_Error
155
+	 * @return string
156
+	 */
157
+	public function get_ipn_url_for_payment_method($transaction, $payment_method)
158
+	{
159
+		/** @type \EE_Transaction $transaction */
160
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
161
+		$primary_reg = $transaction->primary_registration();
162
+		if ( ! $primary_reg instanceof EE_Registration) {
163
+			throw new EE_Error(
164
+				sprintf(
165
+					__(
166
+						"Cannot get IPN URL for transaction with ID %d because it has no primary registration",
167
+						"event_espresso"
168
+					),
169
+					$transaction->ID()
170
+				)
171
+			);
172
+		}
173
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
174
+		$url = add_query_arg(
175
+			array(
176
+				'e_reg_url_link'    => $primary_reg->reg_url_link(),
177
+				'ee_payment_method' => $payment_method->slug(),
178
+			),
179
+			EE_Registry::instance()->CFG->core->txn_page_url()
180
+		);
181
+		return $url;
182
+	}
183
+
184
+
185
+
186
+	/**
187
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
188
+	 * we can easily find what registration the IPN is for and what payment method.
189
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
190
+	 * If a payment is found for the IPN info, it is saved.
191
+	 *
192
+	 * @param array              $_req_data            eg $_REQUEST
193
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
194
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
195
+	 * @param boolean            $update_txn           whether or not to call
196
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
197
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
198
+	 *                                                 or is processed manually ( false like Mijireh )
199
+	 * @throws EE_Error
200
+	 * @throws Exception
201
+	 * @return EE_Payment
202
+	 */
203
+	public function process_ipn(
204
+		$_req_data,
205
+		$transaction = null,
206
+		$payment_method = null,
207
+		$update_txn = true,
208
+		$separate_IPN_request = true
209
+	) {
210
+		EE_Registry::instance()->load_model('Change_Log');
211
+		$_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
212
+		EE_Processor_Base::set_IPN($separate_IPN_request);
213
+		$obj_for_log = null;
214
+		if ($transaction instanceof EE_Transaction) {
215
+			$obj_for_log = $transaction;
216
+			if ($payment_method instanceof EE_Payment_Method) {
217
+				$obj_for_log = EEM_Payment::instance()->get_one(
218
+					array(
219
+						array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
220
+						'order_by' => array('PAY_timestamp' => 'desc'),
221
+					)
222
+				);
223
+			}
224
+		} else if ($payment_method instanceof EE_Payment) {
225
+			$obj_for_log = $payment_method;
226
+		}
227
+		$log = EEM_Change_Log::instance()->log(
228
+			EEM_Change_Log::type_gateway,
229
+			array('IPN data received' => $_req_data),
230
+			$obj_for_log
231
+		);
232
+		try {
233
+			/**
234
+			 * @var EE_Payment $payment
235
+			 */
236
+			$payment = null;
237
+			if ($transaction && $payment_method) {
238
+				/** @type EE_Transaction $transaction */
239
+				$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
240
+				/** @type EE_Payment_Method $payment_method */
241
+				$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
242
+				if ($payment_method->type_obj() instanceof EE_PMT_Base) {
243
+					try {
244
+						$payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
245
+						$log->set_object($payment);
246
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
247
+						EEM_Change_Log::instance()->log(
248
+							EEM_Change_Log::type_gateway,
249
+							array(
250
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
251
+								'current_url' => EEH_URL::current_url(),
252
+								'payment'     => $e->getPaymentProperties(),
253
+								'IPN_data'    => $e->getIpnData(),
254
+							),
255
+							$obj_for_log
256
+						);
257
+						return $e->getPayment();
258
+					}
259
+				} else {
260
+					// not a payment
261
+					EE_Error::add_error(
262
+						sprintf(
263
+							__('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
264
+							'<br/>',
265
+							EE_Registry::instance()->CFG->organization->get_pretty('email')
266
+						),
267
+						__FILE__, __FUNCTION__, __LINE__
268
+					);
269
+				}
270
+			} else {
271
+				//that's actually pretty ok. The IPN just wasn't able
272
+				//to identify which transaction or payment method this was for
273
+				// give all active payment methods a chance to claim it
274
+				$active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
275
+				foreach ($active_payment_methods as $active_payment_method) {
276
+					try {
277
+						$payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
278
+						$payment_method = $active_payment_method;
279
+						EEM_Change_Log::instance()->log(
280
+							EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
281
+						);
282
+						break;
283
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
284
+						EEM_Change_Log::instance()->log(
285
+							EEM_Change_Log::type_gateway,
286
+							array(
287
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
288
+								'current_url' => EEH_URL::current_url(),
289
+								'payment'     => $e->getPaymentProperties(),
290
+								'IPN_data'    => $e->getIpnData(),
291
+							),
292
+							$obj_for_log
293
+						);
294
+						return $e->getPayment();
295
+					} catch (EE_Error $e) {
296
+						//that's fine- it apparently couldn't handle the IPN
297
+					}
298
+				}
299
+			}
300
+			// 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
301
+			if ($payment instanceof EE_Payment) {
302
+				$payment->save();
303
+				//  update the TXN
304
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
305
+			} else {
306
+				//we couldn't find the payment for this IPN... let's try and log at least SOMETHING
307
+				if ($payment_method) {
308
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
309
+				} elseif ($transaction) {
310
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
311
+				}
312
+			}
313
+			return $payment;
314
+		} catch (EE_Error $e) {
315
+			do_action(
316
+				'AHEE__log', __FILE__, __FUNCTION__, sprintf(
317
+					__('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
318
+					print_r($transaction, true),
319
+					print_r($_req_data, true),
320
+					$e->getMessage()
321
+				)
322
+			);
323
+			throw $e;
324
+		}
325
+	}
326
+
327
+
328
+
329
+	/**
330
+	 * Removes any non-printable illegal characters from the input,
331
+	 * which might cause a raucous when trying to insert into the database
332
+	 *
333
+	 * @param  array $request_data
334
+	 * @return array
335
+	 */
336
+	protected function _remove_unusable_characters_from_array(array $request_data)
337
+	{
338
+		$return_data = array();
339
+		foreach ($request_data as $key => $value) {
340
+			$return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
341
+		}
342
+		return $return_data;
343
+	}
344
+
345
+
346
+
347
+	/**
348
+	 * Removes any non-printable illegal characters from the input,
349
+	 * which might cause a raucous when trying to insert into the database
350
+	 *
351
+	 * @param string $request_data
352
+	 * @return string
353
+	 */
354
+	protected function _remove_unusable_characters($request_data)
355
+	{
356
+		return preg_replace('/[^[:print:]]/', '', $request_data);
357
+	}
358
+
359
+
360
+
361
+	/**
362
+	 * Should be called just before displaying the payment attempt results to the user,
363
+	 * when the payment attempt has finished. Some payment methods may have special
364
+	 * logic to perform here. For example, if process_payment() happens on a special request
365
+	 * and then the user is redirected to a page that displays the payment's status, this
366
+	 * should be called while loading the page that displays the payment's status. If the user is
367
+	 * sent to an offsite payment provider, this should be called upon returning from that offsite payment
368
+	 * provider.
369
+	 *
370
+	 * @param EE_Transaction|int $transaction
371
+	 * @param bool               $update_txn whether or not to call
372
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
373
+	 * @throws \EE_Error
374
+	 * @return EE_Payment
375
+	 * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
376
+	 *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
377
+	 */
378
+	public function finalize_payment_for($transaction, $update_txn = true)
379
+	{
380
+		/** @var $transaction EE_Transaction */
381
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
382
+		$last_payment_method = $transaction->payment_method();
383
+		if ($last_payment_method instanceof EE_Payment_Method) {
384
+			$payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
385
+			$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
386
+			return $payment;
387
+		} else {
388
+			return null;
389
+		}
390
+	}
391
+
392
+
393
+
394
+	/**
395
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
396
+	 *
397
+	 * @param EE_Payment_Method $payment_method
398
+	 * @param EE_Payment        $payment_to_refund
399
+	 * @param array             $refund_info
400
+	 * @return EE_Payment
401
+	 * @throws \EE_Error
402
+	 */
403
+	public function process_refund(
404
+		EE_Payment_Method $payment_method,
405
+		EE_Payment $payment_to_refund,
406
+		$refund_info = array()
407
+	) {
408
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
409
+			$payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
410
+			$this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
411
+		}
412
+		return $payment_to_refund;
413
+	}
414
+
415
+
416
+
417
+	/**
418
+	 * This should be called each time there may have been an update to a
419
+	 * payment on a transaction (ie, we asked for a payment to process a
420
+	 * payment for a transaction, or we told a payment method about an IPN, or
421
+	 * we told a payment method to
422
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
423
+	 * process a refund. This should handle firing the correct hooks to
424
+	 * indicate
425
+	 * what exactly happened and updating the transaction appropriately). This
426
+	 * could be integrated directly into EE_Transaction upon save, but we want
427
+	 * this logic to be separate from 'normal' plain-jane saving and updating
428
+	 * of transactions and payments, and to be tied to payment processing.
429
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
430
+	 * of previous code to decide whether or not to save (because the payment passed into
431
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
432
+	 * in which case we only want that payment object for some temporary usage during this request,
433
+	 * but we don't want it to be saved).
434
+	 *
435
+	 * @param EE_Transaction|int $transaction
436
+	 * @param EE_Payment         $payment
437
+	 * @param boolean            $update_txn
438
+	 *                        whether or not to call
439
+	 *                        EE_Transaction_Processor::
440
+	 *                        update_transaction_and_registrations_after_checkout_or_payment()
441
+	 *                        (you can save 1 DB query if you know you're going
442
+	 *                        to save it later instead)
443
+	 * @param bool               $IPN
444
+	 *                        if processing IPNs or other similar payment
445
+	 *                        related activities that occur in alternate
446
+	 *                        requests than the main one that is processing the
447
+	 *                        TXN, then set this to true to check whether the
448
+	 *                        TXN is locked before updating
449
+	 * @throws \EE_Error
450
+	 */
451
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
452
+	{
453
+		$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
454
+		/** @type EE_Transaction $transaction */
455
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
456
+		// can we freely update the TXN at this moment?
457
+		if ($IPN && $transaction->is_locked()) {
458
+			// don't update the transaction at this exact moment
459
+			// because the TXN is active in another request
460
+			EE_Cron_Tasks::schedule_update_transaction_with_payment(
461
+				time(),
462
+				$transaction->ID(),
463
+				$payment->ID()
464
+			);
465
+		} else {
466
+			// verify payment and that it has been saved
467
+			if ($payment instanceof EE_Payment && $payment->ID()) {
468
+				if (
469
+					$payment->payment_method() instanceof EE_Payment_Method
470
+					&& $payment->payment_method()->type_obj() instanceof EE_PMT_Base
471
+				) {
472
+					$payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
473
+					// update TXN registrations with payment info
474
+					$this->process_registration_payments($transaction, $payment);
475
+				}
476
+				$do_action = $payment->just_approved()
477
+					? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
478
+					: $do_action;
479
+			} else {
480
+				// send out notifications
481
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
482
+				$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
483
+			}
484
+			if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
485
+				/** @type EE_Transaction_Payments $transaction_payments */
486
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
487
+				// set new value for total paid
488
+				$transaction_payments->calculate_total_payments_and_update_status($transaction);
489
+				// call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
490
+				if ($update_txn) {
491
+					$this->_post_payment_processing($transaction, $payment, $IPN);
492
+				}
493
+			}
494
+			// granular hook for others to use.
495
+			do_action($do_action, $transaction, $payment);
496
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
497
+			//global hook for others to use.
498
+			do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
499
+		}
500
+	}
501
+
502
+
503
+
504
+	/**
505
+	 * update registrations REG_paid field after successful payment and link registrations with payment
506
+	 *
507
+	 * @param EE_Transaction    $transaction
508
+	 * @param EE_Payment        $payment
509
+	 * @param EE_Registration[] $registrations
510
+	 * @throws \EE_Error
511
+	 */
512
+	public function process_registration_payments(
513
+		EE_Transaction $transaction,
514
+		EE_Payment $payment,
515
+		$registrations = array()
516
+	) {
517
+		// only process if payment was successful
518
+		if ($payment->status() !== EEM_Payment::status_id_approved) {
519
+			return;
520
+		}
521
+		//EEM_Registration::instance()->show_next_x_db_queries();
522
+		if (empty($registrations)) {
523
+			// find registrations with monies owing that can receive a payment
524
+			$registrations = $transaction->registrations(
525
+				array(
526
+					array(
527
+						// only these reg statuses can receive payments
528
+						'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
529
+						'REG_final_price'  => array('!=', 0),
530
+						'REG_final_price*' => array('!=', 'REG_paid', true),
531
+					),
532
+				)
533
+			);
534
+		}
535
+		// still nothing ??!??
536
+		if (empty($registrations)) {
537
+			return;
538
+		}
539
+		// todo: break out the following logic into a separate strategy class
540
+		// todo: named something like "Sequential_Reg_Payment_Strategy"
541
+		// todo: which would apply payments using the capitalist "first come first paid" approach
542
+		// todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
543
+		// todo: which would be the socialist "everybody gets a piece of pie" approach,
544
+		// todo: which would be better for deposits, where you want a bit of the payment applied to each registration
545
+		$refund = $payment->is_a_refund();
546
+		// how much is available to apply to registrations?
547
+		$available_payment_amount = abs($payment->amount());
548
+		foreach ($registrations as $registration) {
549
+			if ($registration instanceof EE_Registration) {
550
+				// nothing left?
551
+				if ($available_payment_amount <= 0) {
552
+					break;
553
+				}
554
+				if ($refund) {
555
+					$available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
556
+				} else {
557
+					$available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
558
+				}
559
+			}
560
+		}
561
+		if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
562
+			EE_Error::add_attention(
563
+				sprintf(
564
+					__('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
565
+						'event_espresso'),
566
+					EEH_Template::format_currency($available_payment_amount),
567
+					implode(', ', array_keys($registrations)),
568
+					'<br/>',
569
+					EEH_Template::format_currency($payment->amount())
570
+				),
571
+				__FILE__, __FUNCTION__, __LINE__
572
+			);
573
+		}
574
+	}
575
+
576
+
577
+
578
+	/**
579
+	 * update registration REG_paid field after successful payment and link registration with payment
580
+	 *
581
+	 * @param EE_Registration $registration
582
+	 * @param EE_Payment      $payment
583
+	 * @param float           $available_payment_amount
584
+	 * @return float
585
+	 * @throws \EE_Error
586
+	 */
587
+	public function process_registration_payment(
588
+		EE_Registration $registration,
589
+		EE_Payment $payment,
590
+		$available_payment_amount = 0.00
591
+	) {
592
+		$owing = $registration->final_price() - $registration->paid();
593
+		if ($owing > 0) {
594
+			// don't allow payment amount to exceed the available payment amount, OR the amount owing
595
+			$payment_amount = min($available_payment_amount, $owing);
596
+			// update $available_payment_amount
597
+			$available_payment_amount -= $payment_amount;
598
+			//calculate and set new REG_paid
599
+			$registration->set_paid($registration->paid() + $payment_amount);
600
+			// now save it
601
+			$this->_apply_registration_payment($registration, $payment, $payment_amount);
602
+		}
603
+		return $available_payment_amount;
604
+	}
605
+
606
+
607
+
608
+	/**
609
+	 * update registration REG_paid field after successful payment and link registration with payment
610
+	 *
611
+	 * @param EE_Registration $registration
612
+	 * @param EE_Payment      $payment
613
+	 * @param float           $payment_amount
614
+	 * @return void
615
+	 * @throws \EE_Error
616
+	 */
617
+	protected function _apply_registration_payment(
618
+		EE_Registration $registration,
619
+		EE_Payment $payment,
620
+		$payment_amount = 0.00
621
+	) {
622
+		// find any existing reg payment records for this registration and payment
623
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
624
+			array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
625
+		);
626
+		// if existing registration payment exists
627
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
628
+			// then update that record
629
+			$existing_reg_payment->set_amount($payment_amount);
630
+			$existing_reg_payment->save();
631
+		} else {
632
+			// or add new relation between registration and payment and set amount
633
+			$registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
634
+			// make it stick
635
+			$registration->save();
636
+		}
637
+	}
638
+
639
+
640
+
641
+	/**
642
+	 * update registration REG_paid field after refund and link registration with payment
643
+	 *
644
+	 * @param EE_Registration $registration
645
+	 * @param EE_Payment      $payment
646
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
647
+	 * @return float
648
+	 * @throws \EE_Error
649
+	 */
650
+	public function process_registration_refund(
651
+		EE_Registration $registration,
652
+		EE_Payment $payment,
653
+		$available_refund_amount = 0.00
654
+	) {
655
+		//EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
656
+		if ($registration->paid() > 0) {
657
+			// ensure $available_refund_amount is NOT negative
658
+			$available_refund_amount = (float)abs($available_refund_amount);
659
+			// don't allow refund amount to exceed the available payment amount, OR the amount paid
660
+			$refund_amount = min($available_refund_amount, (float)$registration->paid());
661
+			// update $available_payment_amount
662
+			$available_refund_amount -= $refund_amount;
663
+			//calculate and set new REG_paid
664
+			$registration->set_paid($registration->paid() - $refund_amount);
665
+			// convert payment amount back to a negative value for storage in the db
666
+			$refund_amount = (float)abs($refund_amount) * -1;
667
+			// now save it
668
+			$this->_apply_registration_payment($registration, $payment, $refund_amount);
669
+		}
670
+		return $available_refund_amount;
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * Process payments and transaction after payment process completed.
677
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
678
+	 * if this request happens to be processing an IPN,
679
+	 * then we will also set the Payment Options Reg Step to completed,
680
+	 * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
681
+	 *
682
+	 * @param EE_Transaction $transaction
683
+	 * @param EE_Payment     $payment
684
+	 * @param bool           $IPN
685
+	 * @throws \EE_Error
686
+	 */
687
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
688
+	{
689
+		/** @type EE_Transaction_Processor $transaction_processor */
690
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
691
+		// is the Payment Options Reg Step completed ?
692
+		$payment_options_step_completed = $transaction->reg_step_completed('payment_options');
693
+		// if the Payment Options Reg Step is completed...
694
+		$revisit = $payment_options_step_completed === true ? true : false;
695
+		// then this is kinda sorta a revisit with regards to payments at least
696
+		$transaction_processor->set_revisit($revisit);
697
+		// if this is an IPN, let's consider the Payment Options Reg Step completed if not already
698
+		if (
699
+			$IPN
700
+			&& $payment_options_step_completed !== true
701
+			&& ($payment->is_approved() || $payment->is_pending())
702
+		) {
703
+			$payment_options_step_completed = $transaction->set_reg_step_completed(
704
+				'payment_options'
705
+			);
706
+		}
707
+		// maybe update status, but don't save transaction just yet
708
+		$transaction->update_status_based_on_total_paid(false);
709
+		// check if 'finalize_registration' step has been completed...
710
+		$finalized = $transaction->reg_step_completed('finalize_registration');
711
+		//  if this is an IPN and the final step has not been initiated
712
+		if ($IPN && $payment_options_step_completed && $finalized === false) {
713
+			// and if it hasn't already been set as being started...
714
+			$finalized = $transaction->set_reg_step_initiated('finalize_registration');
715
+		}
716
+		$transaction->save();
717
+		// because the above will return false if the final step was not fully completed, we need to check again...
718
+		if ($IPN && $finalized !== false) {
719
+			// and if we are all good to go, then send out notifications
720
+			add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
721
+			//ok, now process the transaction according to the payment
722
+			$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
723
+		}
724
+		// DEBUG LOG
725
+		$payment_method = $payment->payment_method();
726
+		if ($payment_method instanceof EE_Payment_Method) {
727
+			$payment_method_type_obj = $payment_method->type_obj();
728
+			if ($payment_method_type_obj instanceof EE_PMT_Base) {
729
+				$gateway = $payment_method_type_obj->get_gateway();
730
+				if ($gateway instanceof EE_Gateway) {
731
+					$gateway->log(
732
+						array(
733
+							'message'               => __('Post Payment Transaction Details', 'event_espresso'),
734
+							'transaction'           => $transaction->model_field_array(),
735
+							'finalized'             => $finalized,
736
+							'IPN'                   => $IPN,
737
+							'deliver_notifications' => has_filter(
738
+								'FHEE__EED_Messages___maybe_registration__deliver_notifications'
739
+							),
740
+						),
741
+						$payment
742
+					);
743
+				}
744
+			}
745
+		}
746
+	}
747
+
748
+
749
+
750
+	/**
751
+	 * Force posts to PayPal to use TLS v1.2. See:
752
+	 * https://core.trac.wordpress.org/ticket/36320
753
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
754
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
755
+	 * This will affect paypal standard, pro, express, and payflow.
756
+	 */
757
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
758
+	{
759
+		if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
760
+			//Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
761
+			//instead of the constant because it might not be defined
762
+			curl_setopt($handle, CURLOPT_SSLVERSION, 1);
763
+		}
764
+	}
765 765
 }
Please login to merge, or discard this patch.
core/EE_Bootstrap.core.php 1 patch
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -42,13 +42,13 @@  discard block
 block discarded – undo
42 42
 
43 43
 	public function __construct() {
44 44
 		// construct request stack and run middleware apps as soon as all WP plugins are loaded
45
-		add_action( 'plugins_loaded', array( $this, 'run_request_stack' ), 0 );
45
+		add_action('plugins_loaded', array($this, 'run_request_stack'), 0);
46 46
 		// set framework for the rest of EE to hook into when loading
47
-		add_action( 'plugins_loaded', array( 'EE_Bootstrap', 'load_espresso_addons' ), 1 );
48
-		add_action( 'plugins_loaded', array( 'EE_Bootstrap', 'detect_activations_or_upgrades' ), 3 );
49
-		add_action( 'plugins_loaded', array( 'EE_Bootstrap', 'load_core_configuration' ), 5 );
50
-		add_action( 'plugins_loaded', array( 'EE_Bootstrap', 'register_shortcodes_modules_and_widgets' ), 7 );
51
-		add_action( 'plugins_loaded', array( 'EE_Bootstrap', 'brew_espresso' ), 9 );
47
+		add_action('plugins_loaded', array('EE_Bootstrap', 'load_espresso_addons'), 1);
48
+		add_action('plugins_loaded', array('EE_Bootstrap', 'detect_activations_or_upgrades'), 3);
49
+		add_action('plugins_loaded', array('EE_Bootstrap', 'load_core_configuration'), 5);
50
+		add_action('plugins_loaded', array('EE_Bootstrap', 'register_shortcodes_modules_and_widgets'), 7);
51
+		add_action('plugins_loaded', array('EE_Bootstrap', 'brew_espresso'), 9);
52 52
 	}
53 53
 
54 54
 
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 			new EE_Load_Espresso_Core()
66 66
 		);
67 67
 		$this->_request_stack->handle_request(
68
-			new EE_Request( $_GET, $_POST, $_COOKIE ),
68
+			new EE_Request($_GET, $_POST, $_COOKIE),
69 69
 			new EE_Response()
70 70
 		);
71 71
 		$this->_request_stack->handle_response();
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 	 */
79 79
 	protected function load_autoloader() {
80 80
 		// load interfaces
81
-		espresso_load_required( 'EEH_Autoloader', EE_CORE . 'helpers' . DS . 'EEH_Autoloader.helper.php' );
81
+		espresso_load_required('EEH_Autoloader', EE_CORE.'helpers'.DS.'EEH_Autoloader.helper.php');
82 82
 		EEH_Autoloader::instance();
83 83
 	}
84 84
 
@@ -89,15 +89,15 @@  discard block
 block discarded – undo
89 89
 	 */
90 90
 	protected function set_autoloaders_for_required_files() {
91 91
 		// load interfaces
92
-		espresso_load_required( 'EEI_Interfaces', EE_CORE . 'interfaces' . DS . 'EEI_Interfaces.php' );
93
-		espresso_load_required( 'InterminableInterface', EE_CORE . 'interfaces' . DS . 'InterminableInterface.php' );
94
-		espresso_load_required( 'ResettableInterface', EE_CORE . 'interfaces' . DS . 'ResettableInterface.php' );
92
+		espresso_load_required('EEI_Interfaces', EE_CORE.'interfaces'.DS.'EEI_Interfaces.php');
93
+		espresso_load_required('InterminableInterface', EE_CORE.'interfaces'.DS.'InterminableInterface.php');
94
+		espresso_load_required('ResettableInterface', EE_CORE.'interfaces'.DS.'ResettableInterface.php');
95 95
 		// load helpers
96
-		EEH_Autoloader::register_autoloaders_for_each_file_in_folder( EE_HELPERS );
96
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_HELPERS);
97 97
 		// load request stack
98
-		EEH_Autoloader::register_autoloaders_for_each_file_in_folder( EE_CORE . 'request_stack' . DS );
98
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE.'request_stack'.DS);
99 99
 		// load middleware
100
-		EEH_Autoloader::register_autoloaders_for_each_file_in_folder( EE_CORE . 'middleware' . DS );
100
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE.'middleware'.DS);
101 101
 	}
102 102
 
103 103
 
@@ -118,9 +118,9 @@  discard block
 block discarded – undo
118 118
 			)
119 119
 		);
120 120
 		// load middleware onto stack : FILO (First In Last Out)
121
-		foreach ( (array)$stack_apps as $stack_app ) {
121
+		foreach ((array) $stack_apps as $stack_app) {
122 122
 			//$request_stack_builder->push( $stack_app );
123
-			$request_stack_builder->unshift( $stack_app );
123
+			$request_stack_builder->unshift($stack_app);
124 124
 		}
125 125
 		return apply_filters(
126 126
 			'FHEE__EE_Bootstrap__build_request_stack__request_stack_builder',
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * no other logic should be performed at this point
138 138
 	 */
139 139
 	public static function load_espresso_addons() {
140
-		do_action( 'AHEE__EE_Bootstrap__load_espresso_addons' );
140
+		do_action('AHEE__EE_Bootstrap__load_espresso_addons');
141 141
 	}
142 142
 
143 143
 
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 	 * we can determine if anything needs activating or upgrading
150 150
 	 */
151 151
 	public static function detect_activations_or_upgrades() {
152
-		do_action( 'AHEE__EE_Bootstrap__detect_activations_or_upgrades' );
152
+		do_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades');
153 153
 	}
154 154
 
155 155
 
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 	 * we can load and set all of the system configurations
162 162
 	 */
163 163
 	public static function load_core_configuration() {
164
-		do_action( 'AHEE__EE_Bootstrap__load_core_configuration' );
164
+		do_action('AHEE__EE_Bootstrap__load_core_configuration');
165 165
 	}
166 166
 
167 167
 
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	 * so that they are ready to be used throughout the system
174 174
 	 */
175 175
 	public static function register_shortcodes_modules_and_widgets() {
176
-		do_action( 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets' );
176
+		do_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets');
177 177
 	}
178 178
 
179 179
 
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 	 * so let the fun begin...
186 186
 	 */
187 187
 	public static function brew_espresso() {
188
-		do_action( 'AHEE__EE_Bootstrap__brew_espresso' );
188
+		do_action('AHEE__EE_Bootstrap__brew_espresso');
189 189
 	}
190 190
 
191 191
 
Please login to merge, or discard this patch.
core/EE_Encryption.core.php 1 patch
Unused Use Statements   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@
 block discarded – undo
1
-<?php use EventEspresso\core\interfaces\InterminableInterface;
1
+<?php 
2 2
 
3 3
 defined('EVENT_ESPRESSO_VERSION') || exit('No direct script access allowed');
4 4
 
Please login to merge, or discard this patch.
core/domain/DomainBase.php 2 patches
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -18,132 +18,132 @@
 block discarded – undo
18 18
 abstract class DomainBase
19 19
 {
20 20
 
21
-    /**
22
-     * Equivalent to `__FILE__` for main plugin file.
23
-     *
24
-     * @var string
25
-     */
26
-    private static $plugin_file = '';
27
-
28
-    /**
29
-     * String indicating version for plugin
30
-     *
31
-     * @var string
32
-     */
33
-    private static $version = '';
34
-
35
-    /**
36
-     * @var string $plugin_basename
37
-     */
38
-    private static $plugin_basename = '';
39
-
40
-    /**
41
-     * @var string $plugin_path
42
-     */
43
-    private static $plugin_path = '';
44
-
45
-    /**
46
-     * @var string $plugin_url
47
-     */
48
-    private static $plugin_url = '';
49
-
50
-
51
-
52
-    /**
53
-     * Initializes internal static properties.
54
-     *
55
-     * @param string $plugin_file
56
-     * @param string $version
57
-     */
58
-    public static function init($plugin_file, $version)
59
-    {
60
-        self::$plugin_file = $plugin_file;
61
-        self::$version = $version;
62
-        self::$plugin_basename = plugin_basename($plugin_file);
63
-        self::$plugin_path = plugin_dir_path($plugin_file);
64
-        self::$plugin_url = plugin_dir_url($plugin_file);
65
-    }
66
-
67
-
68
-
69
-    /**
70
-     * @return string
71
-     * @throws DomainException
72
-     */
73
-    public static function pluginFile()
74
-    {
75
-        self::verifyInitialized(__METHOD__);
76
-        return self::$plugin_file;
77
-    }
78
-
79
-
80
-
81
-    /**
82
-     * @return string
83
-     * @throws DomainException
84
-     */
85
-    public static function pluginBasename()
86
-    {
87
-        self::verifyInitialized(__METHOD__);
88
-        return self::$plugin_basename;
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * @return string
95
-     * @throws DomainException
96
-     */
97
-    public static function pluginPath()
98
-    {
99
-        self::verifyInitialized(__METHOD__);
100
-        return self::$plugin_path;
101
-    }
102
-
103
-
104
-
105
-    /**
106
-     * @return string
107
-     * @throws DomainException
108
-     */
109
-    public static function pluginUrl()
110
-    {
111
-        self::verifyInitialized(__METHOD__);
112
-        return self::$plugin_url;
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     * @return string
119
-     * @throws DomainException
120
-     */
121
-    public static function version()
122
-    {
123
-        self::verifyInitialized(__METHOD__);
124
-        return self::$version;
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     * @param string $method
131
-     * @throws DomainException
132
-     */
133
-    private static function verifyInitialized($method)
134
-    {
135
-        if (self::$plugin_file === '') {
136
-            throw new DomainException(
137
-                sprintf(
138
-                    esc_html__(
139
-                        '%1$s needs to be called before %2$s can return a value.',
140
-                        'event_espresso'
141
-                    ),
142
-                    get_called_class() . '::init()',
143
-                    "{$method}()"
144
-                )
145
-            );
146
-        }
147
-    }
21
+	/**
22
+	 * Equivalent to `__FILE__` for main plugin file.
23
+	 *
24
+	 * @var string
25
+	 */
26
+	private static $plugin_file = '';
27
+
28
+	/**
29
+	 * String indicating version for plugin
30
+	 *
31
+	 * @var string
32
+	 */
33
+	private static $version = '';
34
+
35
+	/**
36
+	 * @var string $plugin_basename
37
+	 */
38
+	private static $plugin_basename = '';
39
+
40
+	/**
41
+	 * @var string $plugin_path
42
+	 */
43
+	private static $plugin_path = '';
44
+
45
+	/**
46
+	 * @var string $plugin_url
47
+	 */
48
+	private static $plugin_url = '';
49
+
50
+
51
+
52
+	/**
53
+	 * Initializes internal static properties.
54
+	 *
55
+	 * @param string $plugin_file
56
+	 * @param string $version
57
+	 */
58
+	public static function init($plugin_file, $version)
59
+	{
60
+		self::$plugin_file = $plugin_file;
61
+		self::$version = $version;
62
+		self::$plugin_basename = plugin_basename($plugin_file);
63
+		self::$plugin_path = plugin_dir_path($plugin_file);
64
+		self::$plugin_url = plugin_dir_url($plugin_file);
65
+	}
66
+
67
+
68
+
69
+	/**
70
+	 * @return string
71
+	 * @throws DomainException
72
+	 */
73
+	public static function pluginFile()
74
+	{
75
+		self::verifyInitialized(__METHOD__);
76
+		return self::$plugin_file;
77
+	}
78
+
79
+
80
+
81
+	/**
82
+	 * @return string
83
+	 * @throws DomainException
84
+	 */
85
+	public static function pluginBasename()
86
+	{
87
+		self::verifyInitialized(__METHOD__);
88
+		return self::$plugin_basename;
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * @return string
95
+	 * @throws DomainException
96
+	 */
97
+	public static function pluginPath()
98
+	{
99
+		self::verifyInitialized(__METHOD__);
100
+		return self::$plugin_path;
101
+	}
102
+
103
+
104
+
105
+	/**
106
+	 * @return string
107
+	 * @throws DomainException
108
+	 */
109
+	public static function pluginUrl()
110
+	{
111
+		self::verifyInitialized(__METHOD__);
112
+		return self::$plugin_url;
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 * @return string
119
+	 * @throws DomainException
120
+	 */
121
+	public static function version()
122
+	{
123
+		self::verifyInitialized(__METHOD__);
124
+		return self::$version;
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 * @param string $method
131
+	 * @throws DomainException
132
+	 */
133
+	private static function verifyInitialized($method)
134
+	{
135
+		if (self::$plugin_file === '') {
136
+			throw new DomainException(
137
+				sprintf(
138
+					esc_html__(
139
+						'%1$s needs to be called before %2$s can return a value.',
140
+						'event_espresso'
141
+					),
142
+					get_called_class() . '::init()',
143
+					"{$method}()"
144
+				)
145
+			);
146
+		}
147
+	}
148 148
 
149 149
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -139,7 +139,7 @@
 block discarded – undo
139 139
                         '%1$s needs to be called before %2$s can return a value.',
140 140
                         'event_espresso'
141 141
                     ),
142
-                    get_called_class() . '::init()',
142
+                    get_called_class().'::init()',
143 143
                     "{$method}()"
144 144
                 )
145 145
             );
Please login to merge, or discard this patch.