Completed
Branch FET/4986/11317/order-by-count (32a2c9)
by
unknown
48:26 queued 35:38
created
caffeinated/brewing_regular.php 2 patches
Indentation   +260 added lines, -260 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,268 +29,268 @@  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
-     * EE_Brewing_Regular constructor.
40
-     * @throws \DomainException
41
-     * @throws \EE_Error
42
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
43
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
44
-     * @throws \InvalidArgumentException
45
-     */
46
-    public function __construct(TableAnalysis $table_analysis)
47
-    {
48
-        $this->_table_analysis = $table_analysis;
49
-        if (defined('EE_CAFF_PATH')) {
50
-            // activation
51
-            add_action('AHEE__EEH_Activation__initialize_db_content', array($this, 'initialize_caf_db_content'));
52
-            // load caff init
53
-            add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'caffeinated_init'));
54
-            // remove the "powered by" credit link from receipts and invoices
55
-            add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
56
-            // add caffeinated modules
57
-            add_filter(
58
-                'FHEE__EE_Config__register_modules__modules_to_register',
59
-                array($this, 'caffeinated_modules_to_register')
60
-            );
61
-            // load caff scripts
62
-            add_action('wp_enqueue_scripts', array($this, 'enqueue_caffeinated_scripts'), 10);
63
-            add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
64
-            //add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
65
-            EE_Register_Payment_Method::register(
66
-                'caffeinated_payment_methods',
67
-                array(
68
-                    'payment_method_paths' => glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR)
69
-                )
70
-            );
71
-            // caffeinated constructed
72
-            do_action('AHEE__EE_Brewing_Regular__construct__complete');
73
-            //seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
74
-            add_filter('FHEE__ee_show_affiliate_links', '__return_false');
75
-        }
76
-    }
77
-
78
-
79
-
80
-    /**
81
-     * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
82
-     *
83
-     * @param array $paths original helper paths array
84
-     * @return array             new array of paths
85
-     */
86
-    public function caf_helper_paths($paths)
87
-    {
88
-        $paths[] = EE_CAF_CORE . 'helpers' . DS;
89
-        return $paths;
90
-    }
91
-
92
-
93
-
94
-    /**
95
-     * Upon brand-new activation, if this is a new activation of CAF, we want to add
96
-     * some global prices that will show off EE4's capabilities. However, if they're upgrading
97
-     * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
98
-     * This action should only be called when EE 4.x.0.P is initially activated.
99
-     * Right now the only CAF content are these global prices. If there's more in the future, then
100
-     * we should probably create a caf file to contain it all instead just a function like this.
101
-     * Right now, we ASSUME the only price types in the system are default ones
102
-     *
103
-     * @global wpdb $wpdb
104
-     */
105
-    public function initialize_caf_db_content()
106
-    {
107
-        global $wpdb;
108
-        //use same method of getting creator id as the version introducing the change
109
-        $default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
110
-        $price_type_table = $wpdb->prefix . "esp_price_type";
111
-        $price_table = $wpdb->prefix . "esp_price";
112
-        if ($this->_get_table_analysis()->tableExists($price_type_table)) {
113
-            $SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
114
-            $tax_price_type_count = $wpdb->get_var($SQL);
115
-            if ($tax_price_type_count <= 1) {
116
-                $wpdb->insert(
117
-                    $price_type_table,
118
-                    array(
119
-                        'PRT_name'       => __("Regional Tax", "event_espresso"),
120
-                        'PBT_ID'         => 4,
121
-                        'PRT_is_percent' => true,
122
-                        'PRT_order'      => 60,
123
-                        'PRT_deleted'    => false,
124
-                        'PRT_wp_user'    => $default_creator_id,
125
-                    ),
126
-                    array(
127
-                        '%s',//PRT_name
128
-                        '%d',//PBT_id
129
-                        '%d',//PRT_is_percent
130
-                        '%d',//PRT_order
131
-                        '%d',//PRT_deleted
132
-                        '%d', //PRT_wp_user
133
-                    )
134
-                );
135
-                //federal tax
136
-                $result = $wpdb->insert(
137
-                    $price_type_table,
138
-                    array(
139
-                        'PRT_name'       => __("Federal Tax", "event_espresso"),
140
-                        'PBT_ID'         => 4,
141
-                        'PRT_is_percent' => true,
142
-                        'PRT_order'      => 70,
143
-                        'PRT_deleted'    => false,
144
-                        'PRT_wp_user'    => $default_creator_id,
145
-                    ),
146
-                    array(
147
-                        '%s',//PRT_name
148
-                        '%d',//PBT_id
149
-                        '%d',//PRT_is_percent
150
-                        '%d',//PRT_order
151
-                        '%d',//PRT_deleted
152
-                        '%d' //PRT_wp_user
153
-                    )
154
-                );
155
-                if ($result) {
156
-                    $wpdb->insert(
157
-                        $price_table,
158
-                        array(
159
-                            'PRT_ID'         => $wpdb->insert_id,
160
-                            'PRC_amount'     => 15.00,
161
-                            'PRC_name'       => __("Sales Tax", "event_espresso"),
162
-                            'PRC_desc'       => '',
163
-                            'PRC_is_default' => true,
164
-                            'PRC_overrides'  => null,
165
-                            'PRC_deleted'    => false,
166
-                            'PRC_order'      => 50,
167
-                            'PRC_parent'     => null,
168
-                            'PRC_wp_user'    => $default_creator_id,
169
-                        ),
170
-                        array(
171
-                            '%d',//PRT_id
172
-                            '%f',//PRC_amount
173
-                            '%s',//PRC_name
174
-                            '%s',//PRC_desc
175
-                            '%d',//PRC_is_default
176
-                            '%d',//PRC_overrides
177
-                            '%d',//PRC_deleted
178
-                            '%d',//PRC_order
179
-                            '%d',//PRC_parent
180
-                            '%d' //PRC_wp_user
181
-                        )
182
-                    );
183
-                }
184
-            }
185
-        }
186
-    }
187
-
188
-
189
-
190
-    /**
191
-     *    caffeinated_modules_to_register
192
-     *
193
-     * @access public
194
-     * @param array $modules_to_register
195
-     * @return array
196
-     */
197
-    public function caffeinated_modules_to_register($modules_to_register = array())
198
-    {
199
-        if (is_readable(EE_CAFF_PATH . 'modules')) {
200
-            $caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
201
-            if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
202
-                $modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
203
-            }
204
-        }
205
-        return $modules_to_register;
206
-    }
207
-
208
-
209
-
210
-    public function caffeinated_init()
211
-    {
212
-        // EE_Register_CPTs hooks
213
-        add_filter('FHEE__EE_Register_CPTs__get_taxonomies__taxonomies', array($this, 'filter_taxonomies'), 10);
214
-        add_filter('FHEE__EE_Register_CPTs__get_CPTs__cpts', array($this, 'filter_cpts'), 10);
215
-        add_filter('FHEE__EE_Admin__get_extra_nav_menu_pages_items', array($this, 'nav_metabox_items'), 10);
216
-        EE_Registry::instance()->load_file(EE_CAFF_PATH, 'EE_Caf_Messages', 'class', array(), false);
217
-        // caffeinated_init__complete hook
218
-        do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
219
-    }
220
-
221
-
222
-
223
-    public function enqueue_caffeinated_scripts()
224
-    {
225
-        // sound of crickets...
226
-    }
227
-
228
-
229
-
230
-    /**
231
-     * callbacks below here
232
-     *
233
-     * @param array $taxonomy_array
234
-     * @return array
235
-     */
236
-    public function filter_taxonomies(array $taxonomy_array)
237
-    {
238
-        $taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
239
-        return $taxonomy_array;
240
-    }
241
-
242
-
243
-
244
-    /**
245
-     * @param array $cpt_array
246
-     * @return mixed
247
-     */
248
-    public function filter_cpts(array $cpt_array)
249
-    {
250
-        $cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
251
-        return $cpt_array;
252
-    }
253
-
254
-
255
-
256
-    /**
257
-     * @param array $menuitems
258
-     * @return array
259
-     */
260
-    public function nav_metabox_items(array $menuitems)
261
-    {
262
-        $menuitems[] = array(
263
-            'title'       => __('Venue List', 'event_espresso'),
264
-            'url'         => get_post_type_archive_link('espresso_venues'),
265
-            'description' => __('Archive page for all venues.', 'event_espresso'),
266
-        );
267
-        return $menuitems;
268
-    }
269
-
270
-
271
-    /**
272
-     * Gets the injected table analyzer, or throws an exception
273
-     *
274
-     * @return TableAnalysis
275
-     * @throws \EE_Error
276
-     */
277
-    protected function _get_table_analysis()
278
-    {
279
-        if ($this->_table_analysis instanceof TableAnalysis) {
280
-            return $this->_table_analysis;
281
-        } else {
282
-            throw new \EE_Error(
283
-                sprintf(
284
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
285
-                    get_class($this)
286
-                )
287
-            );
288
-        }
289
-    }
32
+	/**
33
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
34
+	 */
35
+	protected $_table_analysis;
36
+
37
+
38
+	/**
39
+	 * EE_Brewing_Regular constructor.
40
+	 * @throws \DomainException
41
+	 * @throws \EE_Error
42
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
43
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
44
+	 * @throws \InvalidArgumentException
45
+	 */
46
+	public function __construct(TableAnalysis $table_analysis)
47
+	{
48
+		$this->_table_analysis = $table_analysis;
49
+		if (defined('EE_CAFF_PATH')) {
50
+			// activation
51
+			add_action('AHEE__EEH_Activation__initialize_db_content', array($this, 'initialize_caf_db_content'));
52
+			// load caff init
53
+			add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'caffeinated_init'));
54
+			// remove the "powered by" credit link from receipts and invoices
55
+			add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
56
+			// add caffeinated modules
57
+			add_filter(
58
+				'FHEE__EE_Config__register_modules__modules_to_register',
59
+				array($this, 'caffeinated_modules_to_register')
60
+			);
61
+			// load caff scripts
62
+			add_action('wp_enqueue_scripts', array($this, 'enqueue_caffeinated_scripts'), 10);
63
+			add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
64
+			//add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
65
+			EE_Register_Payment_Method::register(
66
+				'caffeinated_payment_methods',
67
+				array(
68
+					'payment_method_paths' => glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR)
69
+				)
70
+			);
71
+			// caffeinated constructed
72
+			do_action('AHEE__EE_Brewing_Regular__construct__complete');
73
+			//seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
74
+			add_filter('FHEE__ee_show_affiliate_links', '__return_false');
75
+		}
76
+	}
77
+
78
+
79
+
80
+	/**
81
+	 * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
82
+	 *
83
+	 * @param array $paths original helper paths array
84
+	 * @return array             new array of paths
85
+	 */
86
+	public function caf_helper_paths($paths)
87
+	{
88
+		$paths[] = EE_CAF_CORE . 'helpers' . DS;
89
+		return $paths;
90
+	}
91
+
92
+
93
+
94
+	/**
95
+	 * Upon brand-new activation, if this is a new activation of CAF, we want to add
96
+	 * some global prices that will show off EE4's capabilities. However, if they're upgrading
97
+	 * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
98
+	 * This action should only be called when EE 4.x.0.P is initially activated.
99
+	 * Right now the only CAF content are these global prices. If there's more in the future, then
100
+	 * we should probably create a caf file to contain it all instead just a function like this.
101
+	 * Right now, we ASSUME the only price types in the system are default ones
102
+	 *
103
+	 * @global wpdb $wpdb
104
+	 */
105
+	public function initialize_caf_db_content()
106
+	{
107
+		global $wpdb;
108
+		//use same method of getting creator id as the version introducing the change
109
+		$default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
110
+		$price_type_table = $wpdb->prefix . "esp_price_type";
111
+		$price_table = $wpdb->prefix . "esp_price";
112
+		if ($this->_get_table_analysis()->tableExists($price_type_table)) {
113
+			$SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
114
+			$tax_price_type_count = $wpdb->get_var($SQL);
115
+			if ($tax_price_type_count <= 1) {
116
+				$wpdb->insert(
117
+					$price_type_table,
118
+					array(
119
+						'PRT_name'       => __("Regional Tax", "event_espresso"),
120
+						'PBT_ID'         => 4,
121
+						'PRT_is_percent' => true,
122
+						'PRT_order'      => 60,
123
+						'PRT_deleted'    => false,
124
+						'PRT_wp_user'    => $default_creator_id,
125
+					),
126
+					array(
127
+						'%s',//PRT_name
128
+						'%d',//PBT_id
129
+						'%d',//PRT_is_percent
130
+						'%d',//PRT_order
131
+						'%d',//PRT_deleted
132
+						'%d', //PRT_wp_user
133
+					)
134
+				);
135
+				//federal tax
136
+				$result = $wpdb->insert(
137
+					$price_type_table,
138
+					array(
139
+						'PRT_name'       => __("Federal Tax", "event_espresso"),
140
+						'PBT_ID'         => 4,
141
+						'PRT_is_percent' => true,
142
+						'PRT_order'      => 70,
143
+						'PRT_deleted'    => false,
144
+						'PRT_wp_user'    => $default_creator_id,
145
+					),
146
+					array(
147
+						'%s',//PRT_name
148
+						'%d',//PBT_id
149
+						'%d',//PRT_is_percent
150
+						'%d',//PRT_order
151
+						'%d',//PRT_deleted
152
+						'%d' //PRT_wp_user
153
+					)
154
+				);
155
+				if ($result) {
156
+					$wpdb->insert(
157
+						$price_table,
158
+						array(
159
+							'PRT_ID'         => $wpdb->insert_id,
160
+							'PRC_amount'     => 15.00,
161
+							'PRC_name'       => __("Sales Tax", "event_espresso"),
162
+							'PRC_desc'       => '',
163
+							'PRC_is_default' => true,
164
+							'PRC_overrides'  => null,
165
+							'PRC_deleted'    => false,
166
+							'PRC_order'      => 50,
167
+							'PRC_parent'     => null,
168
+							'PRC_wp_user'    => $default_creator_id,
169
+						),
170
+						array(
171
+							'%d',//PRT_id
172
+							'%f',//PRC_amount
173
+							'%s',//PRC_name
174
+							'%s',//PRC_desc
175
+							'%d',//PRC_is_default
176
+							'%d',//PRC_overrides
177
+							'%d',//PRC_deleted
178
+							'%d',//PRC_order
179
+							'%d',//PRC_parent
180
+							'%d' //PRC_wp_user
181
+						)
182
+					);
183
+				}
184
+			}
185
+		}
186
+	}
187
+
188
+
189
+
190
+	/**
191
+	 *    caffeinated_modules_to_register
192
+	 *
193
+	 * @access public
194
+	 * @param array $modules_to_register
195
+	 * @return array
196
+	 */
197
+	public function caffeinated_modules_to_register($modules_to_register = array())
198
+	{
199
+		if (is_readable(EE_CAFF_PATH . 'modules')) {
200
+			$caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
201
+			if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
202
+				$modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
203
+			}
204
+		}
205
+		return $modules_to_register;
206
+	}
207
+
208
+
209
+
210
+	public function caffeinated_init()
211
+	{
212
+		// EE_Register_CPTs hooks
213
+		add_filter('FHEE__EE_Register_CPTs__get_taxonomies__taxonomies', array($this, 'filter_taxonomies'), 10);
214
+		add_filter('FHEE__EE_Register_CPTs__get_CPTs__cpts', array($this, 'filter_cpts'), 10);
215
+		add_filter('FHEE__EE_Admin__get_extra_nav_menu_pages_items', array($this, 'nav_metabox_items'), 10);
216
+		EE_Registry::instance()->load_file(EE_CAFF_PATH, 'EE_Caf_Messages', 'class', array(), false);
217
+		// caffeinated_init__complete hook
218
+		do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
219
+	}
220
+
221
+
222
+
223
+	public function enqueue_caffeinated_scripts()
224
+	{
225
+		// sound of crickets...
226
+	}
227
+
228
+
229
+
230
+	/**
231
+	 * callbacks below here
232
+	 *
233
+	 * @param array $taxonomy_array
234
+	 * @return array
235
+	 */
236
+	public function filter_taxonomies(array $taxonomy_array)
237
+	{
238
+		$taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
239
+		return $taxonomy_array;
240
+	}
241
+
242
+
243
+
244
+	/**
245
+	 * @param array $cpt_array
246
+	 * @return mixed
247
+	 */
248
+	public function filter_cpts(array $cpt_array)
249
+	{
250
+		$cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
251
+		return $cpt_array;
252
+	}
253
+
254
+
255
+
256
+	/**
257
+	 * @param array $menuitems
258
+	 * @return array
259
+	 */
260
+	public function nav_metabox_items(array $menuitems)
261
+	{
262
+		$menuitems[] = array(
263
+			'title'       => __('Venue List', 'event_espresso'),
264
+			'url'         => get_post_type_archive_link('espresso_venues'),
265
+			'description' => __('Archive page for all venues.', 'event_espresso'),
266
+		);
267
+		return $menuitems;
268
+	}
269
+
270
+
271
+	/**
272
+	 * Gets the injected table analyzer, or throws an exception
273
+	 *
274
+	 * @return TableAnalysis
275
+	 * @throws \EE_Error
276
+	 */
277
+	protected function _get_table_analysis()
278
+	{
279
+		if ($this->_table_analysis instanceof TableAnalysis) {
280
+			return $this->_table_analysis;
281
+		} else {
282
+			throw new \EE_Error(
283
+				sprintf(
284
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
285
+					get_class($this)
286
+				)
287
+			);
288
+		}
289
+	}
290 290
 }
291 291
 
292 292
 
293 293
 
294 294
 $brewing = new EE_Brewing_Regular(
295
-    EE_Registry::instance()->create('TableAnalysis', array(), true)
295
+	EE_Registry::instance()->create('TableAnalysis', array(), true)
296 296
 );
297 297
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -12,10 +12,10 @@  discard block
 block discarded – undo
12 12
  * define and use the hook in a specific caffeinated/whatever class or file.
13 13
  */
14 14
 // defined some new constants related to caffeinated folder
15
-define('EE_CAF_URL', EE_PLUGIN_DIR_URL . 'caffeinated/');
16
-define('EE_CAF_CORE', EE_CAFF_PATH . 'core' . DS);
17
-define('EE_CAF_LIBRARIES', EE_CAF_CORE . 'libraries' . DS);
18
-define('EE_CAF_PAYMENT_METHODS', EE_CAFF_PATH . 'payment_methods' . DS);
15
+define('EE_CAF_URL', EE_PLUGIN_DIR_URL.'caffeinated/');
16
+define('EE_CAF_CORE', EE_CAFF_PATH.'core'.DS);
17
+define('EE_CAF_LIBRARIES', EE_CAF_CORE.'libraries'.DS);
18
+define('EE_CAF_PAYMENT_METHODS', EE_CAFF_PATH.'payment_methods'.DS);
19 19
 
20 20
 
21 21
 
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
             EE_Register_Payment_Method::register(
66 66
                 'caffeinated_payment_methods',
67 67
                 array(
68
-                    'payment_method_paths' => glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR)
68
+                    'payment_method_paths' => glob(EE_CAF_PAYMENT_METHODS.'*', GLOB_ONLYDIR)
69 69
                 )
70 70
             );
71 71
             // caffeinated constructed
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
      */
86 86
     public function caf_helper_paths($paths)
87 87
     {
88
-        $paths[] = EE_CAF_CORE . 'helpers' . DS;
88
+        $paths[] = EE_CAF_CORE.'helpers'.DS;
89 89
         return $paths;
90 90
     }
91 91
 
@@ -107,10 +107,10 @@  discard block
 block discarded – undo
107 107
         global $wpdb;
108 108
         //use same method of getting creator id as the version introducing the change
109 109
         $default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
110
-        $price_type_table = $wpdb->prefix . "esp_price_type";
111
-        $price_table = $wpdb->prefix . "esp_price";
110
+        $price_type_table = $wpdb->prefix."esp_price_type";
111
+        $price_table = $wpdb->prefix."esp_price";
112 112
         if ($this->_get_table_analysis()->tableExists($price_type_table)) {
113
-            $SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
113
+            $SQL = 'SELECT COUNT(PRT_ID) FROM '.$price_type_table.' WHERE PBT_ID=4'; //include trashed price types
114 114
             $tax_price_type_count = $wpdb->get_var($SQL);
115 115
             if ($tax_price_type_count <= 1) {
116 116
                 $wpdb->insert(
@@ -124,11 +124,11 @@  discard block
 block discarded – undo
124 124
                         'PRT_wp_user'    => $default_creator_id,
125 125
                     ),
126 126
                     array(
127
-                        '%s',//PRT_name
128
-                        '%d',//PBT_id
129
-                        '%d',//PRT_is_percent
130
-                        '%d',//PRT_order
131
-                        '%d',//PRT_deleted
127
+                        '%s', //PRT_name
128
+                        '%d', //PBT_id
129
+                        '%d', //PRT_is_percent
130
+                        '%d', //PRT_order
131
+                        '%d', //PRT_deleted
132 132
                         '%d', //PRT_wp_user
133 133
                     )
134 134
                 );
@@ -144,11 +144,11 @@  discard block
 block discarded – undo
144 144
                         'PRT_wp_user'    => $default_creator_id,
145 145
                     ),
146 146
                     array(
147
-                        '%s',//PRT_name
148
-                        '%d',//PBT_id
149
-                        '%d',//PRT_is_percent
150
-                        '%d',//PRT_order
151
-                        '%d',//PRT_deleted
147
+                        '%s', //PRT_name
148
+                        '%d', //PBT_id
149
+                        '%d', //PRT_is_percent
150
+                        '%d', //PRT_order
151
+                        '%d', //PRT_deleted
152 152
                         '%d' //PRT_wp_user
153 153
                     )
154 154
                 );
@@ -168,15 +168,15 @@  discard block
 block discarded – undo
168 168
                             'PRC_wp_user'    => $default_creator_id,
169 169
                         ),
170 170
                         array(
171
-                            '%d',//PRT_id
172
-                            '%f',//PRC_amount
173
-                            '%s',//PRC_name
174
-                            '%s',//PRC_desc
175
-                            '%d',//PRC_is_default
176
-                            '%d',//PRC_overrides
177
-                            '%d',//PRC_deleted
178
-                            '%d',//PRC_order
179
-                            '%d',//PRC_parent
171
+                            '%d', //PRT_id
172
+                            '%f', //PRC_amount
173
+                            '%s', //PRC_name
174
+                            '%s', //PRC_desc
175
+                            '%d', //PRC_is_default
176
+                            '%d', //PRC_overrides
177
+                            '%d', //PRC_deleted
178
+                            '%d', //PRC_order
179
+                            '%d', //PRC_parent
180 180
                             '%d' //PRC_wp_user
181 181
                         )
182 182
                     );
@@ -196,8 +196,8 @@  discard block
 block discarded – undo
196 196
      */
197 197
     public function caffeinated_modules_to_register($modules_to_register = array())
198 198
     {
199
-        if (is_readable(EE_CAFF_PATH . 'modules')) {
200
-            $caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
199
+        if (is_readable(EE_CAFF_PATH.'modules')) {
200
+            $caffeinated_modules_to_register = glob(EE_CAFF_PATH.'modules'.DS.'*', GLOB_ONLYDIR);
201 201
             if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
202 202
                 $modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
203 203
             }
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Capabilities.lib.php 2 patches
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -10,7 +10,7 @@  discard block
 block discarded – undo
10 10
 use EventEspresso\core\services\loaders\LoaderFactory;
11 11
 
12 12
 if (! defined('EVENT_ESPRESSO_VERSION')) {
13
-    exit('No direct script access allowed');
13
+	exit('No direct script access allowed');
14 14
 }
15 15
 
16 16
 /**
@@ -24,189 +24,189 @@  discard block
 block discarded – undo
24 24
 class EE_Register_Capabilities implements EEI_Plugin_API
25 25
 {
26 26
 
27
-    /**
28
-     * Holds the settings for a specific registration.
29
-     *
30
-     * @var array
31
-     */
32
-    protected static $_registry = array();
27
+	/**
28
+	 * Holds the settings for a specific registration.
29
+	 *
30
+	 * @var array
31
+	 */
32
+	protected static $_registry = array();
33 33
 
34 34
 
35
-    /**
36
-     * Used to register capability items with EE core.
37
-     *
38
-     * @since 4.5.0
39
-     * @param string $cap_reference                                                       usually will be a class name
40
-     *                                                                                    that references capability
41
-     *                                                                                    related items setup for
42
-     *                                                                                    something.
43
-     * @param array  $setup_args                                                          {
44
-     *                                                                                    An array of items related to
45
-     *                                                                                    registering capabilities.
46
-     * @type array   $capabilities                                                        An array mapping capability
47
-     *       strings to core WP Role. Something like: array(
48
-     *                                                                                    'administrator'    => array(
49
-     *                                                                                    'read_cap', 'edit_cap',
50
-     *                                                                                    'delete_cap'),
51
-     *                                                                                    'author'                =>
52
-     *                                                                                    array( 'read_cap' )
53
-     *                                                                                    ).
54
-     * @type array   $capability_maps                                                     EE_Meta_Capability_Map[]
55
-     * @see   EE_Capabilities.php for php docs on these objects.
56
-     *                                                                                    Should be indexed by the
57
-     *                                                                                    classname for the capability
58
-     *                                                                                    map and values representing
59
-     *                                                                                    the arguments for the map.
60
-     *                                                                                    }
61
-     * @throws EE_Error
62
-     * @return void
63
-     */
64
-    public static function register($cap_reference = null, $setup_args = array())
65
-    {
66
-        //required fields MUST be present, so let's make sure they are.
67
-        if ($cap_reference === null || ! is_array($setup_args) || empty($setup_args['capabilities'])) {
68
-            throw new EE_Error(
69
-                __('In order to register capabilities with EE_Register_Capabilities::register, you must include a unique name to reference the capabilities being registered, plus an array containing the following keys: "capabilities".',
70
-                    'event_espresso')
71
-            );
72
-        }
73
-        //make sure we don't register twice
74
-        if (isset(self::$_registry[$cap_reference])) {
75
-            return;
76
-        }
77
-        //make sure this is not registered too late or too early.
78
-        if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')) {
79
-            EE_Error::doing_it_wrong(__METHOD__,
80
-                sprintf(__('%s has been registered too late.  Please ensure that EE_Register_Capabilities::register has been called at some point before the "AHEE__EE_System___detect_if_activation_or_upgrade__begin" action hook has been called.',
81
-                    'event_espresso'), $cap_reference), '4.5.0');
82
-        }
83
-        //some preliminary sanitization and setting to the $_registry property
84
-        self::$_registry[ $cap_reference ] = array(
85
-            'caps'               => isset($setup_args['capabilities']) && is_array($setup_args['capabilities'])
86
-                ? $setup_args['capabilities']
87
-                : array(),
88
-            'cap_maps'           => isset($setup_args['capability_maps'])
89
-                ? $setup_args['capability_maps']
90
-                : array(),
91
-        );
92
-        //set initial caps (note that EE_Capabilities takes care of making sure that the caps get added only once)
93
-        add_filter(
94
-            'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
95
-            array('EE_Register_Capabilities', 'register_capabilities')
96
-        );
97
-        //add filter for cap maps
98
-        add_filter(
99
-            'FHEE__EE_Capabilities___set_meta_caps__meta_caps',
100
-            array('EE_Register_Capabilities', 'register_cap_maps')
101
-        );
102
-    }
35
+	/**
36
+	 * Used to register capability items with EE core.
37
+	 *
38
+	 * @since 4.5.0
39
+	 * @param string $cap_reference                                                       usually will be a class name
40
+	 *                                                                                    that references capability
41
+	 *                                                                                    related items setup for
42
+	 *                                                                                    something.
43
+	 * @param array  $setup_args                                                          {
44
+	 *                                                                                    An array of items related to
45
+	 *                                                                                    registering capabilities.
46
+	 * @type array   $capabilities                                                        An array mapping capability
47
+	 *       strings to core WP Role. Something like: array(
48
+	 *                                                                                    'administrator'    => array(
49
+	 *                                                                                    'read_cap', 'edit_cap',
50
+	 *                                                                                    'delete_cap'),
51
+	 *                                                                                    'author'                =>
52
+	 *                                                                                    array( 'read_cap' )
53
+	 *                                                                                    ).
54
+	 * @type array   $capability_maps                                                     EE_Meta_Capability_Map[]
55
+	 * @see   EE_Capabilities.php for php docs on these objects.
56
+	 *                                                                                    Should be indexed by the
57
+	 *                                                                                    classname for the capability
58
+	 *                                                                                    map and values representing
59
+	 *                                                                                    the arguments for the map.
60
+	 *                                                                                    }
61
+	 * @throws EE_Error
62
+	 * @return void
63
+	 */
64
+	public static function register($cap_reference = null, $setup_args = array())
65
+	{
66
+		//required fields MUST be present, so let's make sure they are.
67
+		if ($cap_reference === null || ! is_array($setup_args) || empty($setup_args['capabilities'])) {
68
+			throw new EE_Error(
69
+				__('In order to register capabilities with EE_Register_Capabilities::register, you must include a unique name to reference the capabilities being registered, plus an array containing the following keys: "capabilities".',
70
+					'event_espresso')
71
+			);
72
+		}
73
+		//make sure we don't register twice
74
+		if (isset(self::$_registry[$cap_reference])) {
75
+			return;
76
+		}
77
+		//make sure this is not registered too late or too early.
78
+		if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')) {
79
+			EE_Error::doing_it_wrong(__METHOD__,
80
+				sprintf(__('%s has been registered too late.  Please ensure that EE_Register_Capabilities::register has been called at some point before the "AHEE__EE_System___detect_if_activation_or_upgrade__begin" action hook has been called.',
81
+					'event_espresso'), $cap_reference), '4.5.0');
82
+		}
83
+		//some preliminary sanitization and setting to the $_registry property
84
+		self::$_registry[ $cap_reference ] = array(
85
+			'caps'               => isset($setup_args['capabilities']) && is_array($setup_args['capabilities'])
86
+				? $setup_args['capabilities']
87
+				: array(),
88
+			'cap_maps'           => isset($setup_args['capability_maps'])
89
+				? $setup_args['capability_maps']
90
+				: array(),
91
+		);
92
+		//set initial caps (note that EE_Capabilities takes care of making sure that the caps get added only once)
93
+		add_filter(
94
+			'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
95
+			array('EE_Register_Capabilities', 'register_capabilities')
96
+		);
97
+		//add filter for cap maps
98
+		add_filter(
99
+			'FHEE__EE_Capabilities___set_meta_caps__meta_caps',
100
+			array('EE_Register_Capabilities', 'register_cap_maps')
101
+		);
102
+	}
103 103
 
104 104
 
105
-    /**
106
-     * callback for FHEE__EE_Capabilities__init_caps_map__caps filter.
107
-     * Takes care of registering additional capabilities to the caps map.   Note, that this also on the initial
108
-     * registration ensures that new capabilities are added to existing roles.
109
-     *
110
-     * @param array $incoming_caps The original caps map.
111
-     * @return array merged in new caps.
112
-     */
113
-    public static function register_capabilities($incoming_caps)
114
-    {
115
-        foreach (self::$_registry as $cap_reference => $caps_and_cap_map) {
116
-            $incoming_caps = array_merge_recursive($incoming_caps, $caps_and_cap_map['caps']);
117
-        }
118
-        return $incoming_caps;
119
-    }
105
+	/**
106
+	 * callback for FHEE__EE_Capabilities__init_caps_map__caps filter.
107
+	 * Takes care of registering additional capabilities to the caps map.   Note, that this also on the initial
108
+	 * registration ensures that new capabilities are added to existing roles.
109
+	 *
110
+	 * @param array $incoming_caps The original caps map.
111
+	 * @return array merged in new caps.
112
+	 */
113
+	public static function register_capabilities($incoming_caps)
114
+	{
115
+		foreach (self::$_registry as $cap_reference => $caps_and_cap_map) {
116
+			$incoming_caps = array_merge_recursive($incoming_caps, $caps_and_cap_map['caps']);
117
+		}
118
+		return $incoming_caps;
119
+	}
120 120
 
121 121
 
122
-    /**
123
-     * Callback for the 'FHEE__EE_Capabilities___set_meta_caps__meta_caps' filter which registers an array of
124
-     * capability maps for the WP meta_caps filter called in EE_Capabilities.
125
-     *
126
-     * @since 4.5.0
127
-     * @param EE_Meta_Capability_Map[] $cap_maps The existing cap maps array.
128
-     * @return EE_Meta_Capability_Map[]
129
-     * @throws EE_Error
130
-     */
131
-    public static function register_cap_maps($cap_maps)
132
-    {
133
-        //loop through and instantiate cap maps.
134
-        foreach (self::$_registry as $cap_reference => $setup) {
135
-            if (! isset($setup['cap_maps'])) {
136
-                continue;
137
-            }
138
-            foreach ($setup['cap_maps'] as $cap_class => $args) {
122
+	/**
123
+	 * Callback for the 'FHEE__EE_Capabilities___set_meta_caps__meta_caps' filter which registers an array of
124
+	 * capability maps for the WP meta_caps filter called in EE_Capabilities.
125
+	 *
126
+	 * @since 4.5.0
127
+	 * @param EE_Meta_Capability_Map[] $cap_maps The existing cap maps array.
128
+	 * @return EE_Meta_Capability_Map[]
129
+	 * @throws EE_Error
130
+	 */
131
+	public static function register_cap_maps($cap_maps)
132
+	{
133
+		//loop through and instantiate cap maps.
134
+		foreach (self::$_registry as $cap_reference => $setup) {
135
+			if (! isset($setup['cap_maps'])) {
136
+				continue;
137
+			}
138
+			foreach ($setup['cap_maps'] as $cap_class => $args) {
139 139
 
140
-                /**
141
-                 * account for cases where capability maps may be indexed
142
-                 * numerically to allow for the same map class to be utilized
143
-                 * In those cases, maps will be setup in an array like:
144
-                 * array(
145
-                 *    0 => array( 'EE_Meta_Capability' => array(
146
-                 *        'ee_edit_cap', array( 'Object_Name',
147
-                 *        'ee_edit_published_cap',
148
-                 *        'ee_edit_others_cap', 'ee_edit_private_cap' )
149
-                 *        ) )
150
-                 *    1 => ...
151
-                 * )
152
-                 * instead of:
153
-                 * array(
154
-                 *    'EE_Meta_Capability' => array(
155
-                 *        'ee_edit_cap', array( 'Object_Name',
156
-                 *        'ee_edit_published_cap',
157
-                 *        'ee_edit_others_cap', 'ee_edit_private_cap' )
158
-                 *        ),
159
-                 *    ...
160
-                 * )
161
-                 */
162
-                if (is_numeric($cap_class)) {
163
-                    $cap_class = key($args);
164
-                    $args      = $args[$cap_class];
165
-                }
140
+				/**
141
+				 * account for cases where capability maps may be indexed
142
+				 * numerically to allow for the same map class to be utilized
143
+				 * In those cases, maps will be setup in an array like:
144
+				 * array(
145
+				 *    0 => array( 'EE_Meta_Capability' => array(
146
+				 *        'ee_edit_cap', array( 'Object_Name',
147
+				 *        'ee_edit_published_cap',
148
+				 *        'ee_edit_others_cap', 'ee_edit_private_cap' )
149
+				 *        ) )
150
+				 *    1 => ...
151
+				 * )
152
+				 * instead of:
153
+				 * array(
154
+				 *    'EE_Meta_Capability' => array(
155
+				 *        'ee_edit_cap', array( 'Object_Name',
156
+				 *        'ee_edit_published_cap',
157
+				 *        'ee_edit_others_cap', 'ee_edit_private_cap' )
158
+				 *        ),
159
+				 *    ...
160
+				 * )
161
+				 */
162
+				if (is_numeric($cap_class)) {
163
+					$cap_class = key($args);
164
+					$args      = $args[$cap_class];
165
+				}
166 166
 
167
-                if (! class_exists($cap_class)) {
168
-                    throw new EE_Error(sprintf(__('An addon (%s) has tried to register a capability map improperly.  Capability map arrays must be indexed by capability map classname, and an array for the class arguments',
169
-                        'event_espresso'), $cap_reference));
170
-                }
167
+				if (! class_exists($cap_class)) {
168
+					throw new EE_Error(sprintf(__('An addon (%s) has tried to register a capability map improperly.  Capability map arrays must be indexed by capability map classname, and an array for the class arguments',
169
+						'event_espresso'), $cap_reference));
170
+				}
171 171
 
172
-                if (count($args) !== 2) {
173
-                    throw new EE_Error(sprintf(__('An addon (%s) has tried to register a capability map improperly.  Capability map arrays must be indexed by capability map classname, and an array for the class arguments.  The array should have two values the first being a string and the second an array.',
174
-                        'event_espresso'), $cap_reference));
175
-                }
176
-                $cap_maps[] = new $cap_class($args[0], $args[1]);
177
-            }
178
-        }
179
-        return $cap_maps;
180
-    }
172
+				if (count($args) !== 2) {
173
+					throw new EE_Error(sprintf(__('An addon (%s) has tried to register a capability map improperly.  Capability map arrays must be indexed by capability map classname, and an array for the class arguments.  The array should have two values the first being a string and the second an array.',
174
+						'event_espresso'), $cap_reference));
175
+				}
176
+				$cap_maps[] = new $cap_class($args[0], $args[1]);
177
+			}
178
+		}
179
+		return $cap_maps;
180
+	}
181 181
 
182 182
 
183
-    /**
184
-     * @param string $cap_reference
185
-     * @throws EE_Error
186
-     * @throws \InvalidArgumentException
187
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
188
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
189
-     */
190
-    public static function deregister($cap_reference = '')
191
-    {
192
-        if (! empty(self::$_registry[$cap_reference])) {
193
-            if (! empty(self::$_registry[ $cap_reference ]['caps'])) {
194
-                //if it's too early to remove capabilities, wait to do this until core is loaded and ready
195
-                $caps_to_remove = self::$_registry[ $cap_reference ]['caps'];
196
-                if (did_action('AHEE__EE_System__core_loaded_and_ready')) {
197
-                    $capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
198
-                    $capabilities->removeCaps($caps_to_remove);
199
-                } else {
200
-                    add_action(
201
-                        'AHEE__EE_System__core_loaded_and_ready',
202
-                        function () use ($caps_to_remove) {
203
-                            $capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
204
-                            $capabilities->removeCaps($caps_to_remove);
205
-                        }
206
-                    );
207
-                }
208
-            }
209
-            unset(self::$_registry[$cap_reference]);
210
-        }
211
-    }
183
+	/**
184
+	 * @param string $cap_reference
185
+	 * @throws EE_Error
186
+	 * @throws \InvalidArgumentException
187
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
188
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
189
+	 */
190
+	public static function deregister($cap_reference = '')
191
+	{
192
+		if (! empty(self::$_registry[$cap_reference])) {
193
+			if (! empty(self::$_registry[ $cap_reference ]['caps'])) {
194
+				//if it's too early to remove capabilities, wait to do this until core is loaded and ready
195
+				$caps_to_remove = self::$_registry[ $cap_reference ]['caps'];
196
+				if (did_action('AHEE__EE_System__core_loaded_and_ready')) {
197
+					$capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
198
+					$capabilities->removeCaps($caps_to_remove);
199
+				} else {
200
+					add_action(
201
+						'AHEE__EE_System__core_loaded_and_ready',
202
+						function () use ($caps_to_remove) {
203
+							$capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
204
+							$capabilities->removeCaps($caps_to_remove);
205
+						}
206
+					);
207
+				}
208
+			}
209
+			unset(self::$_registry[$cap_reference]);
210
+		}
211
+	}
212 212
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
 
10 10
 use EventEspresso\core\services\loaders\LoaderFactory;
11 11
 
12
-if (! defined('EVENT_ESPRESSO_VERSION')) {
12
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
13 13
     exit('No direct script access allowed');
14 14
 }
15 15
 
@@ -75,13 +75,13 @@  discard block
 block discarded – undo
75 75
             return;
76 76
         }
77 77
         //make sure this is not registered too late or too early.
78
-        if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')) {
78
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin')) {
79 79
             EE_Error::doing_it_wrong(__METHOD__,
80 80
                 sprintf(__('%s has been registered too late.  Please ensure that EE_Register_Capabilities::register has been called at some point before the "AHEE__EE_System___detect_if_activation_or_upgrade__begin" action hook has been called.',
81 81
                     'event_espresso'), $cap_reference), '4.5.0');
82 82
         }
83 83
         //some preliminary sanitization and setting to the $_registry property
84
-        self::$_registry[ $cap_reference ] = array(
84
+        self::$_registry[$cap_reference] = array(
85 85
             'caps'               => isset($setup_args['capabilities']) && is_array($setup_args['capabilities'])
86 86
                 ? $setup_args['capabilities']
87 87
                 : array(),
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
     {
133 133
         //loop through and instantiate cap maps.
134 134
         foreach (self::$_registry as $cap_reference => $setup) {
135
-            if (! isset($setup['cap_maps'])) {
135
+            if ( ! isset($setup['cap_maps'])) {
136 136
                 continue;
137 137
             }
138 138
             foreach ($setup['cap_maps'] as $cap_class => $args) {
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
                     $args      = $args[$cap_class];
165 165
                 }
166 166
 
167
-                if (! class_exists($cap_class)) {
167
+                if ( ! class_exists($cap_class)) {
168 168
                     throw new EE_Error(sprintf(__('An addon (%s) has tried to register a capability map improperly.  Capability map arrays must be indexed by capability map classname, and an array for the class arguments',
169 169
                         'event_espresso'), $cap_reference));
170 170
                 }
@@ -189,17 +189,17 @@  discard block
 block discarded – undo
189 189
      */
190 190
     public static function deregister($cap_reference = '')
191 191
     {
192
-        if (! empty(self::$_registry[$cap_reference])) {
193
-            if (! empty(self::$_registry[ $cap_reference ]['caps'])) {
192
+        if ( ! empty(self::$_registry[$cap_reference])) {
193
+            if ( ! empty(self::$_registry[$cap_reference]['caps'])) {
194 194
                 //if it's too early to remove capabilities, wait to do this until core is loaded and ready
195
-                $caps_to_remove = self::$_registry[ $cap_reference ]['caps'];
195
+                $caps_to_remove = self::$_registry[$cap_reference]['caps'];
196 196
                 if (did_action('AHEE__EE_System__core_loaded_and_ready')) {
197 197
                     $capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
198 198
                     $capabilities->removeCaps($caps_to_remove);
199 199
                 } else {
200 200
                     add_action(
201 201
                         'AHEE__EE_System__core_loaded_and_ready',
202
-                        function () use ($caps_to_remove) {
202
+                        function() use ($caps_to_remove) {
203 203
                             $capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
204 204
                             $capabilities->removeCaps($caps_to_remove);
205 205
                         }
Please login to merge, or discard this patch.
core/EE_Error.core.php 2 patches
Indentation   +1030 added lines, -1030 removed lines patch added patch discarded remove patch
@@ -11,8 +11,8 @@  discard block
 block discarded – undo
11 11
 // if you're a dev and want to receive all errors via email
12 12
 // add this to your wp-config.php: define( 'EE_ERROR_EMAILS', TRUE );
13 13
 if (defined('WP_DEBUG') && WP_DEBUG === true && defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS === true) {
14
-    set_error_handler(array('EE_Error', 'error_handler'));
15
-    register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
14
+	set_error_handler(array('EE_Error', 'error_handler'));
15
+	register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
16 16
 }
17 17
 
18 18
 
@@ -27,256 +27,256 @@  discard block
 block discarded – undo
27 27
 class EE_Error extends Exception
28 28
 {
29 29
 
30
-    const OPTIONS_KEY_NOTICES = 'ee_notices';
31
-
32
-
33
-    /**
34
-     * name of the file to log exceptions to
35
-     *
36
-     * @var string
37
-     */
38
-    private static $_exception_log_file = 'espresso_error_log.txt';
39
-
40
-    /**
41
-     *    stores details for all exception
42
-     *
43
-     * @var array
44
-     */
45
-    private static $_all_exceptions = array();
46
-
47
-    /**
48
-     *    tracks number of errors
49
-     *
50
-     * @var int
51
-     */
52
-    private static $_error_count = 0;
53
-
54
-    /**
55
-     * @var array $_espresso_notices
56
-     */
57
-    private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
58
-
59
-
60
-
61
-    /**
62
-     * @override default exception handling
63
-     * @param string         $message
64
-     * @param int            $code
65
-     * @param Exception|null $previous
66
-     */
67
-    public function __construct($message, $code = 0, Exception $previous = null)
68
-    {
69
-        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
70
-            parent::__construct($message, $code);
71
-        } else {
72
-            parent::__construct($message, $code, $previous);
73
-        }
74
-    }
75
-
76
-
77
-
78
-    /**
79
-     *    error_handler
80
-     *
81
-     * @param $code
82
-     * @param $message
83
-     * @param $file
84
-     * @param $line
85
-     * @return void
86
-     */
87
-    public static function error_handler($code, $message, $file, $line)
88
-    {
89
-        $type = EE_Error::error_type($code);
90
-        $site = site_url();
91
-        switch ($site) {
92
-            case 'http://ee4.eventespresso.com/' :
93
-            case 'http://ee4decaf.eventespresso.com/' :
94
-            case 'http://ee4hf.eventespresso.com/' :
95
-            case 'http://ee4a.eventespresso.com/' :
96
-            case 'http://ee4ad.eventespresso.com/' :
97
-            case 'http://ee4b.eventespresso.com/' :
98
-            case 'http://ee4bd.eventespresso.com/' :
99
-            case 'http://ee4d.eventespresso.com/' :
100
-            case 'http://ee4dd.eventespresso.com/' :
101
-                $to = '[email protected]';
102
-                break;
103
-            default :
104
-                $to = get_option('admin_email');
105
-        }
106
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
107
-        $msg = EE_Error::_format_error($type, $message, $file, $line);
108
-        if (function_exists('wp_mail')) {
109
-            add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
110
-            wp_mail($to, $subject, $msg);
111
-        }
112
-        echo '<div id="message" class="espresso-notices error"><p>';
113
-        echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
114
-        echo '<br /></p></div>';
115
-    }
116
-
117
-
118
-
119
-    /**
120
-     * error_type
121
-     * http://www.php.net/manual/en/errorfunc.constants.php#109430
122
-     *
123
-     * @param $code
124
-     * @return string
125
-     */
126
-    public static function error_type($code)
127
-    {
128
-        switch ($code) {
129
-            case E_ERROR: // 1 //
130
-                return 'E_ERROR';
131
-            case E_WARNING: // 2 //
132
-                return 'E_WARNING';
133
-            case E_PARSE: // 4 //
134
-                return 'E_PARSE';
135
-            case E_NOTICE: // 8 //
136
-                return 'E_NOTICE';
137
-            case E_CORE_ERROR: // 16 //
138
-                return 'E_CORE_ERROR';
139
-            case E_CORE_WARNING: // 32 //
140
-                return 'E_CORE_WARNING';
141
-            case E_COMPILE_ERROR: // 64 //
142
-                return 'E_COMPILE_ERROR';
143
-            case E_COMPILE_WARNING: // 128 //
144
-                return 'E_COMPILE_WARNING';
145
-            case E_USER_ERROR: // 256 //
146
-                return 'E_USER_ERROR';
147
-            case E_USER_WARNING: // 512 //
148
-                return 'E_USER_WARNING';
149
-            case E_USER_NOTICE: // 1024 //
150
-                return 'E_USER_NOTICE';
151
-            case E_STRICT: // 2048 //
152
-                return 'E_STRICT';
153
-            case E_RECOVERABLE_ERROR: // 4096 //
154
-                return 'E_RECOVERABLE_ERROR';
155
-            case E_DEPRECATED: // 8192 //
156
-                return 'E_DEPRECATED';
157
-            case E_USER_DEPRECATED: // 16384 //
158
-                return 'E_USER_DEPRECATED';
159
-            case E_ALL: // 16384 //
160
-                return 'E_ALL';
161
-        }
162
-        return '';
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     *    fatal_error_handler
169
-     *
170
-     * @return void
171
-     */
172
-    public static function fatal_error_handler()
173
-    {
174
-        $last_error = error_get_last();
175
-        if ($last_error['type'] === E_ERROR) {
176
-            EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
177
-        }
178
-    }
179
-
180
-
181
-
182
-    /**
183
-     * _format_error
184
-     *
185
-     * @param $code
186
-     * @param $message
187
-     * @param $file
188
-     * @param $line
189
-     * @return string
190
-     */
191
-    private static function _format_error($code, $message, $file, $line)
192
-    {
193
-        $html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
194
-        $html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
195
-        $html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
196
-        $html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
197
-        $html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
198
-        $html .= '</tbody></table>';
199
-        return $html;
200
-    }
201
-
202
-
203
-
204
-    /**
205
-     * set_content_type
206
-     *
207
-     * @param $content_type
208
-     * @return string
209
-     */
210
-    public static function set_content_type($content_type)
211
-    {
212
-        return 'text/html';
213
-    }
214
-
215
-
216
-
217
-    /**
218
-     * @return void
219
-     * @throws EE_Error
220
-     * @throws ReflectionException
221
-     */
222
-    public function get_error()
223
-    {
224
-        if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
225
-            throw $this;
226
-        }
227
-        // get separate user and developer messages if they exist
228
-        $msg = explode('||', $this->getMessage());
229
-        $user_msg = $msg[0];
230
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
231
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
232
-        // add details to _all_exceptions array
233
-        $x_time = time();
234
-        self::$_all_exceptions[$x_time]['name'] = get_class($this);
235
-        self::$_all_exceptions[$x_time]['file'] = $this->getFile();
236
-        self::$_all_exceptions[$x_time]['line'] = $this->getLine();
237
-        self::$_all_exceptions[$x_time]['msg'] = $msg;
238
-        self::$_all_exceptions[$x_time]['code'] = $this->getCode();
239
-        self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
240
-        self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
241
-        self::$_error_count++;
242
-        //add_action( 'shutdown', array( $this, 'display_errors' ));
243
-        $this->display_errors();
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * @param bool   $check_stored
250
-     * @param string $type_to_check
251
-     * @return bool
252
-     */
253
-    public static function has_error($check_stored = false, $type_to_check = 'errors')
254
-    {
255
-        $has_error = isset(self::$_espresso_notices[$type_to_check])
256
-                     && ! empty(self::$_espresso_notices[$type_to_check])
257
-            ? true
258
-            : false;
259
-        if ($check_stored && ! $has_error) {
260
-            $notices = (array)get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
261
-            foreach ($notices as $type => $notice) {
262
-                if ($type === $type_to_check && $notice) {
263
-                    return true;
264
-                }
265
-            }
266
-        }
267
-        return $has_error;
268
-    }
269
-
270
-
271
-
272
-    /**
273
-     * @echo string
274
-     * @throws \ReflectionException
275
-     */
276
-    public function display_errors()
277
-    {
278
-        $trace_details = '';
279
-        $output = '
30
+	const OPTIONS_KEY_NOTICES = 'ee_notices';
31
+
32
+
33
+	/**
34
+	 * name of the file to log exceptions to
35
+	 *
36
+	 * @var string
37
+	 */
38
+	private static $_exception_log_file = 'espresso_error_log.txt';
39
+
40
+	/**
41
+	 *    stores details for all exception
42
+	 *
43
+	 * @var array
44
+	 */
45
+	private static $_all_exceptions = array();
46
+
47
+	/**
48
+	 *    tracks number of errors
49
+	 *
50
+	 * @var int
51
+	 */
52
+	private static $_error_count = 0;
53
+
54
+	/**
55
+	 * @var array $_espresso_notices
56
+	 */
57
+	private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
58
+
59
+
60
+
61
+	/**
62
+	 * @override default exception handling
63
+	 * @param string         $message
64
+	 * @param int            $code
65
+	 * @param Exception|null $previous
66
+	 */
67
+	public function __construct($message, $code = 0, Exception $previous = null)
68
+	{
69
+		if (version_compare(PHP_VERSION, '5.3.0', '<')) {
70
+			parent::__construct($message, $code);
71
+		} else {
72
+			parent::__construct($message, $code, $previous);
73
+		}
74
+	}
75
+
76
+
77
+
78
+	/**
79
+	 *    error_handler
80
+	 *
81
+	 * @param $code
82
+	 * @param $message
83
+	 * @param $file
84
+	 * @param $line
85
+	 * @return void
86
+	 */
87
+	public static function error_handler($code, $message, $file, $line)
88
+	{
89
+		$type = EE_Error::error_type($code);
90
+		$site = site_url();
91
+		switch ($site) {
92
+			case 'http://ee4.eventespresso.com/' :
93
+			case 'http://ee4decaf.eventespresso.com/' :
94
+			case 'http://ee4hf.eventespresso.com/' :
95
+			case 'http://ee4a.eventespresso.com/' :
96
+			case 'http://ee4ad.eventespresso.com/' :
97
+			case 'http://ee4b.eventespresso.com/' :
98
+			case 'http://ee4bd.eventespresso.com/' :
99
+			case 'http://ee4d.eventespresso.com/' :
100
+			case 'http://ee4dd.eventespresso.com/' :
101
+				$to = '[email protected]';
102
+				break;
103
+			default :
104
+				$to = get_option('admin_email');
105
+		}
106
+		$subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
107
+		$msg = EE_Error::_format_error($type, $message, $file, $line);
108
+		if (function_exists('wp_mail')) {
109
+			add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
110
+			wp_mail($to, $subject, $msg);
111
+		}
112
+		echo '<div id="message" class="espresso-notices error"><p>';
113
+		echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
114
+		echo '<br /></p></div>';
115
+	}
116
+
117
+
118
+
119
+	/**
120
+	 * error_type
121
+	 * http://www.php.net/manual/en/errorfunc.constants.php#109430
122
+	 *
123
+	 * @param $code
124
+	 * @return string
125
+	 */
126
+	public static function error_type($code)
127
+	{
128
+		switch ($code) {
129
+			case E_ERROR: // 1 //
130
+				return 'E_ERROR';
131
+			case E_WARNING: // 2 //
132
+				return 'E_WARNING';
133
+			case E_PARSE: // 4 //
134
+				return 'E_PARSE';
135
+			case E_NOTICE: // 8 //
136
+				return 'E_NOTICE';
137
+			case E_CORE_ERROR: // 16 //
138
+				return 'E_CORE_ERROR';
139
+			case E_CORE_WARNING: // 32 //
140
+				return 'E_CORE_WARNING';
141
+			case E_COMPILE_ERROR: // 64 //
142
+				return 'E_COMPILE_ERROR';
143
+			case E_COMPILE_WARNING: // 128 //
144
+				return 'E_COMPILE_WARNING';
145
+			case E_USER_ERROR: // 256 //
146
+				return 'E_USER_ERROR';
147
+			case E_USER_WARNING: // 512 //
148
+				return 'E_USER_WARNING';
149
+			case E_USER_NOTICE: // 1024 //
150
+				return 'E_USER_NOTICE';
151
+			case E_STRICT: // 2048 //
152
+				return 'E_STRICT';
153
+			case E_RECOVERABLE_ERROR: // 4096 //
154
+				return 'E_RECOVERABLE_ERROR';
155
+			case E_DEPRECATED: // 8192 //
156
+				return 'E_DEPRECATED';
157
+			case E_USER_DEPRECATED: // 16384 //
158
+				return 'E_USER_DEPRECATED';
159
+			case E_ALL: // 16384 //
160
+				return 'E_ALL';
161
+		}
162
+		return '';
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 *    fatal_error_handler
169
+	 *
170
+	 * @return void
171
+	 */
172
+	public static function fatal_error_handler()
173
+	{
174
+		$last_error = error_get_last();
175
+		if ($last_error['type'] === E_ERROR) {
176
+			EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
177
+		}
178
+	}
179
+
180
+
181
+
182
+	/**
183
+	 * _format_error
184
+	 *
185
+	 * @param $code
186
+	 * @param $message
187
+	 * @param $file
188
+	 * @param $line
189
+	 * @return string
190
+	 */
191
+	private static function _format_error($code, $message, $file, $line)
192
+	{
193
+		$html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
194
+		$html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
195
+		$html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
196
+		$html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
197
+		$html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
198
+		$html .= '</tbody></table>';
199
+		return $html;
200
+	}
201
+
202
+
203
+
204
+	/**
205
+	 * set_content_type
206
+	 *
207
+	 * @param $content_type
208
+	 * @return string
209
+	 */
210
+	public static function set_content_type($content_type)
211
+	{
212
+		return 'text/html';
213
+	}
214
+
215
+
216
+
217
+	/**
218
+	 * @return void
219
+	 * @throws EE_Error
220
+	 * @throws ReflectionException
221
+	 */
222
+	public function get_error()
223
+	{
224
+		if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
225
+			throw $this;
226
+		}
227
+		// get separate user and developer messages if they exist
228
+		$msg = explode('||', $this->getMessage());
229
+		$user_msg = $msg[0];
230
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
231
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
232
+		// add details to _all_exceptions array
233
+		$x_time = time();
234
+		self::$_all_exceptions[$x_time]['name'] = get_class($this);
235
+		self::$_all_exceptions[$x_time]['file'] = $this->getFile();
236
+		self::$_all_exceptions[$x_time]['line'] = $this->getLine();
237
+		self::$_all_exceptions[$x_time]['msg'] = $msg;
238
+		self::$_all_exceptions[$x_time]['code'] = $this->getCode();
239
+		self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
240
+		self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
241
+		self::$_error_count++;
242
+		//add_action( 'shutdown', array( $this, 'display_errors' ));
243
+		$this->display_errors();
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 * @param bool   $check_stored
250
+	 * @param string $type_to_check
251
+	 * @return bool
252
+	 */
253
+	public static function has_error($check_stored = false, $type_to_check = 'errors')
254
+	{
255
+		$has_error = isset(self::$_espresso_notices[$type_to_check])
256
+					 && ! empty(self::$_espresso_notices[$type_to_check])
257
+			? true
258
+			: false;
259
+		if ($check_stored && ! $has_error) {
260
+			$notices = (array)get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
261
+			foreach ($notices as $type => $notice) {
262
+				if ($type === $type_to_check && $notice) {
263
+					return true;
264
+				}
265
+			}
266
+		}
267
+		return $has_error;
268
+	}
269
+
270
+
271
+
272
+	/**
273
+	 * @echo string
274
+	 * @throws \ReflectionException
275
+	 */
276
+	public function display_errors()
277
+	{
278
+		$trace_details = '';
279
+		$output = '
280 280
 <style type="text/css">
281 281
 	#ee-error-message {
282 282
 		max-width:90% !important;
@@ -332,21 +332,21 @@  discard block
 block discarded – undo
332 332
 	}
333 333
 </style>
334 334
 <div id="ee-error-message" class="error">';
335
-        if (! WP_DEBUG) {
336
-            $output .= '
335
+		if (! WP_DEBUG) {
336
+			$output .= '
337 337
 	<p>';
338
-        }
339
-        // cycle thru errors
340
-        foreach (self::$_all_exceptions as $time => $ex) {
341
-            $error_code = '';
342
-            // process trace info
343
-            if (empty($ex['trace'])) {
344
-                $trace_details .= __(
345
-                    'Sorry, but no trace information was available for this exception.',
346
-                    'event_espresso'
347
-                );
348
-            } else {
349
-                $trace_details .= '
338
+		}
339
+		// cycle thru errors
340
+		foreach (self::$_all_exceptions as $time => $ex) {
341
+			$error_code = '';
342
+			// process trace info
343
+			if (empty($ex['trace'])) {
344
+				$trace_details .= __(
345
+					'Sorry, but no trace information was available for this exception.',
346
+					'event_espresso'
347
+				);
348
+			} else {
349
+				$trace_details .= '
350 350
 			<div id="ee-trace-details">
351 351
 			<table width="100%" border="0" cellpadding="5" cellspacing="0">
352 352
 				<tr>
@@ -356,43 +356,43 @@  discard block
 block discarded – undo
356 356
 					<th scope="col" align="left">Class</th>
357 357
 					<th scope="col" align="left">Method( arguments )</th>
358 358
 				</tr>';
359
-                $last_on_stack = count($ex['trace']) - 1;
360
-                // reverse array so that stack is in proper chronological order
361
-                $sorted_trace = array_reverse($ex['trace']);
362
-                foreach ($sorted_trace as $nmbr => $trace) {
363
-                    $file = isset($trace['file']) ? $trace['file'] : '';
364
-                    $class = isset($trace['class']) ? $trace['class'] : '';
365
-                    $type = isset($trace['type']) ? $trace['type'] : '';
366
-                    $function = isset($trace['function']) ? $trace['function'] : '';
367
-                    $args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
368
-                    $line = isset($trace['line']) ? $trace['line'] : '';
369
-                    $zebra = ($nmbr % 2) ? ' odd' : '';
370
-                    if (empty($file) && ! empty($class)) {
371
-                        $a = new ReflectionClass($class);
372
-                        $file = $a->getFileName();
373
-                        if (empty($line) && ! empty($function)) {
374
-                            try {
375
-                                //if $function is a closure, this throws an exception
376
-                                $b = new ReflectionMethod($class, $function);
377
-                                $line = $b->getStartLine();
378
-                            } catch (Exception $closure_exception) {
379
-                                $line = 'unknown';
380
-                            }
381
-                        }
382
-                    }
383
-                    if ($nmbr === $last_on_stack) {
384
-                        $file = $ex['file'] !== '' ? $ex['file'] : $file;
385
-                        $line = $ex['line'] !== '' ? $ex['line'] : $line;
386
-                        $error_code = self::generate_error_code($file, $trace['function'], $line);
387
-                    }
388
-                    $nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
389
-                    $line_dsply = ! empty($line) ? $line : '&nbsp;';
390
-                    $file_dsply = ! empty($file) ? $file : '&nbsp;';
391
-                    $class_dsply = ! empty($class) ? $class : '&nbsp;';
392
-                    $type_dsply = ! empty($type) ? $type : '&nbsp;';
393
-                    $function_dsply = ! empty($function) ? $function : '&nbsp;';
394
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
395
-                    $trace_details .= '
359
+				$last_on_stack = count($ex['trace']) - 1;
360
+				// reverse array so that stack is in proper chronological order
361
+				$sorted_trace = array_reverse($ex['trace']);
362
+				foreach ($sorted_trace as $nmbr => $trace) {
363
+					$file = isset($trace['file']) ? $trace['file'] : '';
364
+					$class = isset($trace['class']) ? $trace['class'] : '';
365
+					$type = isset($trace['type']) ? $trace['type'] : '';
366
+					$function = isset($trace['function']) ? $trace['function'] : '';
367
+					$args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
368
+					$line = isset($trace['line']) ? $trace['line'] : '';
369
+					$zebra = ($nmbr % 2) ? ' odd' : '';
370
+					if (empty($file) && ! empty($class)) {
371
+						$a = new ReflectionClass($class);
372
+						$file = $a->getFileName();
373
+						if (empty($line) && ! empty($function)) {
374
+							try {
375
+								//if $function is a closure, this throws an exception
376
+								$b = new ReflectionMethod($class, $function);
377
+								$line = $b->getStartLine();
378
+							} catch (Exception $closure_exception) {
379
+								$line = 'unknown';
380
+							}
381
+						}
382
+					}
383
+					if ($nmbr === $last_on_stack) {
384
+						$file = $ex['file'] !== '' ? $ex['file'] : $file;
385
+						$line = $ex['line'] !== '' ? $ex['line'] : $line;
386
+						$error_code = self::generate_error_code($file, $trace['function'], $line);
387
+					}
388
+					$nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
389
+					$line_dsply = ! empty($line) ? $line : '&nbsp;';
390
+					$file_dsply = ! empty($file) ? $file : '&nbsp;';
391
+					$class_dsply = ! empty($class) ? $class : '&nbsp;';
392
+					$type_dsply = ! empty($type) ? $type : '&nbsp;';
393
+					$function_dsply = ! empty($function) ? $function : '&nbsp;';
394
+					$args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
395
+					$trace_details .= '
396 396
 					<tr>
397 397
 						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
398 398
 						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
@@ -400,523 +400,523 @@  discard block
 block discarded – undo
400 400
 						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
401 401
 						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
402 402
 					</tr>';
403
-                }
404
-                $trace_details .= '
403
+				}
404
+				$trace_details .= '
405 405
 			 </table>
406 406
 			</div>';
407
-            }
408
-            $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
409
-            // add generic non-identifying messages for non-privileged users
410
-            if (! WP_DEBUG) {
411
-                $output .= '<span class="ee-error-user-msg-spn">'
412
-                           . trim($ex['msg'])
413
-                           . '</span> &nbsp; <sup>'
414
-                           . $ex['code']
415
-                           . '</sup><br />';
416
-            } else {
417
-                // or helpful developer messages if debugging is on
418
-                $output .= '
407
+			}
408
+			$ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
409
+			// add generic non-identifying messages for non-privileged users
410
+			if (! WP_DEBUG) {
411
+				$output .= '<span class="ee-error-user-msg-spn">'
412
+						   . trim($ex['msg'])
413
+						   . '</span> &nbsp; <sup>'
414
+						   . $ex['code']
415
+						   . '</sup><br />';
416
+			} else {
417
+				// or helpful developer messages if debugging is on
418
+				$output .= '
419 419
 		<div class="ee-error-dev-msg-dv">
420 420
 			<p class="ee-error-dev-msg-pg">
421 421
 				<strong class="ee-error-dev-msg-str">An '
422
-                           . $ex['name']
423
-                           . ' exception was thrown!</strong>  &nbsp; <span>code: '
424
-                           . $ex['code']
425
-                           . '</span><br />
422
+						   . $ex['name']
423
+						   . ' exception was thrown!</strong>  &nbsp; <span>code: '
424
+						   . $ex['code']
425
+						   . '</span><br />
426 426
 				<span class="big-text">"'
427
-                           . trim($ex['msg'])
428
-                           . '"</span><br/>
427
+						   . trim($ex['msg'])
428
+						   . '"</span><br/>
429 429
 				<a id="display-ee-error-trace-'
430
-                           . self::$_error_count
431
-                           . $time
432
-                           . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
433
-                           . self::$_error_count
434
-                           . $time
435
-                           . '">
430
+						   . self::$_error_count
431
+						   . $time
432
+						   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
433
+						   . self::$_error_count
434
+						   . $time
435
+						   . '">
436 436
 					'
437
-                           . __('click to view backtrace and class/method details', 'event_espresso')
438
-                           . '
437
+						   . __('click to view backtrace and class/method details', 'event_espresso')
438
+						   . '
439 439
 				</a><br />
440 440
 				<span class="small-text lt-grey-text">'
441
-                           . $ex['file']
442
-                           . ' &nbsp; ( line no: '
443
-                           . $ex['line']
444
-                           . ' )</span>
441
+						   . $ex['file']
442
+						   . ' &nbsp; ( line no: '
443
+						   . $ex['line']
444
+						   . ' )</span>
445 445
 			</p>
446 446
 			<div id="ee-error-trace-'
447
-                           . self::$_error_count
448
-                           . $time
449
-                           . '-dv" class="ee-error-trace-dv" style="display: none;">
447
+						   . self::$_error_count
448
+						   . $time
449
+						   . '-dv" class="ee-error-trace-dv" style="display: none;">
450 450
 				'
451
-                           . $trace_details;
452
-                if (! empty($class)) {
453
-                    $output .= '
451
+						   . $trace_details;
452
+				if (! empty($class)) {
453
+					$output .= '
454 454
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
455 455
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
456 456
 						<h3>Class Details</h3>';
457
-                    $a = new ReflectionClass($class);
458
-                    $output .= '
457
+					$a = new ReflectionClass($class);
458
+					$output .= '
459 459
 						<pre>' . $a . '</pre>
460 460
 					</div>
461 461
 				</div>';
462
-                }
463
-                $output .= '
462
+				}
463
+				$output .= '
464 464
 			</div>
465 465
 		</div>
466 466
 		<br />';
467
-            }
468
-            $this->write_to_error_log($time, $ex);
469
-        }
470
-        // remove last linebreak
471
-        $output = substr($output, 0, -6);
472
-        if (! WP_DEBUG) {
473
-            $output .= '
467
+			}
468
+			$this->write_to_error_log($time, $ex);
469
+		}
470
+		// remove last linebreak
471
+		$output = substr($output, 0, -6);
472
+		if (! WP_DEBUG) {
473
+			$output .= '
474 474
 	</p>';
475
-        }
476
-        $output .= '
475
+		}
476
+		$output .= '
477 477
 </div>';
478
-        $output .= self::_print_scripts(true);
479
-        if (defined('DOING_AJAX')) {
480
-            echo wp_json_encode(array('error' => $output));
481
-            exit();
482
-        }
483
-        echo $output;
484
-        die();
485
-    }
486
-
487
-
488
-
489
-    /**
490
-     *    generate string from exception trace args
491
-     *
492
-     * @param array $arguments
493
-     * @param bool  $array
494
-     * @return string
495
-     */
496
-    private function _convert_args_to_string($arguments = array(), $array = false)
497
-    {
498
-        $arg_string = '';
499
-        if (! empty($arguments)) {
500
-            $args = array();
501
-            foreach ($arguments as $arg) {
502
-                if (! empty($arg)) {
503
-                    if (is_string($arg)) {
504
-                        $args[] = " '" . $arg . "'";
505
-                    } elseif (is_array($arg)) {
506
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
507
-                    } elseif ($arg === null) {
508
-                        $args[] = ' NULL';
509
-                    } elseif (is_bool($arg)) {
510
-                        $args[] = ($arg) ? ' TRUE' : ' FALSE';
511
-                    } elseif (is_object($arg)) {
512
-                        $args[] = ' OBJECT ' . get_class($arg);
513
-                    } elseif (is_resource($arg)) {
514
-                        $args[] = get_resource_type($arg);
515
-                    } else {
516
-                        $args[] = $arg;
517
-                    }
518
-                }
519
-            }
520
-            $arg_string = implode(', ', $args);
521
-        }
522
-        if ($array) {
523
-            $arg_string .= ' )';
524
-        }
525
-        return $arg_string;
526
-    }
527
-
528
-
529
-
530
-    /**
531
-     *    add error message
532
-     *
533
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
534
-     *                            separate messages for user || dev
535
-     * @param        string $file the file that the error occurred in - just use __FILE__
536
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
537
-     * @param        string $line the line number where the error occurred - just use __LINE__
538
-     * @return        void
539
-     */
540
-    public static function add_error($msg = null, $file = null, $func = null, $line = null)
541
-    {
542
-        self::_add_notice('errors', $msg, $file, $func, $line);
543
-        self::$_error_count++;
544
-    }
545
-
546
-
547
-
548
-    /**
549
-     * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
550
-     * adds an error
551
-     *
552
-     * @param string $msg
553
-     * @param string $file
554
-     * @param string $func
555
-     * @param string $line
556
-     * @throws EE_Error
557
-     */
558
-    public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
559
-    {
560
-        if (WP_DEBUG) {
561
-            throw new EE_Error($msg);
562
-        }
563
-        EE_Error::add_error($msg, $file, $func, $line);
564
-    }
565
-
566
-
567
-
568
-    /**
569
-     *    add success message
570
-     *
571
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
572
-     *                            separate messages for user || dev
573
-     * @param        string $file the file that the error occurred in - just use __FILE__
574
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
575
-     * @param        string $line the line number where the error occurred - just use __LINE__
576
-     * @return        void
577
-     */
578
-    public static function add_success($msg = null, $file = null, $func = null, $line = null)
579
-    {
580
-        self::_add_notice('success', $msg, $file, $func, $line);
581
-    }
582
-
583
-
584
-
585
-    /**
586
-     *    add attention message
587
-     *
588
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
589
-     *                            separate messages for user || dev
590
-     * @param        string $file the file that the error occurred in - just use __FILE__
591
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
592
-     * @param        string $line the line number where the error occurred - just use __LINE__
593
-     * @return        void
594
-     */
595
-    public static function add_attention($msg = null, $file = null, $func = null, $line = null)
596
-    {
597
-        self::_add_notice('attention', $msg, $file, $func, $line);
598
-    }
599
-
600
-
601
-
602
-    /**
603
-     * @param string $type whether the message is for a success or error notification
604
-     * @param string $msg the message to display to users or developers
605
-     *                    - adding a double pipe || (OR) creates separate messages for user || dev
606
-     * @param string $file the file that the error occurred in - just use __FILE__
607
-     * @param string $func the function/method that the error occurred in - just use __FUNCTION__
608
-     * @param string $line the line number where the error occurred - just use __LINE__
609
-     * @return void
610
-     */
611
-    private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
612
-    {
613
-        if (empty($msg)) {
614
-            EE_Error::doing_it_wrong(
615
-                'EE_Error::add_' . $type . '()',
616
-                sprintf(
617
-                    __('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
618
-                        'event_espresso'),
619
-                    $type,
620
-                    $file,
621
-                    $line
622
-                ),
623
-                EVENT_ESPRESSO_VERSION
624
-            );
625
-        }
626
-        if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
627
-            EE_Error::doing_it_wrong(
628
-                'EE_Error::add_error()',
629
-                __('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
630
-                    'event_espresso'),
631
-                EVENT_ESPRESSO_VERSION
632
-            );
633
-        }
634
-        // get separate user and developer messages if they exist
635
-        $msg      = explode('||', $msg);
636
-        $user_msg = $msg[0];
637
-        $dev_msg  = isset($msg[1]) ? $msg[1] : $msg[0];
638
-        /**
639
-         * Do an action so other code can be triggered when a notice is created
640
-         *
641
-         * @param string $type     can be 'errors', 'attention', or 'success'
642
-         * @param string $user_msg message displayed to user when WP_DEBUG is off
643
-         * @param string $user_msg message displayed to user when WP_DEBUG is on
644
-         * @param string $file     file where error was generated
645
-         * @param string $func     function where error was generated
646
-         * @param string $line     line where error was generated
647
-         */
648
-        do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
649
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
650
-        // add notice if message exists
651
-        if (! empty($msg)) {
652
-            // get error code
653
-            $notice_code = EE_Error::generate_error_code($file, $func, $line);
654
-            if (WP_DEBUG && $type === 'errors') {
655
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
656
-            }
657
-            // add notice. Index by code if it's not blank
658
-            if ($notice_code) {
659
-                self::$_espresso_notices[$type][$notice_code] = $msg;
660
-            } else {
661
-                self::$_espresso_notices[$type][] = $msg;
662
-            }
663
-            add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
664
-        }
665
-    }
666
-
667
-
668
-    /**
669
-     * in some case it may be necessary to overwrite the existing success messages
670
-     *
671
-     * @return        void
672
-     */
673
-    public static function overwrite_success()
674
-    {
675
-        self::$_espresso_notices['success'] = false;
676
-    }
677
-
678
-
679
-
680
-    /**
681
-     * in some case it may be necessary to overwrite the existing attention messages
682
-     *
683
-     * @return void
684
-     */
685
-    public static function overwrite_attention()
686
-    {
687
-        self::$_espresso_notices['attention'] = false;
688
-    }
689
-
690
-
691
-
692
-    /**
693
-     * in some case it may be necessary to overwrite the existing error messages
694
-     *
695
-     * @return void
696
-     */
697
-    public static function overwrite_errors()
698
-    {
699
-        self::$_espresso_notices['errors'] = false;
700
-    }
701
-
702
-
703
-
704
-    /**
705
-     * @return void
706
-     */
707
-    public static function reset_notices()
708
-    {
709
-        self::$_espresso_notices['success']   = false;
710
-        self::$_espresso_notices['attention'] = false;
711
-        self::$_espresso_notices['errors']    = false;
712
-    }
713
-
714
-
715
-
716
-    /**
717
-     * @return int
718
-     */
719
-    public static function has_notices()
720
-    {
721
-        $has_notices = 0;
722
-        // check for success messages
723
-        $has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
724
-            ? 3
725
-            : $has_notices;
726
-        // check for attention messages
727
-        $has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
728
-            ? 2
729
-            : $has_notices;
730
-        // check for error messages
731
-        $has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
732
-            ? 1
733
-            : $has_notices;
734
-        return $has_notices;
735
-    }
736
-
737
-
738
-    /**
739
-     * This simply returns non formatted error notices as they were sent into the EE_Error object.
740
-     *
741
-     * @since 4.9.0
742
-     * @return array
743
-     */
744
-    public static function get_vanilla_notices()
745
-    {
746
-        return array(
747
-            'success'   => isset(self::$_espresso_notices['success'])
748
-                ? self::$_espresso_notices['success']
749
-                : array(),
750
-            'attention' => isset(self::$_espresso_notices['attention'])
751
-                ? self::$_espresso_notices['attention']
752
-                : array(),
753
-            'errors'    => isset(self::$_espresso_notices['errors'])
754
-                ? self::$_espresso_notices['errors']
755
-                : array(),
756
-        );
757
-    }
758
-
759
-
760
-
761
-    /**
762
-     * compile all error or success messages into one string
763
-     *
764
-     * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
765
-     * @param boolean $format_output     whether or not to format the messages for display in the WP admin
766
-     * @param boolean $save_to_transient whether or not to save notices to the db for retrieval on next request
767
-     *                                          - ONLY do this just before redirecting
768
-     * @param boolean $remove_empty      whether or not to unset empty messages
769
-     * @return array
770
-     */
771
-    public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
772
-    {
773
-        // do_action('AHEE_log', __FILE__, __FUNCTION__, '');
774
-        $success_messages   = '';
775
-        $attention_messages = '';
776
-        $error_messages     = '';
777
-        $print_scripts      = false;
778
-        // EEH_Debug_Tools::printr( self::$_espresso_notices, 'espresso_notices  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
779
-        // either save notices to the db
780
-        if ($save_to_transient || isset($_REQUEST['activate-selected'])) {
781
-            $existing_notices  = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
782
-            $existing_notices = is_array($existing_notices) ? $existing_notices : array();
783
-            self::$_espresso_notices = array_merge(
784
-                $existing_notices,
785
-                self::$_espresso_notices
786
-            );
787
-            update_option(EE_Error::OPTIONS_KEY_NOTICES, self::$_espresso_notices);
788
-            return array();
789
-        }
790
-        // grab any notices that have been previously saved
791
-        if ($notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array())) {
792
-            foreach ($notices as $type => $notice) {
793
-                if (is_array($notice) && ! empty($notice)) {
794
-                    // make sure that existing notice type is an array
795
-                    self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
796
-                                                      && ! empty(self::$_espresso_notices[$type])
797
-                        ? self::$_espresso_notices[$type]
798
-                        : array();
799
-                    // merge stored notices with any newly created ones
800
-                    self::$_espresso_notices[$type] = array_merge(self::$_espresso_notices[$type], $notice);
801
-                    $print_scripts                  = true;
802
-                }
803
-            }
804
-            // now clear any stored notices
805
-            update_option(EE_Error::OPTIONS_KEY_NOTICES, array());
806
-        }
807
-        // check for success messages
808
-        if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
809
-            // combine messages
810
-            $success_messages .= implode(self::$_espresso_notices['success'], '<br />');
811
-            $print_scripts    = true;
812
-        }
813
-        // check for attention messages
814
-        if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
815
-            // combine messages
816
-            $attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
817
-            $print_scripts      = true;
818
-        }
819
-        // check for error messages
820
-        if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
821
-            $error_messages .= count(self::$_espresso_notices['errors']) > 1
822
-                ? __('The following errors have occurred:<br />', 'event_espresso')
823
-                : __('An error has occurred:<br />', 'event_espresso');
824
-            // combine messages
825
-            $error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
826
-            $print_scripts  = true;
827
-        }
828
-        if ($format_output) {
829
-
830
-            $notices = '<div id="espresso-notices">';
831
-            $close = is_admin() ? ''
832
-                : '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"></span></a>';
833
-            if ($success_messages !== '') {
834
-                $css_id    = is_admin() ? 'message' : 'espresso-notices-success';
835
-                $css_class = is_admin() ? 'updated fade' : 'success fade-away';
836
-                //showMessage( $success_messages );
837
-                $notices .= '<div id="'
838
-                            . $css_id
839
-                            . '" class="espresso-notices '
840
-                            . $css_class
841
-                            . '" style="display:none;"><p>'
842
-                            . $success_messages
843
-                            . '</p>'
844
-                            . $close
845
-                            . '</div>';
846
-            }
847
-            if ($attention_messages !== '') {
848
-                $css_id    = is_admin() ? 'message' : 'espresso-notices-attention';
849
-                $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
850
-                //showMessage( $error_messages, TRUE );
851
-                $notices .= '<div id="'
852
-                            . $css_id
853
-                            . '" class="espresso-notices '
854
-                            . $css_class
855
-                            . '" style="display:none;"><p>'
856
-                            . $attention_messages
857
-                            . '</p>'
858
-                            . $close
859
-                            . '</div>';
860
-            }
861
-            if ($error_messages !== '') {
862
-                $css_id    = is_admin() ? 'message' : 'espresso-notices-error';
863
-                $css_class = is_admin() ? 'error' : 'error fade-away';
864
-                //showMessage( $error_messages, TRUE );
865
-                $notices .= '<div id="'
866
-                            . $css_id
867
-                            . '" class="espresso-notices '
868
-                            . $css_class
869
-                            . '" style="display:none;"><p>'
870
-                            . $error_messages
871
-                            . '</p>'
872
-                            . $close
873
-                            . '</div>';
874
-            }
875
-            $notices .= '</div>';
876
-        } else {
877
-
878
-            $notices = array(
879
-                'success'   => $success_messages,
880
-                'attention' => $attention_messages,
881
-                'errors'    => $error_messages,
882
-            );
883
-            if ($remove_empty) {
884
-                // remove empty notices
885
-                foreach ($notices as $type => $notice) {
886
-                    if (empty($notice)) {
887
-                        unset($notices[$type]);
888
-                    }
889
-                }
890
-            }
891
-        }
892
-        if ($print_scripts) {
893
-            self::_print_scripts();
894
-        }
895
-        return $notices;
896
-    }
897
-
898
-
899
-
900
-    /**
901
-     * _print_scripts
902
-     *
903
-     * @param    bool $force_print
904
-     * @return    string
905
-     */
906
-    private static function _print_scripts($force_print = false)
907
-    {
908
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
909
-            if (wp_script_is('ee_error_js', 'enqueued')) {
910
-                return '';
911
-            }
912
-            if (wp_script_is('ee_error_js', 'registered')) {
913
-                wp_enqueue_style('espresso_default');
914
-                wp_enqueue_style('espresso_custom_css');
915
-                wp_enqueue_script('ee_error_js');
916
-                wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
917
-            }
918
-        } else {
919
-            return '
478
+		$output .= self::_print_scripts(true);
479
+		if (defined('DOING_AJAX')) {
480
+			echo wp_json_encode(array('error' => $output));
481
+			exit();
482
+		}
483
+		echo $output;
484
+		die();
485
+	}
486
+
487
+
488
+
489
+	/**
490
+	 *    generate string from exception trace args
491
+	 *
492
+	 * @param array $arguments
493
+	 * @param bool  $array
494
+	 * @return string
495
+	 */
496
+	private function _convert_args_to_string($arguments = array(), $array = false)
497
+	{
498
+		$arg_string = '';
499
+		if (! empty($arguments)) {
500
+			$args = array();
501
+			foreach ($arguments as $arg) {
502
+				if (! empty($arg)) {
503
+					if (is_string($arg)) {
504
+						$args[] = " '" . $arg . "'";
505
+					} elseif (is_array($arg)) {
506
+						$args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
507
+					} elseif ($arg === null) {
508
+						$args[] = ' NULL';
509
+					} elseif (is_bool($arg)) {
510
+						$args[] = ($arg) ? ' TRUE' : ' FALSE';
511
+					} elseif (is_object($arg)) {
512
+						$args[] = ' OBJECT ' . get_class($arg);
513
+					} elseif (is_resource($arg)) {
514
+						$args[] = get_resource_type($arg);
515
+					} else {
516
+						$args[] = $arg;
517
+					}
518
+				}
519
+			}
520
+			$arg_string = implode(', ', $args);
521
+		}
522
+		if ($array) {
523
+			$arg_string .= ' )';
524
+		}
525
+		return $arg_string;
526
+	}
527
+
528
+
529
+
530
+	/**
531
+	 *    add error message
532
+	 *
533
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
534
+	 *                            separate messages for user || dev
535
+	 * @param        string $file the file that the error occurred in - just use __FILE__
536
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
537
+	 * @param        string $line the line number where the error occurred - just use __LINE__
538
+	 * @return        void
539
+	 */
540
+	public static function add_error($msg = null, $file = null, $func = null, $line = null)
541
+	{
542
+		self::_add_notice('errors', $msg, $file, $func, $line);
543
+		self::$_error_count++;
544
+	}
545
+
546
+
547
+
548
+	/**
549
+	 * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
550
+	 * adds an error
551
+	 *
552
+	 * @param string $msg
553
+	 * @param string $file
554
+	 * @param string $func
555
+	 * @param string $line
556
+	 * @throws EE_Error
557
+	 */
558
+	public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
559
+	{
560
+		if (WP_DEBUG) {
561
+			throw new EE_Error($msg);
562
+		}
563
+		EE_Error::add_error($msg, $file, $func, $line);
564
+	}
565
+
566
+
567
+
568
+	/**
569
+	 *    add success message
570
+	 *
571
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
572
+	 *                            separate messages for user || dev
573
+	 * @param        string $file the file that the error occurred in - just use __FILE__
574
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
575
+	 * @param        string $line the line number where the error occurred - just use __LINE__
576
+	 * @return        void
577
+	 */
578
+	public static function add_success($msg = null, $file = null, $func = null, $line = null)
579
+	{
580
+		self::_add_notice('success', $msg, $file, $func, $line);
581
+	}
582
+
583
+
584
+
585
+	/**
586
+	 *    add attention message
587
+	 *
588
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
589
+	 *                            separate messages for user || dev
590
+	 * @param        string $file the file that the error occurred in - just use __FILE__
591
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
592
+	 * @param        string $line the line number where the error occurred - just use __LINE__
593
+	 * @return        void
594
+	 */
595
+	public static function add_attention($msg = null, $file = null, $func = null, $line = null)
596
+	{
597
+		self::_add_notice('attention', $msg, $file, $func, $line);
598
+	}
599
+
600
+
601
+
602
+	/**
603
+	 * @param string $type whether the message is for a success or error notification
604
+	 * @param string $msg the message to display to users or developers
605
+	 *                    - adding a double pipe || (OR) creates separate messages for user || dev
606
+	 * @param string $file the file that the error occurred in - just use __FILE__
607
+	 * @param string $func the function/method that the error occurred in - just use __FUNCTION__
608
+	 * @param string $line the line number where the error occurred - just use __LINE__
609
+	 * @return void
610
+	 */
611
+	private static function _add_notice($type = 'success', $msg = '', $file = '', $func = '', $line = '')
612
+	{
613
+		if (empty($msg)) {
614
+			EE_Error::doing_it_wrong(
615
+				'EE_Error::add_' . $type . '()',
616
+				sprintf(
617
+					__('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
618
+						'event_espresso'),
619
+					$type,
620
+					$file,
621
+					$line
622
+				),
623
+				EVENT_ESPRESSO_VERSION
624
+			);
625
+		}
626
+		if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
627
+			EE_Error::doing_it_wrong(
628
+				'EE_Error::add_error()',
629
+				__('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
630
+					'event_espresso'),
631
+				EVENT_ESPRESSO_VERSION
632
+			);
633
+		}
634
+		// get separate user and developer messages if they exist
635
+		$msg      = explode('||', $msg);
636
+		$user_msg = $msg[0];
637
+		$dev_msg  = isset($msg[1]) ? $msg[1] : $msg[0];
638
+		/**
639
+		 * Do an action so other code can be triggered when a notice is created
640
+		 *
641
+		 * @param string $type     can be 'errors', 'attention', or 'success'
642
+		 * @param string $user_msg message displayed to user when WP_DEBUG is off
643
+		 * @param string $user_msg message displayed to user when WP_DEBUG is on
644
+		 * @param string $file     file where error was generated
645
+		 * @param string $func     function where error was generated
646
+		 * @param string $line     line where error was generated
647
+		 */
648
+		do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
649
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
650
+		// add notice if message exists
651
+		if (! empty($msg)) {
652
+			// get error code
653
+			$notice_code = EE_Error::generate_error_code($file, $func, $line);
654
+			if (WP_DEBUG && $type === 'errors') {
655
+				$msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
656
+			}
657
+			// add notice. Index by code if it's not blank
658
+			if ($notice_code) {
659
+				self::$_espresso_notices[$type][$notice_code] = $msg;
660
+			} else {
661
+				self::$_espresso_notices[$type][] = $msg;
662
+			}
663
+			add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
664
+		}
665
+	}
666
+
667
+
668
+	/**
669
+	 * in some case it may be necessary to overwrite the existing success messages
670
+	 *
671
+	 * @return        void
672
+	 */
673
+	public static function overwrite_success()
674
+	{
675
+		self::$_espresso_notices['success'] = false;
676
+	}
677
+
678
+
679
+
680
+	/**
681
+	 * in some case it may be necessary to overwrite the existing attention messages
682
+	 *
683
+	 * @return void
684
+	 */
685
+	public static function overwrite_attention()
686
+	{
687
+		self::$_espresso_notices['attention'] = false;
688
+	}
689
+
690
+
691
+
692
+	/**
693
+	 * in some case it may be necessary to overwrite the existing error messages
694
+	 *
695
+	 * @return void
696
+	 */
697
+	public static function overwrite_errors()
698
+	{
699
+		self::$_espresso_notices['errors'] = false;
700
+	}
701
+
702
+
703
+
704
+	/**
705
+	 * @return void
706
+	 */
707
+	public static function reset_notices()
708
+	{
709
+		self::$_espresso_notices['success']   = false;
710
+		self::$_espresso_notices['attention'] = false;
711
+		self::$_espresso_notices['errors']    = false;
712
+	}
713
+
714
+
715
+
716
+	/**
717
+	 * @return int
718
+	 */
719
+	public static function has_notices()
720
+	{
721
+		$has_notices = 0;
722
+		// check for success messages
723
+		$has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])
724
+			? 3
725
+			: $has_notices;
726
+		// check for attention messages
727
+		$has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])
728
+			? 2
729
+			: $has_notices;
730
+		// check for error messages
731
+		$has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])
732
+			? 1
733
+			: $has_notices;
734
+		return $has_notices;
735
+	}
736
+
737
+
738
+	/**
739
+	 * This simply returns non formatted error notices as they were sent into the EE_Error object.
740
+	 *
741
+	 * @since 4.9.0
742
+	 * @return array
743
+	 */
744
+	public static function get_vanilla_notices()
745
+	{
746
+		return array(
747
+			'success'   => isset(self::$_espresso_notices['success'])
748
+				? self::$_espresso_notices['success']
749
+				: array(),
750
+			'attention' => isset(self::$_espresso_notices['attention'])
751
+				? self::$_espresso_notices['attention']
752
+				: array(),
753
+			'errors'    => isset(self::$_espresso_notices['errors'])
754
+				? self::$_espresso_notices['errors']
755
+				: array(),
756
+		);
757
+	}
758
+
759
+
760
+
761
+	/**
762
+	 * compile all error or success messages into one string
763
+	 *
764
+	 * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
765
+	 * @param boolean $format_output     whether or not to format the messages for display in the WP admin
766
+	 * @param boolean $save_to_transient whether or not to save notices to the db for retrieval on next request
767
+	 *                                          - ONLY do this just before redirecting
768
+	 * @param boolean $remove_empty      whether or not to unset empty messages
769
+	 * @return array
770
+	 */
771
+	public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
772
+	{
773
+		// do_action('AHEE_log', __FILE__, __FUNCTION__, '');
774
+		$success_messages   = '';
775
+		$attention_messages = '';
776
+		$error_messages     = '';
777
+		$print_scripts      = false;
778
+		// EEH_Debug_Tools::printr( self::$_espresso_notices, 'espresso_notices  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
779
+		// either save notices to the db
780
+		if ($save_to_transient || isset($_REQUEST['activate-selected'])) {
781
+			$existing_notices  = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
782
+			$existing_notices = is_array($existing_notices) ? $existing_notices : array();
783
+			self::$_espresso_notices = array_merge(
784
+				$existing_notices,
785
+				self::$_espresso_notices
786
+			);
787
+			update_option(EE_Error::OPTIONS_KEY_NOTICES, self::$_espresso_notices);
788
+			return array();
789
+		}
790
+		// grab any notices that have been previously saved
791
+		if ($notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array())) {
792
+			foreach ($notices as $type => $notice) {
793
+				if (is_array($notice) && ! empty($notice)) {
794
+					// make sure that existing notice type is an array
795
+					self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
796
+													  && ! empty(self::$_espresso_notices[$type])
797
+						? self::$_espresso_notices[$type]
798
+						: array();
799
+					// merge stored notices with any newly created ones
800
+					self::$_espresso_notices[$type] = array_merge(self::$_espresso_notices[$type], $notice);
801
+					$print_scripts                  = true;
802
+				}
803
+			}
804
+			// now clear any stored notices
805
+			update_option(EE_Error::OPTIONS_KEY_NOTICES, array());
806
+		}
807
+		// check for success messages
808
+		if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
809
+			// combine messages
810
+			$success_messages .= implode(self::$_espresso_notices['success'], '<br />');
811
+			$print_scripts    = true;
812
+		}
813
+		// check for attention messages
814
+		if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
815
+			// combine messages
816
+			$attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
817
+			$print_scripts      = true;
818
+		}
819
+		// check for error messages
820
+		if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
821
+			$error_messages .= count(self::$_espresso_notices['errors']) > 1
822
+				? __('The following errors have occurred:<br />', 'event_espresso')
823
+				: __('An error has occurred:<br />', 'event_espresso');
824
+			// combine messages
825
+			$error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
826
+			$print_scripts  = true;
827
+		}
828
+		if ($format_output) {
829
+
830
+			$notices = '<div id="espresso-notices">';
831
+			$close = is_admin() ? ''
832
+				: '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"></span></a>';
833
+			if ($success_messages !== '') {
834
+				$css_id    = is_admin() ? 'message' : 'espresso-notices-success';
835
+				$css_class = is_admin() ? 'updated fade' : 'success fade-away';
836
+				//showMessage( $success_messages );
837
+				$notices .= '<div id="'
838
+							. $css_id
839
+							. '" class="espresso-notices '
840
+							. $css_class
841
+							. '" style="display:none;"><p>'
842
+							. $success_messages
843
+							. '</p>'
844
+							. $close
845
+							. '</div>';
846
+			}
847
+			if ($attention_messages !== '') {
848
+				$css_id    = is_admin() ? 'message' : 'espresso-notices-attention';
849
+				$css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
850
+				//showMessage( $error_messages, TRUE );
851
+				$notices .= '<div id="'
852
+							. $css_id
853
+							. '" class="espresso-notices '
854
+							. $css_class
855
+							. '" style="display:none;"><p>'
856
+							. $attention_messages
857
+							. '</p>'
858
+							. $close
859
+							. '</div>';
860
+			}
861
+			if ($error_messages !== '') {
862
+				$css_id    = is_admin() ? 'message' : 'espresso-notices-error';
863
+				$css_class = is_admin() ? 'error' : 'error fade-away';
864
+				//showMessage( $error_messages, TRUE );
865
+				$notices .= '<div id="'
866
+							. $css_id
867
+							. '" class="espresso-notices '
868
+							. $css_class
869
+							. '" style="display:none;"><p>'
870
+							. $error_messages
871
+							. '</p>'
872
+							. $close
873
+							. '</div>';
874
+			}
875
+			$notices .= '</div>';
876
+		} else {
877
+
878
+			$notices = array(
879
+				'success'   => $success_messages,
880
+				'attention' => $attention_messages,
881
+				'errors'    => $error_messages,
882
+			);
883
+			if ($remove_empty) {
884
+				// remove empty notices
885
+				foreach ($notices as $type => $notice) {
886
+					if (empty($notice)) {
887
+						unset($notices[$type]);
888
+					}
889
+				}
890
+			}
891
+		}
892
+		if ($print_scripts) {
893
+			self::_print_scripts();
894
+		}
895
+		return $notices;
896
+	}
897
+
898
+
899
+
900
+	/**
901
+	 * _print_scripts
902
+	 *
903
+	 * @param    bool $force_print
904
+	 * @return    string
905
+	 */
906
+	private static function _print_scripts($force_print = false)
907
+	{
908
+		if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
909
+			if (wp_script_is('ee_error_js', 'enqueued')) {
910
+				return '';
911
+			}
912
+			if (wp_script_is('ee_error_js', 'registered')) {
913
+				wp_enqueue_style('espresso_default');
914
+				wp_enqueue_style('espresso_custom_css');
915
+				wp_enqueue_script('ee_error_js');
916
+				wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
917
+			}
918
+		} else {
919
+			return '
920 920
 <script>
921 921
 /* <![CDATA[ */
922 922
 var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
@@ -926,223 +926,223 @@  discard block
 block discarded – undo
926 926
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
927 927
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
928 928
 ';
929
-        }
930
-        return '';
931
-    }
932
-
933
-
934
-
935
-    /**
936
-     * @return void
937
-     */
938
-    public static function enqueue_error_scripts()
939
-    {
940
-        self::_print_scripts();
941
-    }
942
-
943
-
944
-
945
-    /**
946
-     * create error code from filepath, function name,
947
-     * and line number where exception or error was thrown
948
-     *
949
-     * @param string $file
950
-     * @param string $func
951
-     * @param string $line
952
-     * @return string
953
-     */
954
-    public static function generate_error_code($file = '', $func = '', $line = '')
955
-    {
956
-        $file       = explode('.', basename($file));
957
-        $error_code = ! empty($file[0]) ? $file[0] : '';
958
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
959
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
960
-        return $error_code;
961
-    }
962
-
963
-
964
-
965
-    /**
966
-     * write exception details to log file
967
-     * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
968
-     *
969
-     * @param int   $time
970
-     * @param array $ex
971
-     * @param bool  $clear
972
-     * @return void
973
-     */
974
-    public function write_to_error_log($time = 0, $ex = array(), $clear = false)
975
-    {
976
-        if (empty($ex)) {
977
-            return;
978
-        }
979
-        if (! $time) {
980
-            $time = time();
981
-        }
982
-        $exception_log = '----------------------------------------------------------------------------------------'
983
-                         . PHP_EOL;
984
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
985
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
986
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
987
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
988
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
989
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
990
-        $exception_log .= $ex['string'] . PHP_EOL;
991
-        $exception_log .= '----------------------------------------------------------------------------------------'
992
-                          . PHP_EOL;
993
-        try {
994
-            error_log($exception_log);
995
-        } catch (EE_Error $e) {
996
-            EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
997
-                'event_espresso'), $e->getMessage()));
998
-        }
999
-    }
1000
-
1001
-
1002
-
1003
-    /**
1004
-     * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1005
-     * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1006
-     * but the code execution is done in a manner that could lead to unexpected results
1007
-     * (i.e. running to early, or too late in WP or EE loading process).
1008
-     * A good test for knowing whether to use this method is:
1009
-     * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1010
-     * Yes -> use EE_Error::add_error() or throw new EE_Error()
1011
-     * 2. If this is loaded before something else, it won't break anything,
1012
-     * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1013
-     *
1014
-     * @uses   constant WP_DEBUG test if wp_debug is on or not
1015
-     * @param string $function      The function that was called
1016
-     * @param string $message       A message explaining what has been done incorrectly
1017
-     * @param string $version       The version of Event Espresso where the error was added
1018
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1019
-     *                              for a deprecated function. This allows deprecation to occur during one version,
1020
-     *                              but not have any notices appear until a later version. This allows developers
1021
-     *                              extra time to update their code before notices appear.
1022
-     * @param int    $error_type
1023
-     */
1024
-    public static function doing_it_wrong(
1025
-        $function,
1026
-        $message,
1027
-        $version,
1028
-        $applies_when = '',
1029
-        $error_type = null
1030
-    ) {
1031
-        if (defined('WP_DEBUG') && WP_DEBUG) {
1032
-            EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1033
-        }
1034
-    }
1035
-
1036
-
1037
-
1038
-    /**
1039
-     * Like get_notices, but returns an array of all the notices of the given type.
1040
-     *
1041
-     * @return array {
1042
-     *  @type array $success   all the success messages
1043
-     *  @type array $errors    all the error messages
1044
-     *  @type array $attention all the attention messages
1045
-     * }
1046
-     */
1047
-    public static function get_raw_notices()
1048
-    {
1049
-        return self::$_espresso_notices;
1050
-    }
1051
-
1052
-
1053
-
1054
-    /**
1055
-     * @deprecated 4.9.27
1056
-     * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1057
-     * @param string $pan_message  the message to be stored persistently until dismissed
1058
-     * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1059
-     * @return void
1060
-     * @throws InvalidDataTypeException
1061
-     */
1062
-    public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
1063
-    {
1064
-        new PersistentAdminNotice(
1065
-            $pan_name,
1066
-            $pan_message,
1067
-            $force_update
1068
-        );
1069
-        EE_Error::doing_it_wrong(
1070
-            __METHOD__,
1071
-            sprintf(
1072
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1073
-                '\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1074
-            ),
1075
-            '4.9.27'
1076
-        );
1077
-    }
1078
-
1079
-
1080
-
1081
-    /**
1082
-     * @deprecated 4.9.27
1083
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1084
-     * @param bool   $purge
1085
-     * @param bool   $return
1086
-     * @throws DomainException
1087
-     * @throws InvalidInterfaceException
1088
-     * @throws InvalidDataTypeException
1089
-     * @throws ServiceNotFoundException
1090
-     * @throws InvalidArgumentException
1091
-     */
1092
-    public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return = false)
1093
-    {
1094
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1095
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1096
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1097
-        );
1098
-        $persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1099
-        EE_Error::doing_it_wrong(
1100
-            __METHOD__,
1101
-            sprintf(
1102
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1103
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1104
-            ),
1105
-            '4.9.27'
1106
-        );
1107
-    }
1108
-
1109
-
1110
-
1111
-    /**
1112
-     * @deprecated 4.9.27
1113
-     * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1114
-     * @param  string $pan_message the message to be stored persistently until dismissed
1115
-     * @param  string $return_url  URL to go back to after nag notice is dismissed
1116
-     */
1117
-    public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1118
-    {
1119
-        EE_Error::doing_it_wrong(
1120
-            __METHOD__,
1121
-            sprintf(
1122
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1123
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1124
-            ),
1125
-            '4.9.27'
1126
-        );
1127
-    }
1128
-
1129
-
1130
-
1131
-    /**
1132
-     * @deprecated 4.9.27
1133
-     * @param string $return_url
1134
-     */
1135
-    public static function get_persistent_admin_notices($return_url = '')
1136
-    {
1137
-        EE_Error::doing_it_wrong(
1138
-            __METHOD__,
1139
-            sprintf(
1140
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1141
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1142
-            ),
1143
-            '4.9.27'
1144
-        );
1145
-    }
929
+		}
930
+		return '';
931
+	}
932
+
933
+
934
+
935
+	/**
936
+	 * @return void
937
+	 */
938
+	public static function enqueue_error_scripts()
939
+	{
940
+		self::_print_scripts();
941
+	}
942
+
943
+
944
+
945
+	/**
946
+	 * create error code from filepath, function name,
947
+	 * and line number where exception or error was thrown
948
+	 *
949
+	 * @param string $file
950
+	 * @param string $func
951
+	 * @param string $line
952
+	 * @return string
953
+	 */
954
+	public static function generate_error_code($file = '', $func = '', $line = '')
955
+	{
956
+		$file       = explode('.', basename($file));
957
+		$error_code = ! empty($file[0]) ? $file[0] : '';
958
+		$error_code .= ! empty($func) ? ' - ' . $func : '';
959
+		$error_code .= ! empty($line) ? ' - ' . $line : '';
960
+		return $error_code;
961
+	}
962
+
963
+
964
+
965
+	/**
966
+	 * write exception details to log file
967
+	 * Since 4.9.53.rc.006 this writes to the standard PHP log file, not EE's custom log file
968
+	 *
969
+	 * @param int   $time
970
+	 * @param array $ex
971
+	 * @param bool  $clear
972
+	 * @return void
973
+	 */
974
+	public function write_to_error_log($time = 0, $ex = array(), $clear = false)
975
+	{
976
+		if (empty($ex)) {
977
+			return;
978
+		}
979
+		if (! $time) {
980
+			$time = time();
981
+		}
982
+		$exception_log = '----------------------------------------------------------------------------------------'
983
+						 . PHP_EOL;
984
+		$exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
985
+		$exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
986
+		$exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
987
+		$exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
988
+		$exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
989
+		$exception_log .= 'Stack trace: ' . PHP_EOL;
990
+		$exception_log .= $ex['string'] . PHP_EOL;
991
+		$exception_log .= '----------------------------------------------------------------------------------------'
992
+						  . PHP_EOL;
993
+		try {
994
+			error_log($exception_log);
995
+		} catch (EE_Error $e) {
996
+			EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
997
+				'event_espresso'), $e->getMessage()));
998
+		}
999
+	}
1000
+
1001
+
1002
+
1003
+	/**
1004
+	 * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1005
+	 * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1006
+	 * but the code execution is done in a manner that could lead to unexpected results
1007
+	 * (i.e. running to early, or too late in WP or EE loading process).
1008
+	 * A good test for knowing whether to use this method is:
1009
+	 * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1010
+	 * Yes -> use EE_Error::add_error() or throw new EE_Error()
1011
+	 * 2. If this is loaded before something else, it won't break anything,
1012
+	 * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1013
+	 *
1014
+	 * @uses   constant WP_DEBUG test if wp_debug is on or not
1015
+	 * @param string $function      The function that was called
1016
+	 * @param string $message       A message explaining what has been done incorrectly
1017
+	 * @param string $version       The version of Event Espresso where the error was added
1018
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1019
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
1020
+	 *                              but not have any notices appear until a later version. This allows developers
1021
+	 *                              extra time to update their code before notices appear.
1022
+	 * @param int    $error_type
1023
+	 */
1024
+	public static function doing_it_wrong(
1025
+		$function,
1026
+		$message,
1027
+		$version,
1028
+		$applies_when = '',
1029
+		$error_type = null
1030
+	) {
1031
+		if (defined('WP_DEBUG') && WP_DEBUG) {
1032
+			EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1033
+		}
1034
+	}
1035
+
1036
+
1037
+
1038
+	/**
1039
+	 * Like get_notices, but returns an array of all the notices of the given type.
1040
+	 *
1041
+	 * @return array {
1042
+	 *  @type array $success   all the success messages
1043
+	 *  @type array $errors    all the error messages
1044
+	 *  @type array $attention all the attention messages
1045
+	 * }
1046
+	 */
1047
+	public static function get_raw_notices()
1048
+	{
1049
+		return self::$_espresso_notices;
1050
+	}
1051
+
1052
+
1053
+
1054
+	/**
1055
+	 * @deprecated 4.9.27
1056
+	 * @param string $pan_name     the name, or key of the Persistent Admin Notice to be stored
1057
+	 * @param string $pan_message  the message to be stored persistently until dismissed
1058
+	 * @param bool   $force_update allows one to enforce the reappearance of a persistent message.
1059
+	 * @return void
1060
+	 * @throws InvalidDataTypeException
1061
+	 */
1062
+	public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
1063
+	{
1064
+		new PersistentAdminNotice(
1065
+			$pan_name,
1066
+			$pan_message,
1067
+			$force_update
1068
+		);
1069
+		EE_Error::doing_it_wrong(
1070
+			__METHOD__,
1071
+			sprintf(
1072
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1073
+				'\EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
1074
+			),
1075
+			'4.9.27'
1076
+		);
1077
+	}
1078
+
1079
+
1080
+
1081
+	/**
1082
+	 * @deprecated 4.9.27
1083
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
1084
+	 * @param bool   $purge
1085
+	 * @param bool   $return
1086
+	 * @throws DomainException
1087
+	 * @throws InvalidInterfaceException
1088
+	 * @throws InvalidDataTypeException
1089
+	 * @throws ServiceNotFoundException
1090
+	 * @throws InvalidArgumentException
1091
+	 */
1092
+	public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return = false)
1093
+	{
1094
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
1095
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
1096
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1097
+		);
1098
+		$persistent_admin_notice_manager->dismissNotice($pan_name, $purge, $return);
1099
+		EE_Error::doing_it_wrong(
1100
+			__METHOD__,
1101
+			sprintf(
1102
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1103
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1104
+			),
1105
+			'4.9.27'
1106
+		);
1107
+	}
1108
+
1109
+
1110
+
1111
+	/**
1112
+	 * @deprecated 4.9.27
1113
+	 * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
1114
+	 * @param  string $pan_message the message to be stored persistently until dismissed
1115
+	 * @param  string $return_url  URL to go back to after nag notice is dismissed
1116
+	 */
1117
+	public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
1118
+	{
1119
+		EE_Error::doing_it_wrong(
1120
+			__METHOD__,
1121
+			sprintf(
1122
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1123
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1124
+			),
1125
+			'4.9.27'
1126
+		);
1127
+	}
1128
+
1129
+
1130
+
1131
+	/**
1132
+	 * @deprecated 4.9.27
1133
+	 * @param string $return_url
1134
+	 */
1135
+	public static function get_persistent_admin_notices($return_url = '')
1136
+	{
1137
+		EE_Error::doing_it_wrong(
1138
+			__METHOD__,
1139
+			sprintf(
1140
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
1141
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
1142
+			),
1143
+			'4.9.27'
1144
+		);
1145
+	}
1146 1146
 
1147 1147
 
1148 1148
 
@@ -1157,27 +1157,27 @@  discard block
 block discarded – undo
1157 1157
  */
1158 1158
 function espresso_error_enqueue_scripts()
1159 1159
 {
1160
-    // js for error handling
1161
-    wp_register_script(
1162
-        'espresso_core',
1163
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1164
-        array('jquery'),
1165
-        EVENT_ESPRESSO_VERSION,
1166
-        false
1167
-    );
1168
-    wp_register_script(
1169
-        'ee_error_js',
1170
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1171
-        array('espresso_core'),
1172
-        EVENT_ESPRESSO_VERSION,
1173
-        false
1174
-    );
1160
+	// js for error handling
1161
+	wp_register_script(
1162
+		'espresso_core',
1163
+		EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1164
+		array('jquery'),
1165
+		EVENT_ESPRESSO_VERSION,
1166
+		false
1167
+	);
1168
+	wp_register_script(
1169
+		'ee_error_js',
1170
+		EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1171
+		array('espresso_core'),
1172
+		EVENT_ESPRESSO_VERSION,
1173
+		false
1174
+	);
1175 1175
 }
1176 1176
 
1177 1177
 if (is_admin()) {
1178
-    add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1178
+	add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1179 1179
 } else {
1180
-    add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1180
+	add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1181 1181
 }
1182 1182
 
1183 1183
 
Please login to merge, or discard this patch.
Spacing   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -103,14 +103,14 @@  discard block
 block discarded – undo
103 103
             default :
104 104
                 $to = get_option('admin_email');
105 105
         }
106
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
106
+        $subject = $type.' '.$message.' in '.EVENT_ESPRESSO_VERSION.' on '.site_url();
107 107
         $msg = EE_Error::_format_error($type, $message, $file, $line);
108 108
         if (function_exists('wp_mail')) {
109 109
             add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
110 110
             wp_mail($to, $subject, $msg);
111 111
         }
112 112
         echo '<div id="message" class="espresso-notices error"><p>';
113
-        echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
113
+        echo $type.': '.$message.'<br />'.$file.' line '.$line;
114 114
         echo '<br /></p></div>';
115 115
     }
116 116
 
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
             ? true
258 258
             : false;
259 259
         if ($check_stored && ! $has_error) {
260
-            $notices = (array)get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
260
+            $notices = (array) get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
261 261
             foreach ($notices as $type => $notice) {
262 262
                 if ($type === $type_to_check && $notice) {
263 263
                     return true;
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 	}
333 333
 </style>
334 334
 <div id="ee-error-message" class="error">';
335
-        if (! WP_DEBUG) {
335
+        if ( ! WP_DEBUG) {
336 336
             $output .= '
337 337
 	<p>';
338 338
         }
@@ -391,14 +391,14 @@  discard block
 block discarded – undo
391 391
                     $class_dsply = ! empty($class) ? $class : '&nbsp;';
392 392
                     $type_dsply = ! empty($type) ? $type : '&nbsp;';
393 393
                     $function_dsply = ! empty($function) ? $function : '&nbsp;';
394
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
394
+                    $args_dsply = ! empty($args) ? '( '.$args.' )' : '';
395 395
                     $trace_details .= '
396 396
 					<tr>
397
-						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
398
-						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
399
-						<td align="left" class="' . $zebra . '">' . $file_dsply . '</td>
400
-						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
401
-						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
397
+						<td align="right" class="' . $zebra.'">'.$nmbr_dsply.'</td>
398
+						<td align="right" class="' . $zebra.'">'.$line_dsply.'</td>
399
+						<td align="left" class="' . $zebra.'">'.$file_dsply.'</td>
400
+						<td align="left" class="' . $zebra.'">'.$class_dsply.'</td>
401
+						<td align="left" class="' . $zebra.'">'.$type_dsply.$function_dsply.$args_dsply.'</td>
402 402
 					</tr>';
403 403
                 }
404 404
                 $trace_details .= '
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
             }
408 408
             $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
409 409
             // add generic non-identifying messages for non-privileged users
410
-            if (! WP_DEBUG) {
410
+            if ( ! WP_DEBUG) {
411 411
                 $output .= '<span class="ee-error-user-msg-spn">'
412 412
                            . trim($ex['msg'])
413 413
                            . '</span> &nbsp; <sup>'
@@ -449,14 +449,14 @@  discard block
 block discarded – undo
449 449
                            . '-dv" class="ee-error-trace-dv" style="display: none;">
450 450
 				'
451 451
                            . $trace_details;
452
-                if (! empty($class)) {
452
+                if ( ! empty($class)) {
453 453
                     $output .= '
454 454
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
455 455
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
456 456
 						<h3>Class Details</h3>';
457 457
                     $a = new ReflectionClass($class);
458 458
                     $output .= '
459
-						<pre>' . $a . '</pre>
459
+						<pre>' . $a.'</pre>
460 460
 					</div>
461 461
 				</div>';
462 462
                 }
@@ -469,7 +469,7 @@  discard block
 block discarded – undo
469 469
         }
470 470
         // remove last linebreak
471 471
         $output = substr($output, 0, -6);
472
-        if (! WP_DEBUG) {
472
+        if ( ! WP_DEBUG) {
473 473
             $output .= '
474 474
 	</p>';
475 475
         }
@@ -496,20 +496,20 @@  discard block
 block discarded – undo
496 496
     private function _convert_args_to_string($arguments = array(), $array = false)
497 497
     {
498 498
         $arg_string = '';
499
-        if (! empty($arguments)) {
499
+        if ( ! empty($arguments)) {
500 500
             $args = array();
501 501
             foreach ($arguments as $arg) {
502
-                if (! empty($arg)) {
502
+                if ( ! empty($arg)) {
503 503
                     if (is_string($arg)) {
504
-                        $args[] = " '" . $arg . "'";
504
+                        $args[] = " '".$arg."'";
505 505
                     } elseif (is_array($arg)) {
506
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
506
+                        $args[] = 'ARRAY('.$this->_convert_args_to_string($arg, true);
507 507
                     } elseif ($arg === null) {
508 508
                         $args[] = ' NULL';
509 509
                     } elseif (is_bool($arg)) {
510 510
                         $args[] = ($arg) ? ' TRUE' : ' FALSE';
511 511
                     } elseif (is_object($arg)) {
512
-                        $args[] = ' OBJECT ' . get_class($arg);
512
+                        $args[] = ' OBJECT '.get_class($arg);
513 513
                     } elseif (is_resource($arg)) {
514 514
                         $args[] = get_resource_type($arg);
515 515
                     } else {
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
     {
613 613
         if (empty($msg)) {
614 614
             EE_Error::doing_it_wrong(
615
-                'EE_Error::add_' . $type . '()',
615
+                'EE_Error::add_'.$type.'()',
616 616
                 sprintf(
617 617
                     __('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
618 618
                         'event_espresso'),
@@ -648,11 +648,11 @@  discard block
 block discarded – undo
648 648
         do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
649 649
         $msg = WP_DEBUG ? $dev_msg : $user_msg;
650 650
         // add notice if message exists
651
-        if (! empty($msg)) {
651
+        if ( ! empty($msg)) {
652 652
             // get error code
653 653
             $notice_code = EE_Error::generate_error_code($file, $func, $line);
654 654
             if (WP_DEBUG && $type === 'errors') {
655
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
655
+                $msg .= '<br/><span class="tiny-text">'.$notice_code.'</span>';
656 656
             }
657 657
             // add notice. Index by code if it's not blank
658 658
             if ($notice_code) {
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
         // EEH_Debug_Tools::printr( self::$_espresso_notices, 'espresso_notices  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
779 779
         // either save notices to the db
780 780
         if ($save_to_transient || isset($_REQUEST['activate-selected'])) {
781
-            $existing_notices  = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
781
+            $existing_notices = get_option(EE_Error::OPTIONS_KEY_NOTICES, array());
782 782
             $existing_notices = is_array($existing_notices) ? $existing_notices : array();
783 783
             self::$_espresso_notices = array_merge(
784 784
                 $existing_notices,
@@ -808,13 +808,13 @@  discard block
 block discarded – undo
808 808
         if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
809 809
             // combine messages
810 810
             $success_messages .= implode(self::$_espresso_notices['success'], '<br />');
811
-            $print_scripts    = true;
811
+            $print_scripts = true;
812 812
         }
813 813
         // check for attention messages
814 814
         if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
815 815
             // combine messages
816 816
             $attention_messages .= implode(self::$_espresso_notices['attention'], '<br />');
817
-            $print_scripts      = true;
817
+            $print_scripts = true;
818 818
         }
819 819
         // check for error messages
820 820
         if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
                 : __('An error has occurred:<br />', 'event_espresso');
824 824
             // combine messages
825 825
             $error_messages .= implode(self::$_espresso_notices['errors'], '<br />');
826
-            $print_scripts  = true;
826
+            $print_scripts = true;
827 827
         }
828 828
         if ($format_output) {
829 829
 
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
      */
906 906
     private static function _print_scripts($force_print = false)
907 907
     {
908
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
908
+        if ( ! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
909 909
             if (wp_script_is('ee_error_js', 'enqueued')) {
910 910
                 return '';
911 911
             }
@@ -919,12 +919,12 @@  discard block
 block discarded – undo
919 919
             return '
920 920
 <script>
921 921
 /* <![CDATA[ */
922
-var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
922
+var ee_settings = {"wp_debug":"' . WP_DEBUG.'"};
923 923
 /* ]]> */
924 924
 </script>
925
-<script src="' . includes_url() . 'js/jquery/jquery.js" type="text/javascript"></script>
926
-<script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
927
-<script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
925
+<script src="' . includes_url().'js/jquery/jquery.js" type="text/javascript"></script>
926
+<script src="' . EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
927
+<script src="' . EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js'.'?ver='.espresso_version().'" type="text/javascript"></script>
928 928
 ';
929 929
         }
930 930
         return '';
@@ -955,8 +955,8 @@  discard block
 block discarded – undo
955 955
     {
956 956
         $file       = explode('.', basename($file));
957 957
         $error_code = ! empty($file[0]) ? $file[0] : '';
958
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
959
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
958
+        $error_code .= ! empty($func) ? ' - '.$func : '';
959
+        $error_code .= ! empty($line) ? ' - '.$line : '';
960 960
         return $error_code;
961 961
     }
962 962
 
@@ -976,18 +976,18 @@  discard block
 block discarded – undo
976 976
         if (empty($ex)) {
977 977
             return;
978 978
         }
979
-        if (! $time) {
979
+        if ( ! $time) {
980 980
             $time = time();
981 981
         }
982 982
         $exception_log = '----------------------------------------------------------------------------------------'
983 983
                          . PHP_EOL;
984
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
985
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
986
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
987
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
988
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
989
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
990
-        $exception_log .= $ex['string'] . PHP_EOL;
984
+        $exception_log .= '['.date('Y-m-d H:i:s', $time).']  Exception Details'.PHP_EOL;
985
+        $exception_log .= 'Message: '.$ex['msg'].PHP_EOL;
986
+        $exception_log .= 'Code: '.$ex['code'].PHP_EOL;
987
+        $exception_log .= 'File: '.$ex['file'].PHP_EOL;
988
+        $exception_log .= 'Line No: '.$ex['line'].PHP_EOL;
989
+        $exception_log .= 'Stack trace: '.PHP_EOL;
990
+        $exception_log .= $ex['string'].PHP_EOL;
991 991
         $exception_log .= '----------------------------------------------------------------------------------------'
992 992
                           . PHP_EOL;
993 993
         try {
@@ -1160,14 +1160,14 @@  discard block
 block discarded – undo
1160 1160
     // js for error handling
1161 1161
     wp_register_script(
1162 1162
         'espresso_core',
1163
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1163
+        EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
1164 1164
         array('jquery'),
1165 1165
         EVENT_ESPRESSO_VERSION,
1166 1166
         false
1167 1167
     );
1168 1168
     wp_register_script(
1169 1169
         'ee_error_js',
1170
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1170
+        EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
1171 1171
         array('espresso_core'),
1172 1172
         EVENT_ESPRESSO_VERSION,
1173 1173
         false
Please login to merge, or discard this patch.
core/EE_Config.core.php 2 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
      * @param    string         $name
534 534
      * @param    string         $config_class
535 535
      * @param    EE_Config_Base $config_obj
536
-     * @param    array          $tests_to_run
536
+     * @param    integer[]          $tests_to_run
537 537
      * @param    bool           $display_errors
538 538
      * @return    bool    TRUE on success, FALSE on fail
539 539
      */
@@ -797,7 +797,7 @@  discard block
 block discarded – undo
797 797
      * @access    public
798 798
      * @param    string                $section
799 799
      * @param    string                $name
800
-     * @param    EE_Config_Base|string $config_obj
800
+     * @param    EE_Config_Base $config_obj
801 801
      * @param    bool                  $throw_errors
802 802
      * @return    bool
803 803
      */
@@ -1764,7 +1764,7 @@  discard block
 block discarded – undo
1764 1764
 
1765 1765
 
1766 1766
     /**
1767
-     * @return array
1767
+     * @return integer[]
1768 1768
      */
1769 1769
     public function get_critical_pages_array()
1770 1770
     {
@@ -1779,7 +1779,7 @@  discard block
 block discarded – undo
1779 1779
 
1780 1780
 
1781 1781
     /**
1782
-     * @return array
1782
+     * @return string[]
1783 1783
      */
1784 1784
     public function get_critical_pages_shortcodes_array()
1785 1785
     {
@@ -3122,7 +3122,7 @@  discard block
 block discarded – undo
3122 3122
      * according to max_input_vars
3123 3123
      *
3124 3124
      * @param int   $input_count the count of input vars.
3125
-     * @return array {
3125
+     * @return string {
3126 3126
      *                           An array that represents whether available space and if no available space the error
3127 3127
      *                           message.
3128 3128
      * @type bool   $has_space   whether more inputs can be added.
Please login to merge, or discard this patch.
Indentation   +3060 added lines, -3060 removed lines patch added patch discarded remove patch
@@ -17,2442 +17,2442 @@  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
+			if ($addon_config_obj instanceof EE_Config_Base) {
449
+				$this->update_config('addons', $addon_name, $addon_config_obj, false);
450
+			}
451
+			$this->addons->{$addon_name} = null;
452
+		}
453
+	}
454
+
455
+
456
+
457
+	/**
458
+	 *    update_espresso_config
459
+	 *
460
+	 * @access   public
461
+	 * @param   bool $add_success
462
+	 * @param   bool $add_error
463
+	 * @return   bool
464
+	 */
465
+	public function update_espresso_config($add_success = false, $add_error = true)
466
+	{
467
+		// don't allow config updates during WP heartbeats
468
+		if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
469
+			return false;
470
+		}
471
+		// commented out the following re: https://events.codebasehq.com/projects/event-espresso/tickets/8197
472
+		//$clone = clone( self::$_instance );
473
+		//self::$_instance = NULL;
474
+		do_action('AHEE__EE_Config__update_espresso_config__begin', $this);
475
+		$this->_reset_espresso_addon_config();
476
+		// hook into update_option because that happens AFTER the ( $value === $old_value ) conditional
477
+		// but BEFORE the actual update occurs
478
+		add_action('update_option', array($this, 'double_check_config_comparison'), 1, 3);
479
+		// don't want to persist legacy_shortcodes_manager, but don't want to lose it either
480
+		$legacy_shortcodes_manager = $this->legacy_shortcodes_manager;
481
+		$this->legacy_shortcodes_manager = null;
482
+		// now update "ee_config"
483
+		$saved = update_option(EE_Config::OPTION_NAME, $this);
484
+		$this->legacy_shortcodes_manager = $legacy_shortcodes_manager;
485
+		EE_Config::log(EE_Config::OPTION_NAME);
486
+		// if not saved... check if the hook we just added still exists;
487
+		// if it does, it means one of two things:
488
+		// 		that update_option bailed at the ( $value === $old_value ) conditional,
489
+		//		 or...
490
+		// 		the db update query returned 0 rows affected
491
+		// 		(probably because the data  value was the same from it's perspective)
492
+		// so the existence of the hook means that a negative result from update_option is NOT an error,
493
+		// but just means no update occurred, so don't display an error to the user.
494
+		// BUT... if update_option returns FALSE, AND the hook is missing,
495
+		// then it means that something truly went wrong
496
+		$saved = ! $saved ? has_action('update_option', array($this, 'double_check_config_comparison')) : $saved;
497
+		// remove our action since we don't want it in the system anymore
498
+		remove_action('update_option', array($this, 'double_check_config_comparison'), 1);
499
+		do_action('AHEE__EE_Config__update_espresso_config__end', $this, $saved);
500
+		//self::$_instance = $clone;
501
+		//unset( $clone );
502
+		// if config remains the same or was updated successfully
503
+		if ($saved) {
504
+			if ($add_success) {
505
+				EE_Error::add_success(
506
+					__('The Event Espresso Configuration Settings have been successfully updated.', 'event_espresso'),
507
+					__FILE__,
508
+					__FUNCTION__,
509
+					__LINE__
510
+				);
511
+			}
512
+			return true;
513
+		} else {
514
+			if ($add_error) {
515
+				EE_Error::add_error(
516
+					__('The Event Espresso Configuration Settings were not updated.', 'event_espresso'),
517
+					__FILE__,
518
+					__FUNCTION__,
519
+					__LINE__
520
+				);
521
+			}
522
+			return false;
523
+		}
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 *    _verify_config_params
530
+	 *
531
+	 * @access    private
532
+	 * @param    string         $section
533
+	 * @param    string         $name
534
+	 * @param    string         $config_class
535
+	 * @param    EE_Config_Base $config_obj
536
+	 * @param    array          $tests_to_run
537
+	 * @param    bool           $display_errors
538
+	 * @return    bool    TRUE on success, FALSE on fail
539
+	 */
540
+	private function _verify_config_params(
541
+		$section = '',
542
+		$name = '',
543
+		$config_class = '',
544
+		$config_obj = null,
545
+		$tests_to_run = array(1, 2, 3, 4, 5, 6, 7, 8),
546
+		$display_errors = true
547
+	) {
548
+		try {
549
+			foreach ($tests_to_run as $test) {
550
+				switch ($test) {
551
+					// TEST #1 : check that section was set
552
+					case 1 :
553
+						if (empty($section)) {
554
+							if ($display_errors) {
555
+								throw new EE_Error(
556
+									sprintf(
557
+										__(
558
+											'No configuration section has been provided while attempting to save "%s".',
559
+											'event_espresso'
560
+										),
561
+										$config_class
562
+									)
563
+								);
564
+							}
565
+							return false;
566
+						}
567
+						break;
568
+					// TEST #2 : check that settings section exists
569
+					case 2 :
570
+						if (! isset($this->{$section})) {
571
+							if ($display_errors) {
572
+								throw new EE_Error(
573
+									sprintf(
574
+										__('The "%s" configuration section does not exist.', 'event_espresso'),
575
+										$section
576
+									)
577
+								);
578
+							}
579
+							return false;
580
+						}
581
+						break;
582
+					// TEST #3 : check that section is the proper format
583
+					case 3 :
584
+						if (
585
+						! ($this->{$section} instanceof EE_Config_Base || $this->{$section} instanceof stdClass)
586
+						) {
587
+							if ($display_errors) {
588
+								throw new EE_Error(
589
+									sprintf(
590
+										__(
591
+											'The "%s" configuration settings have not been formatted correctly.',
592
+											'event_espresso'
593
+										),
594
+										$section
595
+									)
596
+								);
597
+							}
598
+							return false;
599
+						}
600
+						break;
601
+					// TEST #4 : check that config section name has been set
602
+					case 4 :
603
+						if (empty($name)) {
604
+							if ($display_errors) {
605
+								throw new EE_Error(
606
+									__(
607
+										'No name has been provided for the specific configuration section.',
608
+										'event_espresso'
609
+									)
610
+								);
611
+							}
612
+							return false;
613
+						}
614
+						break;
615
+					// TEST #5 : check that a config class name has been set
616
+					case 5 :
617
+						if (empty($config_class)) {
618
+							if ($display_errors) {
619
+								throw new EE_Error(
620
+									__(
621
+										'No class name has been provided for the specific configuration section.',
622
+										'event_espresso'
623
+									)
624
+								);
625
+							}
626
+							return false;
627
+						}
628
+						break;
629
+					// TEST #6 : verify config class is accessible
630
+					case 6 :
631
+						if (! class_exists($config_class)) {
632
+							if ($display_errors) {
633
+								throw new EE_Error(
634
+									sprintf(
635
+										__(
636
+											'The "%s" class does not exist. Please ensure that an autoloader has been set for it.',
637
+											'event_espresso'
638
+										),
639
+										$config_class
640
+									)
641
+								);
642
+							}
643
+							return false;
644
+						}
645
+						break;
646
+					// TEST #7 : check that config has even been set
647
+					case 7 :
648
+						if (! isset($this->{$section}->{$name})) {
649
+							if ($display_errors) {
650
+								throw new EE_Error(
651
+									sprintf(
652
+										__('No configuration has been set for "%1$s->%2$s".', 'event_espresso'),
653
+										$section,
654
+										$name
655
+									)
656
+								);
657
+							}
658
+							return false;
659
+						} else {
660
+							// and make sure it's not serialized
661
+							$this->{$section}->{$name} = maybe_unserialize($this->{$section}->{$name});
662
+						}
663
+						break;
664
+					// TEST #8 : check that config is the requested type
665
+					case 8 :
666
+						if (! $this->{$section}->{$name} instanceof $config_class) {
667
+							if ($display_errors) {
668
+								throw new EE_Error(
669
+									sprintf(
670
+										__(
671
+											'The configuration for "%1$s->%2$s" is not of the "%3$s" class.',
672
+											'event_espresso'
673
+										),
674
+										$section,
675
+										$name,
676
+										$config_class
677
+									)
678
+								);
679
+							}
680
+							return false;
681
+						}
682
+						break;
683
+					// TEST #9 : verify config object
684
+					case 9 :
685
+						if (! $config_obj instanceof EE_Config_Base) {
686
+							if ($display_errors) {
687
+								throw new EE_Error(
688
+									sprintf(
689
+										__('The "%s" class is not an instance of EE_Config_Base.', 'event_espresso'),
690
+										print_r($config_obj, true)
691
+									)
692
+								);
693
+							}
694
+							return false;
695
+						}
696
+						break;
697
+				}
698
+			}
699
+		} catch (EE_Error $e) {
700
+			$e->get_error();
701
+		}
702
+		// you have successfully run the gauntlet
703
+		return true;
704
+	}
705
+
706
+
707
+
708
+	/**
709
+	 *    _generate_config_option_name
710
+	 *
711
+	 * @access        protected
712
+	 * @param        string $section
713
+	 * @param        string $name
714
+	 * @return        string
715
+	 */
716
+	private function _generate_config_option_name($section = '', $name = '')
717
+	{
718
+		return 'ee_config-' . strtolower($section . '-' . str_replace(array('EE_', 'EED_'), '', $name));
719
+	}
720
+
721
+
722
+
723
+	/**
724
+	 *    _set_config_class
725
+	 * ensures that a config class is set, either from a passed config class or one generated from the config name
726
+	 *
727
+	 * @access    private
728
+	 * @param    string $config_class
729
+	 * @param    string $name
730
+	 * @return    string
731
+	 */
732
+	private function _set_config_class($config_class = '', $name = '')
733
+	{
734
+		return ! empty($config_class)
735
+			? $config_class
736
+			: str_replace(' ', '_', ucwords(str_replace('_', ' ', $name))) . '_Config';
737
+	}
738
+
739
+
740
+
741
+	/**
742
+	 *    set_config
743
+	 *
744
+	 * @access    protected
745
+	 * @param    string         $section
746
+	 * @param    string         $name
747
+	 * @param    string         $config_class
748
+	 * @param    EE_Config_Base $config_obj
749
+	 * @return    EE_Config_Base
750
+	 */
751
+	public function set_config($section = '', $name = '', $config_class = '', EE_Config_Base $config_obj = null)
752
+	{
753
+		// ensure config class is set to something
754
+		$config_class = $this->_set_config_class($config_class, $name);
755
+		// run tests 1-4, 6, and 7 to verify all config params are set and valid
756
+		if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
757
+			return null;
758
+		}
759
+		$config_option_name = $this->_generate_config_option_name($section, $name);
760
+		// if the config option name hasn't been added yet to the list of option names we're tracking, then do so now
761
+		if (! isset($this->_addon_option_names[$config_option_name])) {
762
+			$this->_addon_option_names[$config_option_name] = $config_class;
763
+			$this->update_addon_option_names();
764
+		}
765
+		// verify the incoming config object but suppress errors
766
+		if (! $this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
767
+			$config_obj = new $config_class();
768
+		}
769
+		if (get_option($config_option_name)) {
770
+			EE_Config::log($config_option_name);
771
+			update_option($config_option_name, $config_obj);
772
+			$this->{$section}->{$name} = $config_obj;
773
+			return $this->{$section}->{$name};
774
+		} else {
775
+			// create a wp-option for this config
776
+			if (add_option($config_option_name, $config_obj, '', 'no')) {
777
+				$this->{$section}->{$name} = maybe_unserialize($config_obj);
778
+				return $this->{$section}->{$name};
779
+			} else {
780
+				EE_Error::add_error(
781
+					sprintf(__('The "%s" could not be saved to the database.', 'event_espresso'), $config_class),
782
+					__FILE__,
783
+					__FUNCTION__,
784
+					__LINE__
785
+				);
786
+				return null;
787
+			}
788
+		}
789
+	}
790
+
791
+
792
+
793
+	/**
794
+	 *    update_config
795
+	 * Important: the config object must ALREADY be set, otherwise this will produce an error.
796
+	 *
797
+	 * @access    public
798
+	 * @param    string                $section
799
+	 * @param    string                $name
800
+	 * @param    EE_Config_Base|string $config_obj
801
+	 * @param    bool                  $throw_errors
802
+	 * @return    bool
803
+	 */
804
+	public function update_config($section = '', $name = '', $config_obj = '', $throw_errors = true)
805
+	{
806
+		// don't allow config updates during WP heartbeats
807
+		if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
808
+			return false;
809
+		}
810
+		$config_obj = maybe_unserialize($config_obj);
811
+		// get class name of the incoming object
812
+		$config_class = get_class($config_obj);
813
+		// run tests 1-5 and 9 to verify config
814
+		if (! $this->_verify_config_params(
815
+			$section,
816
+			$name,
817
+			$config_class,
818
+			$config_obj,
819
+			array(1, 2, 3, 4, 7, 9)
820
+		)
821
+		) {
822
+			return false;
823
+		}
824
+		$config_option_name = $this->_generate_config_option_name($section, $name);
825
+		// check if config object has been added to db by seeing if config option name is in $this->_addon_option_names array
826
+		if (! isset($this->_addon_option_names[$config_option_name])) {
827
+			// save new config to db
828
+			if ($this->set_config($section, $name, $config_class, $config_obj)) {
829
+				return true;
830
+			}
831
+		} else {
832
+			// first check if the record already exists
833
+			$existing_config = get_option($config_option_name);
834
+			$config_obj = serialize($config_obj);
835
+			// just return if db record is already up to date (NOT type safe comparison)
836
+			if ($existing_config == $config_obj) {
837
+				$this->{$section}->{$name} = $config_obj;
838
+				return true;
839
+			} else if (update_option($config_option_name, $config_obj)) {
840
+				EE_Config::log($config_option_name);
841
+				// update wp-option for this config class
842
+				$this->{$section}->{$name} = $config_obj;
843
+				return true;
844
+			} elseif ($throw_errors) {
845
+				EE_Error::add_error(
846
+					sprintf(
847
+						__(
848
+							'The "%1$s" object stored at"%2$s" was not successfully updated in the database.',
849
+							'event_espresso'
850
+						),
851
+						$config_class,
852
+						'EE_Config->' . $section . '->' . $name
853
+					),
854
+					__FILE__,
855
+					__FUNCTION__,
856
+					__LINE__
857
+				);
858
+			}
859
+		}
860
+		return false;
861
+	}
862
+
863
+
864
+
865
+	/**
866
+	 *    get_config
867
+	 *
868
+	 * @access    public
869
+	 * @param    string $section
870
+	 * @param    string $name
871
+	 * @param    string $config_class
872
+	 * @return    mixed EE_Config_Base | NULL
873
+	 */
874
+	public function get_config($section = '', $name = '', $config_class = '')
875
+	{
876
+		// ensure config class is set to something
877
+		$config_class = $this->_set_config_class($config_class, $name);
878
+		// run tests 1-4, 6 and 7 to verify that all params have been set
879
+		if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
880
+			return null;
881
+		}
882
+		// now test if the requested config object exists, but suppress errors
883
+		if ($this->_verify_config_params($section, $name, $config_class, null, array(7, 8), false)) {
884
+			// config already exists, so pass it back
885
+			return $this->{$section}->{$name};
886
+		}
887
+		// load config option from db if it exists
888
+		$config_obj = $this->get_config_option($this->_generate_config_option_name($section, $name));
889
+		// verify the newly retrieved config object, but suppress errors
890
+		if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
891
+			// config is good, so set it and pass it back
892
+			$this->{$section}->{$name} = $config_obj;
893
+			return $this->{$section}->{$name};
894
+		}
895
+		// oops! $config_obj is not already set and does not exist in the db, so create a new one
896
+		$config_obj = $this->set_config($section, $name, $config_class);
897
+		// verify the newly created config object
898
+		if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9))) {
899
+			return $this->{$section}->{$name};
900
+		} else {
901
+			EE_Error::add_error(
902
+				sprintf(__('The "%s" could not be retrieved from the database.', 'event_espresso'), $config_class),
903
+				__FILE__,
904
+				__FUNCTION__,
905
+				__LINE__
906
+			);
907
+		}
908
+		return null;
909
+	}
910
+
911
+
912
+
913
+	/**
914
+	 *    get_config_option
915
+	 *
916
+	 * @access    public
917
+	 * @param    string $config_option_name
918
+	 * @return    mixed EE_Config_Base | FALSE
919
+	 */
920
+	public function get_config_option($config_option_name = '')
921
+	{
922
+		// retrieve the wp-option for this config class.
923
+		$config_option = maybe_unserialize(get_option($config_option_name, array()));
924
+		if (empty($config_option)) {
925
+			EE_Config::log($config_option_name . '-NOT-FOUND');
926
+		}
927
+		return $config_option;
928
+	}
929
+
930
+
931
+
932
+	/**
933
+	 * log
934
+	 *
935
+	 * @param string $config_option_name
936
+	 */
937
+	public static function log($config_option_name = '')
938
+	{
939
+		if (EE_Config::logging_enabled() && ! empty($config_option_name)) {
940
+			$config_log = get_option(EE_Config::LOG_NAME, array());
941
+			//copy incoming $_REQUEST and sanitize it so we can save it
942
+			$_request = $_REQUEST;
943
+			array_walk_recursive($_request, 'sanitize_text_field');
944
+			$config_log[(string)microtime(true)] = array(
945
+				'config_name' => $config_option_name,
946
+				'request'     => $_request,
947
+			);
948
+			update_option(EE_Config::LOG_NAME, $config_log);
949
+		}
950
+	}
951
+
952
+
953
+
954
+	/**
955
+	 * trim_log
956
+	 * reduces the size of the config log to the length specified by EE_Config::LOG_LENGTH
957
+	 */
958
+	public static function trim_log()
959
+	{
960
+		if (! EE_Config::logging_enabled()) {
961
+			return;
962
+		}
963
+		$config_log = maybe_unserialize(get_option(EE_Config::LOG_NAME, array()));
964
+		$log_length = count($config_log);
965
+		if ($log_length > EE_Config::LOG_LENGTH) {
966
+			ksort($config_log);
967
+			$config_log = array_slice($config_log, $log_length - EE_Config::LOG_LENGTH, null, true);
968
+			update_option(EE_Config::LOG_NAME, $config_log);
969
+		}
970
+	}
971
+
972
+
973
+
974
+	/**
975
+	 *    get_page_for_posts
976
+	 *    if the wp-option "show_on_front" is set to "page", then this is the post_name for the post set in the
977
+	 *    wp-option "page_for_posts", or "posts" if no page is selected
978
+	 *
979
+	 * @access    public
980
+	 * @return    string
981
+	 */
982
+	public static function get_page_for_posts()
983
+	{
984
+		$page_for_posts = get_option('page_for_posts');
985
+		if (! $page_for_posts) {
986
+			return 'posts';
987
+		}
988
+		/** @type WPDB $wpdb */
989
+		global $wpdb;
990
+		$SQL = "SELECT post_name from $wpdb->posts WHERE post_type='posts' OR post_type='page' AND post_status='publish' AND ID=%d";
991
+		return $wpdb->get_var($wpdb->prepare($SQL, $page_for_posts));
992
+	}
993
+
994
+
995
+
996
+	/**
997
+	 *    register_shortcodes_and_modules.
998
+	 *    At this point, it's too early to tell if we're maintenance mode or not.
999
+	 *    In fact, this is where we give modules a chance to let core know they exist
1000
+	 *    so they can help trigger maintenance mode if it's needed
1001
+	 *
1002
+	 * @access    public
1003
+	 * @return    void
1004
+	 */
1005
+	public function register_shortcodes_and_modules()
1006
+	{
1007
+		// allow modules to set hooks for the rest of the system
1008
+		EE_Registry::instance()->modules = $this->_register_modules();
1009
+	}
1010
+
1011
+
1012
+
1013
+	/**
1014
+	 *    initialize_shortcodes_and_modules
1015
+	 *    meaning they can start adding their hooks to get stuff done
1016
+	 *
1017
+	 * @access    public
1018
+	 * @return    void
1019
+	 */
1020
+	public function initialize_shortcodes_and_modules()
1021
+	{
1022
+		// allow modules to set hooks for the rest of the system
1023
+		$this->_initialize_modules();
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 *    widgets_init
1030
+	 *
1031
+	 * @access private
1032
+	 * @return void
1033
+	 */
1034
+	public function widgets_init()
1035
+	{
1036
+		//only init widgets on admin pages when not in complete maintenance, and
1037
+		//on frontend when not in any maintenance mode
1038
+		if (
1039
+			! EE_Maintenance_Mode::instance()->level()
1040
+			|| (
1041
+				is_admin()
1042
+				&& EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
1043
+			)
1044
+		) {
1045
+			// grab list of installed widgets
1046
+			$widgets_to_register = glob(EE_WIDGETS . '*', GLOB_ONLYDIR);
1047
+			// filter list of modules to register
1048
+			$widgets_to_register = apply_filters(
1049
+				'FHEE__EE_Config__register_widgets__widgets_to_register',
1050
+				$widgets_to_register
1051
+			);
1052
+			if (! empty($widgets_to_register)) {
1053
+				// cycle thru widget folders
1054
+				foreach ($widgets_to_register as $widget_path) {
1055
+					// add to list of installed widget modules
1056
+					EE_Config::register_ee_widget($widget_path);
1057
+				}
1058
+			}
1059
+			// filter list of installed modules
1060
+			EE_Registry::instance()->widgets = apply_filters(
1061
+				'FHEE__EE_Config__register_widgets__installed_widgets',
1062
+				EE_Registry::instance()->widgets
1063
+			);
1064
+		}
1065
+	}
1066
+
1067
+
1068
+
1069
+	/**
1070
+	 *    register_ee_widget - makes core aware of this widget
1071
+	 *
1072
+	 * @access    public
1073
+	 * @param    string $widget_path - full path up to and including widget folder
1074
+	 * @return    void
1075
+	 */
1076
+	public static function register_ee_widget($widget_path = null)
1077
+	{
1078
+		do_action('AHEE__EE_Config__register_widget__begin', $widget_path);
1079
+		$widget_ext = '.widget.php';
1080
+		// make all separators match
1081
+		$widget_path = rtrim(str_replace('/\\', DS, $widget_path), DS);
1082
+		// does the file path INCLUDE the actual file name as part of the path ?
1083
+		if (strpos($widget_path, $widget_ext) !== false) {
1084
+			// grab and shortcode file name from directory name and break apart at dots
1085
+			$file_name = explode('.', basename($widget_path));
1086
+			// take first segment from file name pieces and remove class prefix if it exists
1087
+			$widget = strpos($file_name[0], 'EEW_') === 0 ? substr($file_name[0], 4) : $file_name[0];
1088
+			// sanitize shortcode directory name
1089
+			$widget = sanitize_key($widget);
1090
+			// now we need to rebuild the shortcode path
1091
+			$widget_path = explode(DS, $widget_path);
1092
+			// remove last segment
1093
+			array_pop($widget_path);
1094
+			// glue it back together
1095
+			$widget_path = implode(DS, $widget_path);
1096
+		} else {
1097
+			// grab and sanitize widget directory name
1098
+			$widget = sanitize_key(basename($widget_path));
1099
+		}
1100
+		// create classname from widget directory name
1101
+		$widget = str_replace(' ', '_', ucwords(str_replace('_', ' ', $widget)));
1102
+		// add class prefix
1103
+		$widget_class = 'EEW_' . $widget;
1104
+		// does the widget exist ?
1105
+		if (! is_readable($widget_path . DS . $widget_class . $widget_ext)) {
1106
+			$msg = sprintf(
1107
+				__(
1108
+					'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',
1109
+					'event_espresso'
1110
+				),
1111
+				$widget_class,
1112
+				$widget_path . DS . $widget_class . $widget_ext
1113
+			);
1114
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1115
+			return;
1116
+		}
1117
+		// load the widget class file
1118
+		require_once($widget_path . DS . $widget_class . $widget_ext);
1119
+		// verify that class exists
1120
+		if (! class_exists($widget_class)) {
1121
+			$msg = sprintf(__('The requested %s widget class does not exist.', 'event_espresso'), $widget_class);
1122
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1123
+			return;
1124
+		}
1125
+		register_widget($widget_class);
1126
+		// add to array of registered widgets
1127
+		EE_Registry::instance()->widgets->{$widget_class} = $widget_path . DS . $widget_class . $widget_ext;
1128
+	}
1129
+
1130
+
1131
+
1132
+	/**
1133
+	 *        _register_modules
1134
+	 *
1135
+	 * @access private
1136
+	 * @return array
1137
+	 */
1138
+	private function _register_modules()
1139
+	{
1140
+		// grab list of installed modules
1141
+		$modules_to_register = glob(EE_MODULES . '*', GLOB_ONLYDIR);
1142
+		// filter list of modules to register
1143
+		$modules_to_register = apply_filters(
1144
+			'FHEE__EE_Config__register_modules__modules_to_register',
1145
+			$modules_to_register
1146
+		);
1147
+		if (! empty($modules_to_register)) {
1148
+			// loop through folders
1149
+			foreach ($modules_to_register as $module_path) {
1150
+				/**TEMPORARILY EXCLUDE gateways from modules for time being**/
1151
+				if (
1152
+					$module_path !== EE_MODULES . 'zzz-copy-this-module-template'
1153
+					&& $module_path !== EE_MODULES . 'gateways'
1154
+				) {
1155
+					// add to list of installed modules
1156
+					EE_Config::register_module($module_path);
1157
+				}
1158
+			}
1159
+		}
1160
+		// filter list of installed modules
1161
+		return apply_filters(
1162
+			'FHEE__EE_Config___register_modules__installed_modules',
1163
+			EE_Registry::instance()->modules
1164
+		);
1165
+	}
1166
+
1167
+
1168
+
1169
+	/**
1170
+	 *    register_module - makes core aware of this module
1171
+	 *
1172
+	 * @access    public
1173
+	 * @param    string $module_path - full path up to and including module folder
1174
+	 * @return    bool
1175
+	 */
1176
+	public static function register_module($module_path = null)
1177
+	{
1178
+		do_action('AHEE__EE_Config__register_module__begin', $module_path);
1179
+		$module_ext = '.module.php';
1180
+		// make all separators match
1181
+		$module_path = str_replace(array('\\', '/'), DS, $module_path);
1182
+		// does the file path INCLUDE the actual file name as part of the path ?
1183
+		if (strpos($module_path, $module_ext) !== false) {
1184
+			// grab and shortcode file name from directory name and break apart at dots
1185
+			$module_file = explode('.', basename($module_path));
1186
+			// now we need to rebuild the shortcode path
1187
+			$module_path = explode(DS, $module_path);
1188
+			// remove last segment
1189
+			array_pop($module_path);
1190
+			// glue it back together
1191
+			$module_path = implode(DS, $module_path) . DS;
1192
+			// take first segment from file name pieces and sanitize it
1193
+			$module = preg_replace('/[^a-zA-Z0-9_\-]/', '', $module_file[0]);
1194
+			// ensure class prefix is added
1195
+			$module_class = strpos($module, 'EED_') !== 0 ? 'EED_' . $module : $module;
1196
+		} else {
1197
+			// we need to generate the filename based off of the folder name
1198
+			// grab and sanitize module name
1199
+			$module = strtolower(basename($module_path));
1200
+			$module = preg_replace('/[^a-z0-9_\-]/', '', $module);
1201
+			// like trailingslashit()
1202
+			$module_path = rtrim($module_path, DS) . DS;
1203
+			// create classname from module directory name
1204
+			$module = str_replace(' ', '_', ucwords(str_replace('_', ' ', $module)));
1205
+			// add class prefix
1206
+			$module_class = 'EED_' . $module;
1207
+		}
1208
+		// does the module exist ?
1209
+		if (! is_readable($module_path . DS . $module_class . $module_ext)) {
1210
+			$msg = sprintf(
1211
+				__(
1212
+					'The requested %s module file could not be found or is not readable due to file permissions.',
1213
+					'event_espresso'
1214
+				),
1215
+				$module
1216
+			);
1217
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1218
+			return false;
1219
+		}
1220
+		// load the module class file
1221
+		require_once($module_path . $module_class . $module_ext);
1222
+		// verify that class exists
1223
+		if (! class_exists($module_class)) {
1224
+			$msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
1225
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1226
+			return false;
1227
+		}
1228
+		// add to array of registered modules
1229
+		EE_Registry::instance()->modules->{$module_class} = $module_path . $module_class . $module_ext;
1230
+		do_action(
1231
+			'AHEE__EE_Config__register_module__complete',
1232
+			$module_class,
1233
+			EE_Registry::instance()->modules->{$module_class}
1234
+		);
1235
+		return true;
1236
+	}
1237
+
1238
+
1239
+
1240
+	/**
1241
+	 *    _initialize_modules
1242
+	 *    allow modules to set hooks for the rest of the system
1243
+	 *
1244
+	 * @access private
1245
+	 * @return void
1246
+	 */
1247
+	private function _initialize_modules()
1248
+	{
1249
+		// cycle thru shortcode folders
1250
+		foreach (EE_Registry::instance()->modules as $module_class => $module_path) {
1251
+			// fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
1252
+			// which set hooks ?
1253
+			if (is_admin()) {
1254
+				// fire immediately
1255
+				call_user_func(array($module_class, 'set_hooks_admin'));
1256
+			} else {
1257
+				// delay until other systems are online
1258
+				add_action(
1259
+					'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
1260
+					array($module_class, 'set_hooks')
1261
+				);
1262
+			}
1263
+		}
1264
+	}
1265
+
1266
+
1267
+
1268
+	/**
1269
+	 *    register_route - adds module method routes to route_map
1270
+	 *
1271
+	 * @access    public
1272
+	 * @param    string $route       - "pretty" public alias for module method
1273
+	 * @param    string $module      - module name (classname without EED_ prefix)
1274
+	 * @param    string $method_name - the actual module method to be routed to
1275
+	 * @param    string $key         - url param key indicating a route is being called
1276
+	 * @return    bool
1277
+	 */
1278
+	public static function register_route($route = null, $module = null, $method_name = null, $key = 'ee')
1279
+	{
1280
+		do_action('AHEE__EE_Config__register_route__begin', $route, $module, $method_name);
1281
+		$module = str_replace('EED_', '', $module);
1282
+		$module_class = 'EED_' . $module;
1283
+		if (! isset(EE_Registry::instance()->modules->{$module_class})) {
1284
+			$msg = sprintf(__('The module %s has not been registered.', 'event_espresso'), $module);
1285
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1286
+			return false;
1287
+		}
1288
+		if (empty($route)) {
1289
+			$msg = sprintf(__('No route has been supplied.', 'event_espresso'), $route);
1290
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1291
+			return false;
1292
+		}
1293
+		if (! method_exists('EED_' . $module, $method_name)) {
1294
+			$msg = sprintf(
1295
+				__('A valid class method for the %s route has not been supplied.', 'event_espresso'),
1296
+				$route
1297
+			);
1298
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1299
+			return false;
1300
+		}
1301
+		EE_Config::$_module_route_map[$key][$route] = array('EED_' . $module, $method_name);
1302
+		return true;
1303
+	}
1304
+
1305
+
1306
+
1307
+	/**
1308
+	 *    get_route - get module method route
1309
+	 *
1310
+	 * @access    public
1311
+	 * @param    string $route - "pretty" public alias for module method
1312
+	 * @param    string $key   - url param key indicating a route is being called
1313
+	 * @return    string
1314
+	 */
1315
+	public static function get_route($route = null, $key = 'ee')
1316
+	{
1317
+		do_action('AHEE__EE_Config__get_route__begin', $route);
1318
+		$route = (string)apply_filters('FHEE__EE_Config__get_route', $route);
1319
+		if (isset(EE_Config::$_module_route_map[$key][$route])) {
1320
+			return EE_Config::$_module_route_map[$key][$route];
1321
+		}
1322
+		return null;
1323
+	}
1324
+
1325
+
1326
+
1327
+	/**
1328
+	 *    get_routes - get ALL module method routes
1329
+	 *
1330
+	 * @access    public
1331
+	 * @return    array
1332
+	 */
1333
+	public static function get_routes()
1334
+	{
1335
+		return EE_Config::$_module_route_map;
1336
+	}
1337
+
1338
+
1339
+
1340
+	/**
1341
+	 *    register_forward - allows modules to forward request to another module for further processing
1342
+	 *
1343
+	 * @access    public
1344
+	 * @param    string       $route   - "pretty" public alias for module method
1345
+	 * @param    integer      $status  - integer value corresponding  to status constant strings set in module parent
1346
+	 *                                 class, allows different forwards to be served based on status
1347
+	 * @param    array|string $forward - function name or array( class, method )
1348
+	 * @param    string       $key     - url param key indicating a route is being called
1349
+	 * @return    bool
1350
+	 */
1351
+	public static function register_forward($route = null, $status = 0, $forward = null, $key = 'ee')
1352
+	{
1353
+		do_action('AHEE__EE_Config__register_forward', $route, $status, $forward);
1354
+		if (! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1355
+			$msg = sprintf(
1356
+				__('The module route %s for this forward has not been registered.', 'event_espresso'),
1357
+				$route
1358
+			);
1359
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1360
+			return false;
1361
+		}
1362
+		if (empty($forward)) {
1363
+			$msg = sprintf(__('No forwarding route has been supplied.', 'event_espresso'), $route);
1364
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1365
+			return false;
1366
+		}
1367
+		if (is_array($forward)) {
1368
+			if (! isset($forward[1])) {
1369
+				$msg = sprintf(
1370
+					__('A class method for the %s forwarding route has not been supplied.', 'event_espresso'),
1371
+					$route
1372
+				);
1373
+				EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1374
+				return false;
1375
+			}
1376
+			if (! method_exists($forward[0], $forward[1])) {
1377
+				$msg = sprintf(
1378
+					__('The class method %s for the %s forwarding route is in invalid.', 'event_espresso'),
1379
+					$forward[1],
1380
+					$route
1381
+				);
1382
+				EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1383
+				return false;
1384
+			}
1385
+		} else if (! function_exists($forward)) {
1386
+			$msg = sprintf(
1387
+				__('The function %s for the %s forwarding route is in invalid.', 'event_espresso'),
1388
+				$forward,
1389
+				$route
1390
+			);
1391
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1392
+			return false;
1393
+		}
1394
+		EE_Config::$_module_forward_map[$key][$route][absint($status)] = $forward;
1395
+		return true;
1396
+	}
1397
+
1398
+
1399
+
1400
+	/**
1401
+	 *    get_forward - get forwarding route
1402
+	 *
1403
+	 * @access    public
1404
+	 * @param    string  $route  - "pretty" public alias for module method
1405
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1406
+	 *                           allows different forwards to be served based on status
1407
+	 * @param    string  $key    - url param key indicating a route is being called
1408
+	 * @return    string
1409
+	 */
1410
+	public static function get_forward($route = null, $status = 0, $key = 'ee')
1411
+	{
1412
+		do_action('AHEE__EE_Config__get_forward__begin', $route, $status);
1413
+		if (isset(EE_Config::$_module_forward_map[$key][$route][$status])) {
1414
+			return apply_filters(
1415
+				'FHEE__EE_Config__get_forward',
1416
+				EE_Config::$_module_forward_map[$key][$route][$status],
1417
+				$route,
1418
+				$status
1419
+			);
1420
+		}
1421
+		return null;
1422
+	}
1423
+
1424
+
1425
+
1426
+	/**
1427
+	 *    register_forward - allows modules to specify different view templates for different method routes and status
1428
+	 *    results
1429
+	 *
1430
+	 * @access    public
1431
+	 * @param    string  $route  - "pretty" public alias for module method
1432
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1433
+	 *                           allows different views to be served based on status
1434
+	 * @param    string  $view
1435
+	 * @param    string  $key    - url param key indicating a route is being called
1436
+	 * @return    bool
1437
+	 */
1438
+	public static function register_view($route = null, $status = 0, $view = null, $key = 'ee')
1439
+	{
1440
+		do_action('AHEE__EE_Config__register_view__begin', $route, $status, $view);
1441
+		if (! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1442
+			$msg = sprintf(
1443
+				__('The module route %s for this view has not been registered.', 'event_espresso'),
1444
+				$route
1445
+			);
1446
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1447
+			return false;
1448
+		}
1449
+		if (! is_readable($view)) {
1450
+			$msg = sprintf(
1451
+				__(
1452
+					'The %s view file could not be found or is not readable due to file permissions.',
1453
+					'event_espresso'
1454
+				),
1455
+				$view
1456
+			);
1457
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1458
+			return false;
1459
+		}
1460
+		EE_Config::$_module_view_map[$key][$route][absint($status)] = $view;
1461
+		return true;
1462
+	}
1463
+
1464
+
1465
+
1466
+	/**
1467
+	 *    get_view - get view for route and status
1468
+	 *
1469
+	 * @access    public
1470
+	 * @param    string  $route  - "pretty" public alias for module method
1471
+	 * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1472
+	 *                           allows different views to be served based on status
1473
+	 * @param    string  $key    - url param key indicating a route is being called
1474
+	 * @return    string
1475
+	 */
1476
+	public static function get_view($route = null, $status = 0, $key = 'ee')
1477
+	{
1478
+		do_action('AHEE__EE_Config__get_view__begin', $route, $status);
1479
+		if (isset(EE_Config::$_module_view_map[$key][$route][$status])) {
1480
+			return apply_filters(
1481
+				'FHEE__EE_Config__get_view',
1482
+				EE_Config::$_module_view_map[$key][$route][$status],
1483
+				$route,
1484
+				$status
1485
+			);
1486
+		}
1487
+		return null;
1488
+	}
1489
+
1490
+
1491
+
1492
+	public function update_addon_option_names()
1493
+	{
1494
+		update_option(EE_Config::ADDON_OPTION_NAMES, $this->_addon_option_names);
1495
+	}
1496
+
1497
+
1498
+
1499
+	public function shutdown()
1500
+	{
1501
+		$this->update_addon_option_names();
1502
+	}
1503
+
1504
+
1505
+
1506
+	/**
1507
+	 * @return LegacyShortcodesManager
1508
+	 */
1509
+	public static function getLegacyShortcodesManager()
1510
+	{
1511
+
1512
+		if ( ! EE_Config::instance()->legacy_shortcodes_manager instanceof LegacyShortcodesManager) {
1513
+			EE_Config::instance()->legacy_shortcodes_manager = new LegacyShortcodesManager(
1514
+				EE_Registry::instance()
1515
+			);
1516
+		}
1517
+		return EE_Config::instance()->legacy_shortcodes_manager;
1518
+	}
1519
+
1520
+
1521
+
1522
+	/**
1523
+	 * register_shortcode - makes core aware of this shortcode
1524
+	 *
1525
+	 * @deprecated 4.9.26
1526
+	 * @param    string $shortcode_path - full path up to and including shortcode folder
1527
+	 * @return    bool
1528
+	 */
1529
+	public static function register_shortcode($shortcode_path = null)
1530
+	{
1531
+		EE_Error::doing_it_wrong(
1532
+			__METHOD__,
1533
+			__(
1534
+				'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.',
1535
+				'event_espresso'
1536
+			),
1537
+			'4.9.26'
1538
+		);
1539
+		return EE_Config::instance()->getLegacyShortcodesManager()->registerShortcode($shortcode_path);
1540
+	}
21 1541
 
22
-    const LOG_NAME           = 'ee_config_log';
23 1542
 
24
-    const LOG_LENGTH         = 100;
25 1543
 
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
-            if ($addon_config_obj instanceof EE_Config_Base) {
449
-                $this->update_config('addons', $addon_name, $addon_config_obj, false);
450
-            }
451
-            $this->addons->{$addon_name} = null;
452
-        }
453
-    }
454
-
455
-
456
-
457
-    /**
458
-     *    update_espresso_config
459
-     *
460
-     * @access   public
461
-     * @param   bool $add_success
462
-     * @param   bool $add_error
463
-     * @return   bool
464
-     */
465
-    public function update_espresso_config($add_success = false, $add_error = true)
466
-    {
467
-        // don't allow config updates during WP heartbeats
468
-        if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
469
-            return false;
470
-        }
471
-        // commented out the following re: https://events.codebasehq.com/projects/event-espresso/tickets/8197
472
-        //$clone = clone( self::$_instance );
473
-        //self::$_instance = NULL;
474
-        do_action('AHEE__EE_Config__update_espresso_config__begin', $this);
475
-        $this->_reset_espresso_addon_config();
476
-        // hook into update_option because that happens AFTER the ( $value === $old_value ) conditional
477
-        // but BEFORE the actual update occurs
478
-        add_action('update_option', array($this, 'double_check_config_comparison'), 1, 3);
479
-        // don't want to persist legacy_shortcodes_manager, but don't want to lose it either
480
-        $legacy_shortcodes_manager = $this->legacy_shortcodes_manager;
481
-        $this->legacy_shortcodes_manager = null;
482
-        // now update "ee_config"
483
-        $saved = update_option(EE_Config::OPTION_NAME, $this);
484
-        $this->legacy_shortcodes_manager = $legacy_shortcodes_manager;
485
-        EE_Config::log(EE_Config::OPTION_NAME);
486
-        // if not saved... check if the hook we just added still exists;
487
-        // if it does, it means one of two things:
488
-        // 		that update_option bailed at the ( $value === $old_value ) conditional,
489
-        //		 or...
490
-        // 		the db update query returned 0 rows affected
491
-        // 		(probably because the data  value was the same from it's perspective)
492
-        // so the existence of the hook means that a negative result from update_option is NOT an error,
493
-        // but just means no update occurred, so don't display an error to the user.
494
-        // BUT... if update_option returns FALSE, AND the hook is missing,
495
-        // then it means that something truly went wrong
496
-        $saved = ! $saved ? has_action('update_option', array($this, 'double_check_config_comparison')) : $saved;
497
-        // remove our action since we don't want it in the system anymore
498
-        remove_action('update_option', array($this, 'double_check_config_comparison'), 1);
499
-        do_action('AHEE__EE_Config__update_espresso_config__end', $this, $saved);
500
-        //self::$_instance = $clone;
501
-        //unset( $clone );
502
-        // if config remains the same or was updated successfully
503
-        if ($saved) {
504
-            if ($add_success) {
505
-                EE_Error::add_success(
506
-                    __('The Event Espresso Configuration Settings have been successfully updated.', 'event_espresso'),
507
-                    __FILE__,
508
-                    __FUNCTION__,
509
-                    __LINE__
510
-                );
511
-            }
512
-            return true;
513
-        } else {
514
-            if ($add_error) {
515
-                EE_Error::add_error(
516
-                    __('The Event Espresso Configuration Settings were not updated.', 'event_espresso'),
517
-                    __FILE__,
518
-                    __FUNCTION__,
519
-                    __LINE__
520
-                );
521
-            }
522
-            return false;
523
-        }
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     *    _verify_config_params
530
-     *
531
-     * @access    private
532
-     * @param    string         $section
533
-     * @param    string         $name
534
-     * @param    string         $config_class
535
-     * @param    EE_Config_Base $config_obj
536
-     * @param    array          $tests_to_run
537
-     * @param    bool           $display_errors
538
-     * @return    bool    TRUE on success, FALSE on fail
539
-     */
540
-    private function _verify_config_params(
541
-        $section = '',
542
-        $name = '',
543
-        $config_class = '',
544
-        $config_obj = null,
545
-        $tests_to_run = array(1, 2, 3, 4, 5, 6, 7, 8),
546
-        $display_errors = true
547
-    ) {
548
-        try {
549
-            foreach ($tests_to_run as $test) {
550
-                switch ($test) {
551
-                    // TEST #1 : check that section was set
552
-                    case 1 :
553
-                        if (empty($section)) {
554
-                            if ($display_errors) {
555
-                                throw new EE_Error(
556
-                                    sprintf(
557
-                                        __(
558
-                                            'No configuration section has been provided while attempting to save "%s".',
559
-                                            'event_espresso'
560
-                                        ),
561
-                                        $config_class
562
-                                    )
563
-                                );
564
-                            }
565
-                            return false;
566
-                        }
567
-                        break;
568
-                    // TEST #2 : check that settings section exists
569
-                    case 2 :
570
-                        if (! isset($this->{$section})) {
571
-                            if ($display_errors) {
572
-                                throw new EE_Error(
573
-                                    sprintf(
574
-                                        __('The "%s" configuration section does not exist.', 'event_espresso'),
575
-                                        $section
576
-                                    )
577
-                                );
578
-                            }
579
-                            return false;
580
-                        }
581
-                        break;
582
-                    // TEST #3 : check that section is the proper format
583
-                    case 3 :
584
-                        if (
585
-                        ! ($this->{$section} instanceof EE_Config_Base || $this->{$section} instanceof stdClass)
586
-                        ) {
587
-                            if ($display_errors) {
588
-                                throw new EE_Error(
589
-                                    sprintf(
590
-                                        __(
591
-                                            'The "%s" configuration settings have not been formatted correctly.',
592
-                                            'event_espresso'
593
-                                        ),
594
-                                        $section
595
-                                    )
596
-                                );
597
-                            }
598
-                            return false;
599
-                        }
600
-                        break;
601
-                    // TEST #4 : check that config section name has been set
602
-                    case 4 :
603
-                        if (empty($name)) {
604
-                            if ($display_errors) {
605
-                                throw new EE_Error(
606
-                                    __(
607
-                                        'No name has been provided for the specific configuration section.',
608
-                                        'event_espresso'
609
-                                    )
610
-                                );
611
-                            }
612
-                            return false;
613
-                        }
614
-                        break;
615
-                    // TEST #5 : check that a config class name has been set
616
-                    case 5 :
617
-                        if (empty($config_class)) {
618
-                            if ($display_errors) {
619
-                                throw new EE_Error(
620
-                                    __(
621
-                                        'No class name has been provided for the specific configuration section.',
622
-                                        'event_espresso'
623
-                                    )
624
-                                );
625
-                            }
626
-                            return false;
627
-                        }
628
-                        break;
629
-                    // TEST #6 : verify config class is accessible
630
-                    case 6 :
631
-                        if (! class_exists($config_class)) {
632
-                            if ($display_errors) {
633
-                                throw new EE_Error(
634
-                                    sprintf(
635
-                                        __(
636
-                                            'The "%s" class does not exist. Please ensure that an autoloader has been set for it.',
637
-                                            'event_espresso'
638
-                                        ),
639
-                                        $config_class
640
-                                    )
641
-                                );
642
-                            }
643
-                            return false;
644
-                        }
645
-                        break;
646
-                    // TEST #7 : check that config has even been set
647
-                    case 7 :
648
-                        if (! isset($this->{$section}->{$name})) {
649
-                            if ($display_errors) {
650
-                                throw new EE_Error(
651
-                                    sprintf(
652
-                                        __('No configuration has been set for "%1$s->%2$s".', 'event_espresso'),
653
-                                        $section,
654
-                                        $name
655
-                                    )
656
-                                );
657
-                            }
658
-                            return false;
659
-                        } else {
660
-                            // and make sure it's not serialized
661
-                            $this->{$section}->{$name} = maybe_unserialize($this->{$section}->{$name});
662
-                        }
663
-                        break;
664
-                    // TEST #8 : check that config is the requested type
665
-                    case 8 :
666
-                        if (! $this->{$section}->{$name} instanceof $config_class) {
667
-                            if ($display_errors) {
668
-                                throw new EE_Error(
669
-                                    sprintf(
670
-                                        __(
671
-                                            'The configuration for "%1$s->%2$s" is not of the "%3$s" class.',
672
-                                            'event_espresso'
673
-                                        ),
674
-                                        $section,
675
-                                        $name,
676
-                                        $config_class
677
-                                    )
678
-                                );
679
-                            }
680
-                            return false;
681
-                        }
682
-                        break;
683
-                    // TEST #9 : verify config object
684
-                    case 9 :
685
-                        if (! $config_obj instanceof EE_Config_Base) {
686
-                            if ($display_errors) {
687
-                                throw new EE_Error(
688
-                                    sprintf(
689
-                                        __('The "%s" class is not an instance of EE_Config_Base.', 'event_espresso'),
690
-                                        print_r($config_obj, true)
691
-                                    )
692
-                                );
693
-                            }
694
-                            return false;
695
-                        }
696
-                        break;
697
-                }
698
-            }
699
-        } catch (EE_Error $e) {
700
-            $e->get_error();
701
-        }
702
-        // you have successfully run the gauntlet
703
-        return true;
704
-    }
705
-
706
-
707
-
708
-    /**
709
-     *    _generate_config_option_name
710
-     *
711
-     * @access        protected
712
-     * @param        string $section
713
-     * @param        string $name
714
-     * @return        string
715
-     */
716
-    private function _generate_config_option_name($section = '', $name = '')
717
-    {
718
-        return 'ee_config-' . strtolower($section . '-' . str_replace(array('EE_', 'EED_'), '', $name));
719
-    }
720
-
721
-
722
-
723
-    /**
724
-     *    _set_config_class
725
-     * ensures that a config class is set, either from a passed config class or one generated from the config name
726
-     *
727
-     * @access    private
728
-     * @param    string $config_class
729
-     * @param    string $name
730
-     * @return    string
731
-     */
732
-    private function _set_config_class($config_class = '', $name = '')
733
-    {
734
-        return ! empty($config_class)
735
-            ? $config_class
736
-            : str_replace(' ', '_', ucwords(str_replace('_', ' ', $name))) . '_Config';
737
-    }
738
-
739
-
740
-
741
-    /**
742
-     *    set_config
743
-     *
744
-     * @access    protected
745
-     * @param    string         $section
746
-     * @param    string         $name
747
-     * @param    string         $config_class
748
-     * @param    EE_Config_Base $config_obj
749
-     * @return    EE_Config_Base
750
-     */
751
-    public function set_config($section = '', $name = '', $config_class = '', EE_Config_Base $config_obj = null)
752
-    {
753
-        // ensure config class is set to something
754
-        $config_class = $this->_set_config_class($config_class, $name);
755
-        // run tests 1-4, 6, and 7 to verify all config params are set and valid
756
-        if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
757
-            return null;
758
-        }
759
-        $config_option_name = $this->_generate_config_option_name($section, $name);
760
-        // if the config option name hasn't been added yet to the list of option names we're tracking, then do so now
761
-        if (! isset($this->_addon_option_names[$config_option_name])) {
762
-            $this->_addon_option_names[$config_option_name] = $config_class;
763
-            $this->update_addon_option_names();
764
-        }
765
-        // verify the incoming config object but suppress errors
766
-        if (! $this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
767
-            $config_obj = new $config_class();
768
-        }
769
-        if (get_option($config_option_name)) {
770
-            EE_Config::log($config_option_name);
771
-            update_option($config_option_name, $config_obj);
772
-            $this->{$section}->{$name} = $config_obj;
773
-            return $this->{$section}->{$name};
774
-        } else {
775
-            // create a wp-option for this config
776
-            if (add_option($config_option_name, $config_obj, '', 'no')) {
777
-                $this->{$section}->{$name} = maybe_unserialize($config_obj);
778
-                return $this->{$section}->{$name};
779
-            } else {
780
-                EE_Error::add_error(
781
-                    sprintf(__('The "%s" could not be saved to the database.', 'event_espresso'), $config_class),
782
-                    __FILE__,
783
-                    __FUNCTION__,
784
-                    __LINE__
785
-                );
786
-                return null;
787
-            }
788
-        }
789
-    }
790
-
791
-
792
-
793
-    /**
794
-     *    update_config
795
-     * Important: the config object must ALREADY be set, otherwise this will produce an error.
796
-     *
797
-     * @access    public
798
-     * @param    string                $section
799
-     * @param    string                $name
800
-     * @param    EE_Config_Base|string $config_obj
801
-     * @param    bool                  $throw_errors
802
-     * @return    bool
803
-     */
804
-    public function update_config($section = '', $name = '', $config_obj = '', $throw_errors = true)
805
-    {
806
-        // don't allow config updates during WP heartbeats
807
-        if (\EE_Registry::instance()->REQ->get('action', '') === 'heartbeat') {
808
-            return false;
809
-        }
810
-        $config_obj = maybe_unserialize($config_obj);
811
-        // get class name of the incoming object
812
-        $config_class = get_class($config_obj);
813
-        // run tests 1-5 and 9 to verify config
814
-        if (! $this->_verify_config_params(
815
-            $section,
816
-            $name,
817
-            $config_class,
818
-            $config_obj,
819
-            array(1, 2, 3, 4, 7, 9)
820
-        )
821
-        ) {
822
-            return false;
823
-        }
824
-        $config_option_name = $this->_generate_config_option_name($section, $name);
825
-        // check if config object has been added to db by seeing if config option name is in $this->_addon_option_names array
826
-        if (! isset($this->_addon_option_names[$config_option_name])) {
827
-            // save new config to db
828
-            if ($this->set_config($section, $name, $config_class, $config_obj)) {
829
-                return true;
830
-            }
831
-        } else {
832
-            // first check if the record already exists
833
-            $existing_config = get_option($config_option_name);
834
-            $config_obj = serialize($config_obj);
835
-            // just return if db record is already up to date (NOT type safe comparison)
836
-            if ($existing_config == $config_obj) {
837
-                $this->{$section}->{$name} = $config_obj;
838
-                return true;
839
-            } else if (update_option($config_option_name, $config_obj)) {
840
-                EE_Config::log($config_option_name);
841
-                // update wp-option for this config class
842
-                $this->{$section}->{$name} = $config_obj;
843
-                return true;
844
-            } elseif ($throw_errors) {
845
-                EE_Error::add_error(
846
-                    sprintf(
847
-                        __(
848
-                            'The "%1$s" object stored at"%2$s" was not successfully updated in the database.',
849
-                            'event_espresso'
850
-                        ),
851
-                        $config_class,
852
-                        'EE_Config->' . $section . '->' . $name
853
-                    ),
854
-                    __FILE__,
855
-                    __FUNCTION__,
856
-                    __LINE__
857
-                );
858
-            }
859
-        }
860
-        return false;
861
-    }
862
-
863
-
864
-
865
-    /**
866
-     *    get_config
867
-     *
868
-     * @access    public
869
-     * @param    string $section
870
-     * @param    string $name
871
-     * @param    string $config_class
872
-     * @return    mixed EE_Config_Base | NULL
873
-     */
874
-    public function get_config($section = '', $name = '', $config_class = '')
875
-    {
876
-        // ensure config class is set to something
877
-        $config_class = $this->_set_config_class($config_class, $name);
878
-        // run tests 1-4, 6 and 7 to verify that all params have been set
879
-        if (! $this->_verify_config_params($section, $name, $config_class, null, array(1, 2, 3, 4, 5, 6))) {
880
-            return null;
881
-        }
882
-        // now test if the requested config object exists, but suppress errors
883
-        if ($this->_verify_config_params($section, $name, $config_class, null, array(7, 8), false)) {
884
-            // config already exists, so pass it back
885
-            return $this->{$section}->{$name};
886
-        }
887
-        // load config option from db if it exists
888
-        $config_obj = $this->get_config_option($this->_generate_config_option_name($section, $name));
889
-        // verify the newly retrieved config object, but suppress errors
890
-        if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9), false)) {
891
-            // config is good, so set it and pass it back
892
-            $this->{$section}->{$name} = $config_obj;
893
-            return $this->{$section}->{$name};
894
-        }
895
-        // oops! $config_obj is not already set and does not exist in the db, so create a new one
896
-        $config_obj = $this->set_config($section, $name, $config_class);
897
-        // verify the newly created config object
898
-        if ($this->_verify_config_params($section, $name, $config_class, $config_obj, array(9))) {
899
-            return $this->{$section}->{$name};
900
-        } else {
901
-            EE_Error::add_error(
902
-                sprintf(__('The "%s" could not be retrieved from the database.', 'event_espresso'), $config_class),
903
-                __FILE__,
904
-                __FUNCTION__,
905
-                __LINE__
906
-            );
907
-        }
908
-        return null;
909
-    }
910
-
911
-
912
-
913
-    /**
914
-     *    get_config_option
915
-     *
916
-     * @access    public
917
-     * @param    string $config_option_name
918
-     * @return    mixed EE_Config_Base | FALSE
919
-     */
920
-    public function get_config_option($config_option_name = '')
921
-    {
922
-        // retrieve the wp-option for this config class.
923
-        $config_option = maybe_unserialize(get_option($config_option_name, array()));
924
-        if (empty($config_option)) {
925
-            EE_Config::log($config_option_name . '-NOT-FOUND');
926
-        }
927
-        return $config_option;
928
-    }
929
-
930
-
931
-
932
-    /**
933
-     * log
934
-     *
935
-     * @param string $config_option_name
936
-     */
937
-    public static function log($config_option_name = '')
938
-    {
939
-        if (EE_Config::logging_enabled() && ! empty($config_option_name)) {
940
-            $config_log = get_option(EE_Config::LOG_NAME, array());
941
-            //copy incoming $_REQUEST and sanitize it so we can save it
942
-            $_request = $_REQUEST;
943
-            array_walk_recursive($_request, 'sanitize_text_field');
944
-            $config_log[(string)microtime(true)] = array(
945
-                'config_name' => $config_option_name,
946
-                'request'     => $_request,
947
-            );
948
-            update_option(EE_Config::LOG_NAME, $config_log);
949
-        }
950
-    }
951
-
952
-
953
-
954
-    /**
955
-     * trim_log
956
-     * reduces the size of the config log to the length specified by EE_Config::LOG_LENGTH
957
-     */
958
-    public static function trim_log()
959
-    {
960
-        if (! EE_Config::logging_enabled()) {
961
-            return;
962
-        }
963
-        $config_log = maybe_unserialize(get_option(EE_Config::LOG_NAME, array()));
964
-        $log_length = count($config_log);
965
-        if ($log_length > EE_Config::LOG_LENGTH) {
966
-            ksort($config_log);
967
-            $config_log = array_slice($config_log, $log_length - EE_Config::LOG_LENGTH, null, true);
968
-            update_option(EE_Config::LOG_NAME, $config_log);
969
-        }
970
-    }
971
-
972
-
973
-
974
-    /**
975
-     *    get_page_for_posts
976
-     *    if the wp-option "show_on_front" is set to "page", then this is the post_name for the post set in the
977
-     *    wp-option "page_for_posts", or "posts" if no page is selected
978
-     *
979
-     * @access    public
980
-     * @return    string
981
-     */
982
-    public static function get_page_for_posts()
983
-    {
984
-        $page_for_posts = get_option('page_for_posts');
985
-        if (! $page_for_posts) {
986
-            return 'posts';
987
-        }
988
-        /** @type WPDB $wpdb */
989
-        global $wpdb;
990
-        $SQL = "SELECT post_name from $wpdb->posts WHERE post_type='posts' OR post_type='page' AND post_status='publish' AND ID=%d";
991
-        return $wpdb->get_var($wpdb->prepare($SQL, $page_for_posts));
992
-    }
993
-
994
-
995
-
996
-    /**
997
-     *    register_shortcodes_and_modules.
998
-     *    At this point, it's too early to tell if we're maintenance mode or not.
999
-     *    In fact, this is where we give modules a chance to let core know they exist
1000
-     *    so they can help trigger maintenance mode if it's needed
1001
-     *
1002
-     * @access    public
1003
-     * @return    void
1004
-     */
1005
-    public function register_shortcodes_and_modules()
1006
-    {
1007
-        // allow modules to set hooks for the rest of the system
1008
-        EE_Registry::instance()->modules = $this->_register_modules();
1009
-    }
1010
-
1011
-
1012
-
1013
-    /**
1014
-     *    initialize_shortcodes_and_modules
1015
-     *    meaning they can start adding their hooks to get stuff done
1016
-     *
1017
-     * @access    public
1018
-     * @return    void
1019
-     */
1020
-    public function initialize_shortcodes_and_modules()
1021
-    {
1022
-        // allow modules to set hooks for the rest of the system
1023
-        $this->_initialize_modules();
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     *    widgets_init
1030
-     *
1031
-     * @access private
1032
-     * @return void
1033
-     */
1034
-    public function widgets_init()
1035
-    {
1036
-        //only init widgets on admin pages when not in complete maintenance, and
1037
-        //on frontend when not in any maintenance mode
1038
-        if (
1039
-            ! EE_Maintenance_Mode::instance()->level()
1040
-            || (
1041
-                is_admin()
1042
-                && EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
1043
-            )
1044
-        ) {
1045
-            // grab list of installed widgets
1046
-            $widgets_to_register = glob(EE_WIDGETS . '*', GLOB_ONLYDIR);
1047
-            // filter list of modules to register
1048
-            $widgets_to_register = apply_filters(
1049
-                'FHEE__EE_Config__register_widgets__widgets_to_register',
1050
-                $widgets_to_register
1051
-            );
1052
-            if (! empty($widgets_to_register)) {
1053
-                // cycle thru widget folders
1054
-                foreach ($widgets_to_register as $widget_path) {
1055
-                    // add to list of installed widget modules
1056
-                    EE_Config::register_ee_widget($widget_path);
1057
-                }
1058
-            }
1059
-            // filter list of installed modules
1060
-            EE_Registry::instance()->widgets = apply_filters(
1061
-                'FHEE__EE_Config__register_widgets__installed_widgets',
1062
-                EE_Registry::instance()->widgets
1063
-            );
1064
-        }
1065
-    }
1066
-
1067
-
1068
-
1069
-    /**
1070
-     *    register_ee_widget - makes core aware of this widget
1071
-     *
1072
-     * @access    public
1073
-     * @param    string $widget_path - full path up to and including widget folder
1074
-     * @return    void
1075
-     */
1076
-    public static function register_ee_widget($widget_path = null)
1077
-    {
1078
-        do_action('AHEE__EE_Config__register_widget__begin', $widget_path);
1079
-        $widget_ext = '.widget.php';
1080
-        // make all separators match
1081
-        $widget_path = rtrim(str_replace('/\\', DS, $widget_path), DS);
1082
-        // does the file path INCLUDE the actual file name as part of the path ?
1083
-        if (strpos($widget_path, $widget_ext) !== false) {
1084
-            // grab and shortcode file name from directory name and break apart at dots
1085
-            $file_name = explode('.', basename($widget_path));
1086
-            // take first segment from file name pieces and remove class prefix if it exists
1087
-            $widget = strpos($file_name[0], 'EEW_') === 0 ? substr($file_name[0], 4) : $file_name[0];
1088
-            // sanitize shortcode directory name
1089
-            $widget = sanitize_key($widget);
1090
-            // now we need to rebuild the shortcode path
1091
-            $widget_path = explode(DS, $widget_path);
1092
-            // remove last segment
1093
-            array_pop($widget_path);
1094
-            // glue it back together
1095
-            $widget_path = implode(DS, $widget_path);
1096
-        } else {
1097
-            // grab and sanitize widget directory name
1098
-            $widget = sanitize_key(basename($widget_path));
1099
-        }
1100
-        // create classname from widget directory name
1101
-        $widget = str_replace(' ', '_', ucwords(str_replace('_', ' ', $widget)));
1102
-        // add class prefix
1103
-        $widget_class = 'EEW_' . $widget;
1104
-        // does the widget exist ?
1105
-        if (! is_readable($widget_path . DS . $widget_class . $widget_ext)) {
1106
-            $msg = sprintf(
1107
-                __(
1108
-                    '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',
1109
-                    'event_espresso'
1110
-                ),
1111
-                $widget_class,
1112
-                $widget_path . DS . $widget_class . $widget_ext
1113
-            );
1114
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1115
-            return;
1116
-        }
1117
-        // load the widget class file
1118
-        require_once($widget_path . DS . $widget_class . $widget_ext);
1119
-        // verify that class exists
1120
-        if (! class_exists($widget_class)) {
1121
-            $msg = sprintf(__('The requested %s widget class does not exist.', 'event_espresso'), $widget_class);
1122
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1123
-            return;
1124
-        }
1125
-        register_widget($widget_class);
1126
-        // add to array of registered widgets
1127
-        EE_Registry::instance()->widgets->{$widget_class} = $widget_path . DS . $widget_class . $widget_ext;
1128
-    }
1129
-
1130
-
1131
-
1132
-    /**
1133
-     *        _register_modules
1134
-     *
1135
-     * @access private
1136
-     * @return array
1137
-     */
1138
-    private function _register_modules()
1139
-    {
1140
-        // grab list of installed modules
1141
-        $modules_to_register = glob(EE_MODULES . '*', GLOB_ONLYDIR);
1142
-        // filter list of modules to register
1143
-        $modules_to_register = apply_filters(
1144
-            'FHEE__EE_Config__register_modules__modules_to_register',
1145
-            $modules_to_register
1146
-        );
1147
-        if (! empty($modules_to_register)) {
1148
-            // loop through folders
1149
-            foreach ($modules_to_register as $module_path) {
1150
-                /**TEMPORARILY EXCLUDE gateways from modules for time being**/
1151
-                if (
1152
-                    $module_path !== EE_MODULES . 'zzz-copy-this-module-template'
1153
-                    && $module_path !== EE_MODULES . 'gateways'
1154
-                ) {
1155
-                    // add to list of installed modules
1156
-                    EE_Config::register_module($module_path);
1157
-                }
1158
-            }
1159
-        }
1160
-        // filter list of installed modules
1161
-        return apply_filters(
1162
-            'FHEE__EE_Config___register_modules__installed_modules',
1163
-            EE_Registry::instance()->modules
1164
-        );
1165
-    }
1166
-
1167
-
1168
-
1169
-    /**
1170
-     *    register_module - makes core aware of this module
1171
-     *
1172
-     * @access    public
1173
-     * @param    string $module_path - full path up to and including module folder
1174
-     * @return    bool
1175
-     */
1176
-    public static function register_module($module_path = null)
1177
-    {
1178
-        do_action('AHEE__EE_Config__register_module__begin', $module_path);
1179
-        $module_ext = '.module.php';
1180
-        // make all separators match
1181
-        $module_path = str_replace(array('\\', '/'), DS, $module_path);
1182
-        // does the file path INCLUDE the actual file name as part of the path ?
1183
-        if (strpos($module_path, $module_ext) !== false) {
1184
-            // grab and shortcode file name from directory name and break apart at dots
1185
-            $module_file = explode('.', basename($module_path));
1186
-            // now we need to rebuild the shortcode path
1187
-            $module_path = explode(DS, $module_path);
1188
-            // remove last segment
1189
-            array_pop($module_path);
1190
-            // glue it back together
1191
-            $module_path = implode(DS, $module_path) . DS;
1192
-            // take first segment from file name pieces and sanitize it
1193
-            $module = preg_replace('/[^a-zA-Z0-9_\-]/', '', $module_file[0]);
1194
-            // ensure class prefix is added
1195
-            $module_class = strpos($module, 'EED_') !== 0 ? 'EED_' . $module : $module;
1196
-        } else {
1197
-            // we need to generate the filename based off of the folder name
1198
-            // grab and sanitize module name
1199
-            $module = strtolower(basename($module_path));
1200
-            $module = preg_replace('/[^a-z0-9_\-]/', '', $module);
1201
-            // like trailingslashit()
1202
-            $module_path = rtrim($module_path, DS) . DS;
1203
-            // create classname from module directory name
1204
-            $module = str_replace(' ', '_', ucwords(str_replace('_', ' ', $module)));
1205
-            // add class prefix
1206
-            $module_class = 'EED_' . $module;
1207
-        }
1208
-        // does the module exist ?
1209
-        if (! is_readable($module_path . DS . $module_class . $module_ext)) {
1210
-            $msg = sprintf(
1211
-                __(
1212
-                    'The requested %s module file could not be found or is not readable due to file permissions.',
1213
-                    'event_espresso'
1214
-                ),
1215
-                $module
1216
-            );
1217
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1218
-            return false;
1219
-        }
1220
-        // load the module class file
1221
-        require_once($module_path . $module_class . $module_ext);
1222
-        // verify that class exists
1223
-        if (! class_exists($module_class)) {
1224
-            $msg = sprintf(__('The requested %s module class does not exist.', 'event_espresso'), $module_class);
1225
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1226
-            return false;
1227
-        }
1228
-        // add to array of registered modules
1229
-        EE_Registry::instance()->modules->{$module_class} = $module_path . $module_class . $module_ext;
1230
-        do_action(
1231
-            'AHEE__EE_Config__register_module__complete',
1232
-            $module_class,
1233
-            EE_Registry::instance()->modules->{$module_class}
1234
-        );
1235
-        return true;
1236
-    }
1237
-
1238
-
1239
-
1240
-    /**
1241
-     *    _initialize_modules
1242
-     *    allow modules to set hooks for the rest of the system
1243
-     *
1244
-     * @access private
1245
-     * @return void
1246
-     */
1247
-    private function _initialize_modules()
1248
-    {
1249
-        // cycle thru shortcode folders
1250
-        foreach (EE_Registry::instance()->modules as $module_class => $module_path) {
1251
-            // fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
1252
-            // which set hooks ?
1253
-            if (is_admin()) {
1254
-                // fire immediately
1255
-                call_user_func(array($module_class, 'set_hooks_admin'));
1256
-            } else {
1257
-                // delay until other systems are online
1258
-                add_action(
1259
-                    'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
1260
-                    array($module_class, 'set_hooks')
1261
-                );
1262
-            }
1263
-        }
1264
-    }
1265
-
1266
-
1267
-
1268
-    /**
1269
-     *    register_route - adds module method routes to route_map
1270
-     *
1271
-     * @access    public
1272
-     * @param    string $route       - "pretty" public alias for module method
1273
-     * @param    string $module      - module name (classname without EED_ prefix)
1274
-     * @param    string $method_name - the actual module method to be routed to
1275
-     * @param    string $key         - url param key indicating a route is being called
1276
-     * @return    bool
1277
-     */
1278
-    public static function register_route($route = null, $module = null, $method_name = null, $key = 'ee')
1279
-    {
1280
-        do_action('AHEE__EE_Config__register_route__begin', $route, $module, $method_name);
1281
-        $module = str_replace('EED_', '', $module);
1282
-        $module_class = 'EED_' . $module;
1283
-        if (! isset(EE_Registry::instance()->modules->{$module_class})) {
1284
-            $msg = sprintf(__('The module %s has not been registered.', 'event_espresso'), $module);
1285
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1286
-            return false;
1287
-        }
1288
-        if (empty($route)) {
1289
-            $msg = sprintf(__('No route has been supplied.', 'event_espresso'), $route);
1290
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1291
-            return false;
1292
-        }
1293
-        if (! method_exists('EED_' . $module, $method_name)) {
1294
-            $msg = sprintf(
1295
-                __('A valid class method for the %s route has not been supplied.', 'event_espresso'),
1296
-                $route
1297
-            );
1298
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1299
-            return false;
1300
-        }
1301
-        EE_Config::$_module_route_map[$key][$route] = array('EED_' . $module, $method_name);
1302
-        return true;
1303
-    }
1304
-
1305
-
1306
-
1307
-    /**
1308
-     *    get_route - get module method route
1309
-     *
1310
-     * @access    public
1311
-     * @param    string $route - "pretty" public alias for module method
1312
-     * @param    string $key   - url param key indicating a route is being called
1313
-     * @return    string
1314
-     */
1315
-    public static function get_route($route = null, $key = 'ee')
1316
-    {
1317
-        do_action('AHEE__EE_Config__get_route__begin', $route);
1318
-        $route = (string)apply_filters('FHEE__EE_Config__get_route', $route);
1319
-        if (isset(EE_Config::$_module_route_map[$key][$route])) {
1320
-            return EE_Config::$_module_route_map[$key][$route];
1321
-        }
1322
-        return null;
1323
-    }
1324
-
1325
-
1326
-
1327
-    /**
1328
-     *    get_routes - get ALL module method routes
1329
-     *
1330
-     * @access    public
1331
-     * @return    array
1332
-     */
1333
-    public static function get_routes()
1334
-    {
1335
-        return EE_Config::$_module_route_map;
1336
-    }
1337
-
1338
-
1339
-
1340
-    /**
1341
-     *    register_forward - allows modules to forward request to another module for further processing
1342
-     *
1343
-     * @access    public
1344
-     * @param    string       $route   - "pretty" public alias for module method
1345
-     * @param    integer      $status  - integer value corresponding  to status constant strings set in module parent
1346
-     *                                 class, allows different forwards to be served based on status
1347
-     * @param    array|string $forward - function name or array( class, method )
1348
-     * @param    string       $key     - url param key indicating a route is being called
1349
-     * @return    bool
1350
-     */
1351
-    public static function register_forward($route = null, $status = 0, $forward = null, $key = 'ee')
1352
-    {
1353
-        do_action('AHEE__EE_Config__register_forward', $route, $status, $forward);
1354
-        if (! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1355
-            $msg = sprintf(
1356
-                __('The module route %s for this forward has not been registered.', 'event_espresso'),
1357
-                $route
1358
-            );
1359
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1360
-            return false;
1361
-        }
1362
-        if (empty($forward)) {
1363
-            $msg = sprintf(__('No forwarding route has been supplied.', 'event_espresso'), $route);
1364
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1365
-            return false;
1366
-        }
1367
-        if (is_array($forward)) {
1368
-            if (! isset($forward[1])) {
1369
-                $msg = sprintf(
1370
-                    __('A class method for the %s forwarding route has not been supplied.', 'event_espresso'),
1371
-                    $route
1372
-                );
1373
-                EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1374
-                return false;
1375
-            }
1376
-            if (! method_exists($forward[0], $forward[1])) {
1377
-                $msg = sprintf(
1378
-                    __('The class method %s for the %s forwarding route is in invalid.', 'event_espresso'),
1379
-                    $forward[1],
1380
-                    $route
1381
-                );
1382
-                EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1383
-                return false;
1384
-            }
1385
-        } else if (! function_exists($forward)) {
1386
-            $msg = sprintf(
1387
-                __('The function %s for the %s forwarding route is in invalid.', 'event_espresso'),
1388
-                $forward,
1389
-                $route
1390
-            );
1391
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1392
-            return false;
1393
-        }
1394
-        EE_Config::$_module_forward_map[$key][$route][absint($status)] = $forward;
1395
-        return true;
1396
-    }
1397
-
1398
-
1399
-
1400
-    /**
1401
-     *    get_forward - get forwarding route
1402
-     *
1403
-     * @access    public
1404
-     * @param    string  $route  - "pretty" public alias for module method
1405
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1406
-     *                           allows different forwards to be served based on status
1407
-     * @param    string  $key    - url param key indicating a route is being called
1408
-     * @return    string
1409
-     */
1410
-    public static function get_forward($route = null, $status = 0, $key = 'ee')
1411
-    {
1412
-        do_action('AHEE__EE_Config__get_forward__begin', $route, $status);
1413
-        if (isset(EE_Config::$_module_forward_map[$key][$route][$status])) {
1414
-            return apply_filters(
1415
-                'FHEE__EE_Config__get_forward',
1416
-                EE_Config::$_module_forward_map[$key][$route][$status],
1417
-                $route,
1418
-                $status
1419
-            );
1420
-        }
1421
-        return null;
1422
-    }
1423
-
1424
-
1425
-
1426
-    /**
1427
-     *    register_forward - allows modules to specify different view templates for different method routes and status
1428
-     *    results
1429
-     *
1430
-     * @access    public
1431
-     * @param    string  $route  - "pretty" public alias for module method
1432
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1433
-     *                           allows different views to be served based on status
1434
-     * @param    string  $view
1435
-     * @param    string  $key    - url param key indicating a route is being called
1436
-     * @return    bool
1437
-     */
1438
-    public static function register_view($route = null, $status = 0, $view = null, $key = 'ee')
1439
-    {
1440
-        do_action('AHEE__EE_Config__register_view__begin', $route, $status, $view);
1441
-        if (! isset(EE_Config::$_module_route_map[$key][$route]) || empty($route)) {
1442
-            $msg = sprintf(
1443
-                __('The module route %s for this view has not been registered.', 'event_espresso'),
1444
-                $route
1445
-            );
1446
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1447
-            return false;
1448
-        }
1449
-        if (! is_readable($view)) {
1450
-            $msg = sprintf(
1451
-                __(
1452
-                    'The %s view file could not be found or is not readable due to file permissions.',
1453
-                    'event_espresso'
1454
-                ),
1455
-                $view
1456
-            );
1457
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
1458
-            return false;
1459
-        }
1460
-        EE_Config::$_module_view_map[$key][$route][absint($status)] = $view;
1461
-        return true;
1462
-    }
1463
-
1464
-
1465
-
1466
-    /**
1467
-     *    get_view - get view for route and status
1468
-     *
1469
-     * @access    public
1470
-     * @param    string  $route  - "pretty" public alias for module method
1471
-     * @param    integer $status - integer value corresponding  to status constant strings set in module parent class,
1472
-     *                           allows different views to be served based on status
1473
-     * @param    string  $key    - url param key indicating a route is being called
1474
-     * @return    string
1475
-     */
1476
-    public static function get_view($route = null, $status = 0, $key = 'ee')
1477
-    {
1478
-        do_action('AHEE__EE_Config__get_view__begin', $route, $status);
1479
-        if (isset(EE_Config::$_module_view_map[$key][$route][$status])) {
1480
-            return apply_filters(
1481
-                'FHEE__EE_Config__get_view',
1482
-                EE_Config::$_module_view_map[$key][$route][$status],
1483
-                $route,
1484
-                $status
1485
-            );
1486
-        }
1487
-        return null;
1488
-    }
1489
-
1490
-
1491
-
1492
-    public function update_addon_option_names()
1493
-    {
1494
-        update_option(EE_Config::ADDON_OPTION_NAMES, $this->_addon_option_names);
1495
-    }
1496
-
1497
-
1498
-
1499
-    public function shutdown()
1500
-    {
1501
-        $this->update_addon_option_names();
1502
-    }
1503
-
1504
-
1505
-
1506
-    /**
1507
-     * @return LegacyShortcodesManager
1508
-     */
1509
-    public static function getLegacyShortcodesManager()
1510
-    {
1511
-
1512
-        if ( ! EE_Config::instance()->legacy_shortcodes_manager instanceof LegacyShortcodesManager) {
1513
-            EE_Config::instance()->legacy_shortcodes_manager = new LegacyShortcodesManager(
1514
-                EE_Registry::instance()
1515
-            );
1516
-        }
1517
-        return EE_Config::instance()->legacy_shortcodes_manager;
1518
-    }
1519
-
1520
-
1521
-
1522
-    /**
1523
-     * register_shortcode - makes core aware of this shortcode
1524
-     *
1525
-     * @deprecated 4.9.26
1526
-     * @param    string $shortcode_path - full path up to and including shortcode folder
1527
-     * @return    bool
1528
-     */
1529
-    public static function register_shortcode($shortcode_path = null)
1530
-    {
1531
-        EE_Error::doing_it_wrong(
1532
-            __METHOD__,
1533
-            __(
1534
-                '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.',
1535
-                'event_espresso'
1536
-            ),
1537
-            '4.9.26'
1538
-        );
1539
-        return EE_Config::instance()->getLegacyShortcodesManager()->registerShortcode($shortcode_path);
1540
-    }
1541
-
1542
-
1543
-
1544
-}
1545
-
1546
-
1547
-
1548
-/**
1549
- * Base class used for config classes. These classes should generally not have
1550
- * magic functions in use, except we'll allow them to magically set and get stuff...
1551
- * basically, they should just be well-defined stdClasses
1552
- */
1553
-class EE_Config_Base
1554
-{
1555
-
1556
-    /**
1557
-     * Utility function for escaping the value of a property and returning.
1558
-     *
1559
-     * @param string $property property name (checks to see if exists).
1560
-     * @return mixed if a detected type found return the escaped value, otherwise just the raw value is returned.
1561
-     * @throws \EE_Error
1562
-     */
1563
-    public function get_pretty($property)
1564
-    {
1565
-        if (! property_exists($this, $property)) {
1566
-            throw new EE_Error(
1567
-                sprintf(
1568
-                    __(
1569
-                        '%1$s::get_pretty() has been called with the property %2$s which does not exist on the %1$s config class.',
1570
-                        'event_espresso'
1571
-                    ),
1572
-                    get_class($this),
1573
-                    $property
1574
-                )
1575
-            );
1576
-        }
1577
-        //just handling escaping of strings for now.
1578
-        if (is_string($this->{$property})) {
1579
-            return stripslashes($this->{$property});
1580
-        }
1581
-        return $this->{$property};
1582
-    }
1583
-
1584
-
1585
-
1586
-    public function populate()
1587
-    {
1588
-        //grab defaults via a new instance of this class.
1589
-        $class_name = get_class($this);
1590
-        $defaults = new $class_name;
1591
-        //loop through the properties for this class and see if they are set.  If they are NOT, then grab the
1592
-        //default from our $defaults object.
1593
-        foreach (get_object_vars($defaults) as $property => $value) {
1594
-            if ($this->{$property} === null) {
1595
-                $this->{$property} = $value;
1596
-            }
1597
-        }
1598
-        //cleanup
1599
-        unset($defaults);
1600
-    }
1601
-
1602
-
1603
-
1604
-    /**
1605
-     *        __isset
1606
-     *
1607
-     * @param $a
1608
-     * @return bool
1609
-     */
1610
-    public function __isset($a)
1611
-    {
1612
-        return false;
1613
-    }
1614
-
1615
-
1616
-
1617
-    /**
1618
-     *        __unset
1619
-     *
1620
-     * @param $a
1621
-     * @return bool
1622
-     */
1623
-    public function __unset($a)
1624
-    {
1625
-        return false;
1626
-    }
1627
-
1628
-
1629
-
1630
-    /**
1631
-     *        __clone
1632
-     */
1633
-    public function __clone()
1634
-    {
1635
-    }
1636
-
1637
-
1638
-
1639
-    /**
1640
-     *        __wakeup
1641
-     */
1642
-    public function __wakeup()
1643
-    {
1644
-    }
1645
-
1646
-
1647
-
1648
-    /**
1649
-     *        __destruct
1650
-     */
1651
-    public function __destruct()
1652
-    {
1653
-    }
1654
-}
1655
-
1656
-
1657
-
1658
-/**
1659
- * Class for defining what's in the EE_Config relating to registration settings
1660
- */
1661
-class EE_Core_Config extends EE_Config_Base
1662
-{
1663
-
1664
-    public $current_blog_id;
1665
-
1666
-    public $ee_ueip_optin;
1667
-
1668
-    public $ee_ueip_has_notified;
1669
-
1670
-    /**
1671
-     * Not to be confused with the 4 critical page variables (See
1672
-     * get_critical_pages_array()), this is just an array of wp posts that have EE
1673
-     * shortcodes in them. Keys are slugs, values are arrays with only 1 element: where the key is the shortcode
1674
-     * in the page, and the value is the page's ID. The key 'posts' is basically a duplicate of this same array.
1675
-     *
1676
-     * @var array
1677
-     */
1678
-    public $post_shortcodes;
1679
-
1680
-    public $module_route_map;
1681
-
1682
-    public $module_forward_map;
1683
-
1684
-    public $module_view_map;
1685
-
1686
-    /**
1687
-     * The next 4 vars are the IDs of critical EE pages.
1688
-     *
1689
-     * @var int
1690
-     */
1691
-    public $reg_page_id;
1692
-
1693
-    public $txn_page_id;
1694
-
1695
-    public $thank_you_page_id;
1696
-
1697
-    public $cancel_page_id;
1698
-
1699
-    /**
1700
-     * The next 4 vars are the URLs of critical EE pages.
1701
-     *
1702
-     * @var int
1703
-     */
1704
-    public $reg_page_url;
1705
-
1706
-    public $txn_page_url;
1707
-
1708
-    public $thank_you_page_url;
1709
-
1710
-    public $cancel_page_url;
1711
-
1712
-    /**
1713
-     * The next vars relate to the custom slugs for EE CPT routes
1714
-     */
1715
-    public $event_cpt_slug;
1716
-
1717
-
1718
-    /**
1719
-     * This caches the _ee_ueip_option in case this config is reset in the same
1720
-     * request across blog switches in a multisite context.
1721
-     * Avoids extra queries to the db for this option.
1722
-     *
1723
-     * @var bool
1724
-     */
1725
-    public static $ee_ueip_option;
1726
-
1727
-
1728
-
1729
-    /**
1730
-     *    class constructor
1731
-     *
1732
-     * @access    public
1733
-     */
1734
-    public function __construct()
1735
-    {
1736
-        // set default organization settings
1737
-        $this->current_blog_id = get_current_blog_id();
1738
-        $this->current_blog_id = $this->current_blog_id === null ? 1 : $this->current_blog_id;
1739
-        $this->ee_ueip_optin = $this->_get_main_ee_ueip_optin();
1740
-        $this->ee_ueip_has_notified = is_main_site() ? get_option('ee_ueip_has_notified', false) : true;
1741
-        $this->post_shortcodes = array();
1742
-        $this->module_route_map = array();
1743
-        $this->module_forward_map = array();
1744
-        $this->module_view_map = array();
1745
-        // critical EE page IDs
1746
-        $this->reg_page_id = 0;
1747
-        $this->txn_page_id = 0;
1748
-        $this->thank_you_page_id = 0;
1749
-        $this->cancel_page_id = 0;
1750
-        // critical EE page URLs
1751
-        $this->reg_page_url = '';
1752
-        $this->txn_page_url = '';
1753
-        $this->thank_you_page_url = '';
1754
-        $this->cancel_page_url = '';
1755
-        //cpt slugs
1756
-        $this->event_cpt_slug = __('events', 'event_espresso');
1757
-        //ueip constant check
1758
-        if (defined('EE_DISABLE_UXIP') && EE_DISABLE_UXIP) {
1759
-            $this->ee_ueip_optin = false;
1760
-            $this->ee_ueip_has_notified = true;
1761
-        }
1762
-    }
1763
-
1764
-
1765
-
1766
-    /**
1767
-     * @return array
1768
-     */
1769
-    public function get_critical_pages_array()
1770
-    {
1771
-        return array(
1772
-            $this->reg_page_id,
1773
-            $this->txn_page_id,
1774
-            $this->thank_you_page_id,
1775
-            $this->cancel_page_id,
1776
-        );
1777
-    }
1778
-
1779
-
1780
-
1781
-    /**
1782
-     * @return array
1783
-     */
1784
-    public function get_critical_pages_shortcodes_array()
1785
-    {
1786
-        return array(
1787
-            $this->reg_page_id       => 'ESPRESSO_CHECKOUT',
1788
-            $this->txn_page_id       => 'ESPRESSO_TXN_PAGE',
1789
-            $this->thank_you_page_id => 'ESPRESSO_THANK_YOU',
1790
-            $this->cancel_page_id    => 'ESPRESSO_CANCELLED',
1791
-        );
1792
-    }
1793
-
1794
-
1795
-
1796
-    /**
1797
-     *  gets/returns URL for EE reg_page
1798
-     *
1799
-     * @access    public
1800
-     * @return    string
1801
-     */
1802
-    public function reg_page_url()
1803
-    {
1804
-        if (! $this->reg_page_url) {
1805
-            $this->reg_page_url = add_query_arg(
1806
-                                      array('uts' => time()),
1807
-                                      get_permalink($this->reg_page_id)
1808
-                                  ) . '#checkout';
1809
-        }
1810
-        return $this->reg_page_url;
1811
-    }
1812
-
1813
-
1814
-
1815
-    /**
1816
-     *  gets/returns URL for EE txn_page
1817
-     *
1818
-     * @param array $query_args like what gets passed to
1819
-     *                          add_query_arg() as the first argument
1820
-     * @access    public
1821
-     * @return    string
1822
-     */
1823
-    public function txn_page_url($query_args = array())
1824
-    {
1825
-        if (! $this->txn_page_url) {
1826
-            $this->txn_page_url = get_permalink($this->txn_page_id);
1827
-        }
1828
-        if ($query_args) {
1829
-            return add_query_arg($query_args, $this->txn_page_url);
1830
-        } else {
1831
-            return $this->txn_page_url;
1832
-        }
1833
-    }
1834
-
1835
-
1836
-
1837
-    /**
1838
-     *  gets/returns URL for EE thank_you_page
1839
-     *
1840
-     * @param array $query_args like what gets passed to
1841
-     *                          add_query_arg() as the first argument
1842
-     * @access    public
1843
-     * @return    string
1844
-     */
1845
-    public function thank_you_page_url($query_args = array())
1846
-    {
1847
-        if (! $this->thank_you_page_url) {
1848
-            $this->thank_you_page_url = get_permalink($this->thank_you_page_id);
1849
-        }
1850
-        if ($query_args) {
1851
-            return add_query_arg($query_args, $this->thank_you_page_url);
1852
-        } else {
1853
-            return $this->thank_you_page_url;
1854
-        }
1855
-    }
1856
-
1857
-
1858
-
1859
-    /**
1860
-     *  gets/returns URL for EE cancel_page
1861
-     *
1862
-     * @access    public
1863
-     * @return    string
1864
-     */
1865
-    public function cancel_page_url()
1866
-    {
1867
-        if (! $this->cancel_page_url) {
1868
-            $this->cancel_page_url = get_permalink($this->cancel_page_id);
1869
-        }
1870
-        return $this->cancel_page_url;
1871
-    }
1872
-
1873
-
1874
-
1875
-    /**
1876
-     * Resets all critical page urls to their original state.  Used primarily by the __sleep() magic method currently.
1877
-     *
1878
-     * @since 4.7.5
1879
-     */
1880
-    protected function _reset_urls()
1881
-    {
1882
-        $this->reg_page_url = '';
1883
-        $this->txn_page_url = '';
1884
-        $this->cancel_page_url = '';
1885
-        $this->thank_you_page_url = '';
1886
-    }
1887
-
1888
-
1889
-
1890
-    /**
1891
-     * Used to return what the optin value is set for the EE User Experience Program.
1892
-     * This accounts for multisite and this value being requested for a subsite.  In multisite, the value is set
1893
-     * on the main site only.
1894
-     *
1895
-     * @return mixed|void
1896
-     */
1897
-    protected function _get_main_ee_ueip_optin()
1898
-    {
1899
-        //if this is the main site then we can just bypass our direct query.
1900
-        if (is_main_site()) {
1901
-            return get_option('ee_ueip_optin', false);
1902
-        }
1903
-        //is this already cached for this request?  If so use it.
1904
-        if ( ! empty(EE_Core_Config::$ee_ueip_option)) {
1905
-            return EE_Core_Config::$ee_ueip_option;
1906
-        }
1907
-        global $wpdb;
1908
-        $current_network_main_site = is_multisite() ? get_current_site() : null;
1909
-        $current_main_site_id = ! empty($current_network_main_site) ? $current_network_main_site->blog_id : 1;
1910
-        $option = 'ee_ueip_optin';
1911
-        //set correct table for query
1912
-        $table_name = $wpdb->get_blog_prefix($current_main_site_id) . 'options';
1913
-        //rather than getting blog option for the $current_main_site_id, we do a direct $wpdb query because
1914
-        //get_blog_option() does a switch_to_blog an that could cause infinite recursion because EE_Core_Config might be
1915
-        //re-constructed on the blog switch.  Note, we are still executing any core wp filters on this option retrieval.
1916
-        //this bit of code is basically a direct copy of get_option without any caching because we are NOT switched to the blog
1917
-        //for the purpose of caching.
1918
-        $pre = apply_filters('pre_option_' . $option, false, $option);
1919
-        if (false !== $pre) {
1920
-            EE_Core_Config::$ee_ueip_option = $pre;
1921
-            return EE_Core_Config::$ee_ueip_option;
1922
-        }
1923
-        $row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $table_name WHERE option_name = %s LIMIT 1",
1924
-            $option));
1925
-        if (is_object($row)) {
1926
-            $value = $row->option_value;
1927
-        } else { //option does not exist so use default.
1928
-            return apply_filters('default_option_' . $option, false, $option);
1929
-        }
1930
-        EE_Core_Config::$ee_ueip_option = apply_filters('option_' . $option, maybe_unserialize($value), $option);
1931
-        return EE_Core_Config::$ee_ueip_option;
1932
-    }
1933
-
1934
-
1935
-
1936
-    /**
1937
-     * Currently used to ensure critical page urls have initial values saved to the db instead of any current set values
1938
-     * on the object.
1939
-     *
1940
-     * @return array
1941
-     */
1942
-    public function __sleep()
1943
-    {
1944
-        //reset all url properties
1945
-        $this->_reset_urls();
1946
-        //return what to save to db
1947
-        return array_keys(get_object_vars($this));
1948
-    }
1949
-
1950
-}
1951
-
1952
-
1953
-
1954
-/**
1955
- * Config class for storing info on the Organization
1956
- */
1957
-class EE_Organization_Config extends EE_Config_Base
1958
-{
1959
-
1960
-    /**
1961
-     * @var string $name
1962
-     * eg EE4.1
1963
-     */
1964
-    public $name;
1965
-
1966
-    /**
1967
-     * @var string $address_1
1968
-     * eg 123 Onna Road
1969
-     */
1970
-    public $address_1;
1971
-
1972
-    /**
1973
-     * @var string $address_2
1974
-     * eg PO Box 123
1975
-     */
1976
-    public $address_2;
1977
-
1978
-    /**
1979
-     * @var string $city
1980
-     * eg Inna City
1981
-     */
1982
-    public $city;
1983
-
1984
-    /**
1985
-     * @var int $STA_ID
1986
-     * eg 4
1987
-     */
1988
-    public $STA_ID;
1989
-
1990
-    /**
1991
-     * @var string $CNT_ISO
1992
-     * eg US
1993
-     */
1994
-    public $CNT_ISO;
1995
-
1996
-    /**
1997
-     * @var string $zip
1998
-     * eg 12345  or V1A 2B3
1999
-     */
2000
-    public $zip;
2001
-
2002
-    /**
2003
-     * @var string $email
2004
-     * eg [email protected]
2005
-     */
2006
-    public $email;
2007
-
2008
-
2009
-    /**
2010
-     * @var string $phone
2011
-     * eg. 111-111-1111
2012
-     */
2013
-    public $phone;
2014
-
2015
-
2016
-    /**
2017
-     * @var string $vat
2018
-     * VAT/Tax Number
2019
-     */
2020
-    public $vat;
2021
-
2022
-    /**
2023
-     * @var string $logo_url
2024
-     * eg http://www.somedomain.com/wp-content/uploads/kittehs.jpg
2025
-     */
2026
-    public $logo_url;
2027
-
2028
-
2029
-    /**
2030
-     * The below are all various properties for holding links to organization social network profiles
2031
-     *
2032
-     * @var string
2033
-     */
2034
-    /**
2035
-     * facebook (facebook.com/profile.name)
2036
-     *
2037
-     * @var string
2038
-     */
2039
-    public $facebook;
2040
-
2041
-
2042
-    /**
2043
-     * twitter (twitter.com/twitter_handle)
2044
-     *
2045
-     * @var string
2046
-     */
2047
-    public $twitter;
2048
-
2049
-
2050
-    /**
2051
-     * linkedin (linkedin.com/in/profile_name)
2052
-     *
2053
-     * @var string
2054
-     */
2055
-    public $linkedin;
2056
-
2057
-
2058
-    /**
2059
-     * pinterest (www.pinterest.com/profile_name)
2060
-     *
2061
-     * @var string
2062
-     */
2063
-    public $pinterest;
2064
-
2065
-
2066
-    /**
2067
-     * google+ (google.com/+profileName)
2068
-     *
2069
-     * @var string
2070
-     */
2071
-    public $google;
2072
-
2073
-
2074
-    /**
2075
-     * instagram (instagram.com/handle)
2076
-     *
2077
-     * @var string
2078
-     */
2079
-    public $instagram;
2080
-
2081
-
2082
-
2083
-    /**
2084
-     *    class constructor
2085
-     *
2086
-     * @access    public
2087
-     */
2088
-    public function __construct()
2089
-    {
2090
-        // set default organization settings
2091
-        $this->name = get_bloginfo('name');
2092
-        $this->address_1 = '123 Onna Road';
2093
-        $this->address_2 = 'PO Box 123';
2094
-        $this->city = 'Inna City';
2095
-        $this->STA_ID = 4;
2096
-        $this->CNT_ISO = 'US';
2097
-        $this->zip = '12345';
2098
-        $this->email = get_bloginfo('admin_email');
2099
-        $this->phone = '';
2100
-        $this->vat = '123456789';
2101
-        $this->logo_url = '';
2102
-        $this->facebook = '';
2103
-        $this->twitter = '';
2104
-        $this->linkedin = '';
2105
-        $this->pinterest = '';
2106
-        $this->google = '';
2107
-        $this->instagram = '';
2108
-    }
2109
-
2110
-}
2111
-
2112
-
2113
-
2114
-/**
2115
- * Class for defining what's in the EE_Config relating to currency
2116
- */
2117
-class EE_Currency_Config extends EE_Config_Base
2118
-{
2119
-
2120
-    /**
2121
-     * @var string $code
2122
-     * eg 'US'
2123
-     */
2124
-    public $code;
2125
-
2126
-    /**
2127
-     * @var string $name
2128
-     * eg 'Dollar'
2129
-     */
2130
-    public $name;
2131
-
2132
-    /**
2133
-     * plural name
2134
-     *
2135
-     * @var string $plural
2136
-     * eg 'Dollars'
2137
-     */
2138
-    public $plural;
2139
-
2140
-    /**
2141
-     * currency sign
2142
-     *
2143
-     * @var string $sign
2144
-     * eg '$'
2145
-     */
2146
-    public $sign;
2147
-
2148
-    /**
2149
-     * Whether the currency sign should come before the number or not
2150
-     *
2151
-     * @var boolean $sign_b4
2152
-     */
2153
-    public $sign_b4;
2154
-
2155
-    /**
2156
-     * How many digits should come after the decimal place
2157
-     *
2158
-     * @var int $dec_plc
2159
-     */
2160
-    public $dec_plc;
2161
-
2162
-    /**
2163
-     * Symbol to use for decimal mark
2164
-     *
2165
-     * @var string $dec_mrk
2166
-     * eg '.'
2167
-     */
2168
-    public $dec_mrk;
2169
-
2170
-    /**
2171
-     * Symbol to use for thousands
2172
-     *
2173
-     * @var string $thsnds
2174
-     * eg ','
2175
-     */
2176
-    public $thsnds;
2177
-
2178
-
2179
-
2180
-    /**
2181
-     *    class constructor
2182
-     *
2183
-     * @access    public
2184
-     * @param string $CNT_ISO
2185
-     * @throws \EE_Error
2186
-     */
2187
-    public function __construct($CNT_ISO = '')
2188
-    {
2189
-        /** @var \EventEspresso\core\services\database\TableAnalysis $table_analysis */
2190
-        $table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
2191
-        // get country code from organization settings or use default
2192
-        $ORG_CNT = isset(EE_Registry::instance()->CFG->organization)
2193
-                   && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
2194
-            ? EE_Registry::instance()->CFG->organization->CNT_ISO
2195
-            : '';
2196
-        // but override if requested
2197
-        $CNT_ISO = ! empty($CNT_ISO) ? $CNT_ISO : $ORG_CNT;
2198
-        // 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
2199
-        if (
2200
-            ! empty($CNT_ISO)
2201
-            && EE_Maintenance_Mode::instance()->models_can_query()
2202
-            && $table_analysis->tableExists(EE_Registry::instance()->load_model('Country')->table())
2203
-        ) {
2204
-            // retrieve the country settings from the db, just in case they have been customized
2205
-            $country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($CNT_ISO);
2206
-            if ($country instanceof EE_Country) {
2207
-                $this->code = $country->currency_code();    // currency code: USD, CAD, EUR
2208
-                $this->name = $country->currency_name_single();    // Dollar
2209
-                $this->plural = $country->currency_name_plural();    // Dollars
2210
-                $this->sign = $country->currency_sign();            // currency sign: $
2211
-                $this->sign_b4 = $country->currency_sign_before();        // currency sign before or after: $TRUE  or  FALSE$
2212
-                $this->dec_plc = $country->currency_decimal_places();    // decimal places: 2 = 0.00  3 = 0.000
2213
-                $this->dec_mrk = $country->currency_decimal_mark();    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2214
-                $this->thsnds = $country->currency_thousands_separator();    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2215
-            }
2216
-        }
2217
-        // fallback to hardcoded defaults, in case the above failed
2218
-        if (empty($this->code)) {
2219
-            // set default currency settings
2220
-            $this->code = 'USD';    // currency code: USD, CAD, EUR
2221
-            $this->name = __('Dollar', 'event_espresso');    // Dollar
2222
-            $this->plural = __('Dollars', 'event_espresso');    // Dollars
2223
-            $this->sign = '$';    // currency sign: $
2224
-            $this->sign_b4 = true;    // currency sign before or after: $TRUE  or  FALSE$
2225
-            $this->dec_plc = 2;    // decimal places: 2 = 0.00  3 = 0.000
2226
-            $this->dec_mrk = '.';    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2227
-            $this->thsnds = ',';    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2228
-        }
2229
-    }
2230
-}
2231
-
2232
-
2233
-
2234
-/**
2235
- * Class for defining what's in the EE_Config relating to registration settings
2236
- */
2237
-class EE_Registration_Config extends EE_Config_Base
2238
-{
2239
-
2240
-    /**
2241
-     * Default registration status
2242
-     *
2243
-     * @var string $default_STS_ID
2244
-     * eg 'RPP'
2245
-     */
2246
-    public $default_STS_ID;
2247
-
2248
-
2249
-    /**
2250
-     * For new events, this will be the default value for the maximum number of tickets (equivalent to maximum number of
2251
-     * registrations)
2252
-     * @var int
2253
-     */
2254
-    public $default_maximum_number_of_tickets;
2255
-
2256
-
2257
-    /**
2258
-     * level of validation to apply to email addresses
2259
-     *
2260
-     * @var string $email_validation_level
2261
-     * options: 'basic', 'wp_default', 'i18n', 'i18n_dns'
2262
-     */
2263
-    public $email_validation_level;
2264
-
2265
-    /**
2266
-     *    whether or not to show alternate payment options during the reg process if payment status is pending
2267
-     *
2268
-     * @var boolean $show_pending_payment_options
2269
-     */
2270
-    public $show_pending_payment_options;
2271
-
2272
-    /**
2273
-     * Whether to skip the registration confirmation page
2274
-     *
2275
-     * @var boolean $skip_reg_confirmation
2276
-     */
2277
-    public $skip_reg_confirmation;
2278
-
2279
-    /**
2280
-     * an array of SPCO reg steps where:
2281
-     *        the keys denotes the reg step order
2282
-     *        each element consists of an array with the following elements:
2283
-     *            "file_path" => the file path to the EE_SPCO_Reg_Step class
2284
-     *            "class_name" => the specific EE_SPCO_Reg_Step child class name
2285
-     *            "slug" => the URL param used to trigger the reg step
2286
-     *
2287
-     * @var array $reg_steps
2288
-     */
2289
-    public $reg_steps;
2290
-
2291
-    /**
2292
-     * Whether registration confirmation should be the last page of SPCO
2293
-     *
2294
-     * @var boolean $reg_confirmation_last
2295
-     */
2296
-    public $reg_confirmation_last;
2297
-
2298
-    /**
2299
-     * Whether or not to enable the EE Bot Trap
2300
-     *
2301
-     * @var boolean $use_bot_trap
2302
-     */
2303
-    public $use_bot_trap;
2304
-
2305
-    /**
2306
-     * Whether or not to encrypt some data sent by the EE Bot Trap
2307
-     *
2308
-     * @var boolean $use_encryption
2309
-     */
2310
-    public $use_encryption;
1544
+}
2311 1545
 
2312
-    /**
2313
-     * Whether or not to use ReCaptcha
2314
-     *
2315
-     * @var boolean $use_captcha
2316
-     */
2317
-    public $use_captcha;
2318 1546
 
2319
-    /**
2320
-     * ReCaptcha Theme
2321
-     *
2322
-     * @var string $recaptcha_theme
2323
-     *    options: 'dark    ', 'light'
2324
-     */
2325
-    public $recaptcha_theme;
2326 1547
 
2327
-    /**
2328
-     * ReCaptcha Type
2329
-     *
2330
-     * @var string $recaptcha_type
2331
-     *    options: 'audio', 'image'
2332
-     */
2333
-    public $recaptcha_type;
1548
+/**
1549
+ * Base class used for config classes. These classes should generally not have
1550
+ * magic functions in use, except we'll allow them to magically set and get stuff...
1551
+ * basically, they should just be well-defined stdClasses
1552
+ */
1553
+class EE_Config_Base
1554
+{
2334 1555
 
2335
-    /**
2336
-     * ReCaptcha language
2337
-     *
2338
-     * @var string $recaptcha_language
2339
-     * eg 'en'
2340
-     */
2341
-    public $recaptcha_language;
1556
+	/**
1557
+	 * Utility function for escaping the value of a property and returning.
1558
+	 *
1559
+	 * @param string $property property name (checks to see if exists).
1560
+	 * @return mixed if a detected type found return the escaped value, otherwise just the raw value is returned.
1561
+	 * @throws \EE_Error
1562
+	 */
1563
+	public function get_pretty($property)
1564
+	{
1565
+		if (! property_exists($this, $property)) {
1566
+			throw new EE_Error(
1567
+				sprintf(
1568
+					__(
1569
+						'%1$s::get_pretty() has been called with the property %2$s which does not exist on the %1$s config class.',
1570
+						'event_espresso'
1571
+					),
1572
+					get_class($this),
1573
+					$property
1574
+				)
1575
+			);
1576
+		}
1577
+		//just handling escaping of strings for now.
1578
+		if (is_string($this->{$property})) {
1579
+			return stripslashes($this->{$property});
1580
+		}
1581
+		return $this->{$property};
1582
+	}
1583
+
1584
+
1585
+
1586
+	public function populate()
1587
+	{
1588
+		//grab defaults via a new instance of this class.
1589
+		$class_name = get_class($this);
1590
+		$defaults = new $class_name;
1591
+		//loop through the properties for this class and see if they are set.  If they are NOT, then grab the
1592
+		//default from our $defaults object.
1593
+		foreach (get_object_vars($defaults) as $property => $value) {
1594
+			if ($this->{$property} === null) {
1595
+				$this->{$property} = $value;
1596
+			}
1597
+		}
1598
+		//cleanup
1599
+		unset($defaults);
1600
+	}
1601
+
1602
+
1603
+
1604
+	/**
1605
+	 *        __isset
1606
+	 *
1607
+	 * @param $a
1608
+	 * @return bool
1609
+	 */
1610
+	public function __isset($a)
1611
+	{
1612
+		return false;
1613
+	}
1614
+
1615
+
1616
+
1617
+	/**
1618
+	 *        __unset
1619
+	 *
1620
+	 * @param $a
1621
+	 * @return bool
1622
+	 */
1623
+	public function __unset($a)
1624
+	{
1625
+		return false;
1626
+	}
1627
+
1628
+
1629
+
1630
+	/**
1631
+	 *        __clone
1632
+	 */
1633
+	public function __clone()
1634
+	{
1635
+	}
1636
+
1637
+
1638
+
1639
+	/**
1640
+	 *        __wakeup
1641
+	 */
1642
+	public function __wakeup()
1643
+	{
1644
+	}
1645
+
1646
+
1647
+
1648
+	/**
1649
+	 *        __destruct
1650
+	 */
1651
+	public function __destruct()
1652
+	{
1653
+	}
1654
+}
2342 1655
 
2343
-    /**
2344
-     * ReCaptcha public key
2345
-     *
2346
-     * @var string $recaptcha_publickey
2347
-     */
2348
-    public $recaptcha_publickey;
2349 1656
 
2350
-    /**
2351
-     * ReCaptcha private key
2352
-     *
2353
-     * @var string $recaptcha_privatekey
2354
-     */
2355
-    public $recaptcha_privatekey;
2356 1657
 
2357
-    /**
2358
-     * ReCaptcha width
2359
-     *
2360
-     * @var int $recaptcha_width
2361
-     * @deprecated
2362
-     */
2363
-    public $recaptcha_width;
1658
+/**
1659
+ * Class for defining what's in the EE_Config relating to registration settings
1660
+ */
1661
+class EE_Core_Config extends EE_Config_Base
1662
+{
2364 1663
 
2365
-    /**
2366
-     * Whether or not invalid attempts to directly access the registration checkout page should be tracked.
2367
-     *
2368
-     * @var boolean $track_invalid_checkout_access
2369
-     */
2370
-    protected $track_invalid_checkout_access = true;
1664
+	public $current_blog_id;
1665
+
1666
+	public $ee_ueip_optin;
1667
+
1668
+	public $ee_ueip_has_notified;
1669
+
1670
+	/**
1671
+	 * Not to be confused with the 4 critical page variables (See
1672
+	 * get_critical_pages_array()), this is just an array of wp posts that have EE
1673
+	 * shortcodes in them. Keys are slugs, values are arrays with only 1 element: where the key is the shortcode
1674
+	 * in the page, and the value is the page's ID. The key 'posts' is basically a duplicate of this same array.
1675
+	 *
1676
+	 * @var array
1677
+	 */
1678
+	public $post_shortcodes;
1679
+
1680
+	public $module_route_map;
1681
+
1682
+	public $module_forward_map;
1683
+
1684
+	public $module_view_map;
1685
+
1686
+	/**
1687
+	 * The next 4 vars are the IDs of critical EE pages.
1688
+	 *
1689
+	 * @var int
1690
+	 */
1691
+	public $reg_page_id;
1692
+
1693
+	public $txn_page_id;
1694
+
1695
+	public $thank_you_page_id;
1696
+
1697
+	public $cancel_page_id;
1698
+
1699
+	/**
1700
+	 * The next 4 vars are the URLs of critical EE pages.
1701
+	 *
1702
+	 * @var int
1703
+	 */
1704
+	public $reg_page_url;
1705
+
1706
+	public $txn_page_url;
1707
+
1708
+	public $thank_you_page_url;
1709
+
1710
+	public $cancel_page_url;
1711
+
1712
+	/**
1713
+	 * The next vars relate to the custom slugs for EE CPT routes
1714
+	 */
1715
+	public $event_cpt_slug;
1716
+
1717
+
1718
+	/**
1719
+	 * This caches the _ee_ueip_option in case this config is reset in the same
1720
+	 * request across blog switches in a multisite context.
1721
+	 * Avoids extra queries to the db for this option.
1722
+	 *
1723
+	 * @var bool
1724
+	 */
1725
+	public static $ee_ueip_option;
1726
+
1727
+
1728
+
1729
+	/**
1730
+	 *    class constructor
1731
+	 *
1732
+	 * @access    public
1733
+	 */
1734
+	public function __construct()
1735
+	{
1736
+		// set default organization settings
1737
+		$this->current_blog_id = get_current_blog_id();
1738
+		$this->current_blog_id = $this->current_blog_id === null ? 1 : $this->current_blog_id;
1739
+		$this->ee_ueip_optin = $this->_get_main_ee_ueip_optin();
1740
+		$this->ee_ueip_has_notified = is_main_site() ? get_option('ee_ueip_has_notified', false) : true;
1741
+		$this->post_shortcodes = array();
1742
+		$this->module_route_map = array();
1743
+		$this->module_forward_map = array();
1744
+		$this->module_view_map = array();
1745
+		// critical EE page IDs
1746
+		$this->reg_page_id = 0;
1747
+		$this->txn_page_id = 0;
1748
+		$this->thank_you_page_id = 0;
1749
+		$this->cancel_page_id = 0;
1750
+		// critical EE page URLs
1751
+		$this->reg_page_url = '';
1752
+		$this->txn_page_url = '';
1753
+		$this->thank_you_page_url = '';
1754
+		$this->cancel_page_url = '';
1755
+		//cpt slugs
1756
+		$this->event_cpt_slug = __('events', 'event_espresso');
1757
+		//ueip constant check
1758
+		if (defined('EE_DISABLE_UXIP') && EE_DISABLE_UXIP) {
1759
+			$this->ee_ueip_optin = false;
1760
+			$this->ee_ueip_has_notified = true;
1761
+		}
1762
+	}
1763
+
1764
+
1765
+
1766
+	/**
1767
+	 * @return array
1768
+	 */
1769
+	public function get_critical_pages_array()
1770
+	{
1771
+		return array(
1772
+			$this->reg_page_id,
1773
+			$this->txn_page_id,
1774
+			$this->thank_you_page_id,
1775
+			$this->cancel_page_id,
1776
+		);
1777
+	}
1778
+
1779
+
1780
+
1781
+	/**
1782
+	 * @return array
1783
+	 */
1784
+	public function get_critical_pages_shortcodes_array()
1785
+	{
1786
+		return array(
1787
+			$this->reg_page_id       => 'ESPRESSO_CHECKOUT',
1788
+			$this->txn_page_id       => 'ESPRESSO_TXN_PAGE',
1789
+			$this->thank_you_page_id => 'ESPRESSO_THANK_YOU',
1790
+			$this->cancel_page_id    => 'ESPRESSO_CANCELLED',
1791
+		);
1792
+	}
1793
+
1794
+
1795
+
1796
+	/**
1797
+	 *  gets/returns URL for EE reg_page
1798
+	 *
1799
+	 * @access    public
1800
+	 * @return    string
1801
+	 */
1802
+	public function reg_page_url()
1803
+	{
1804
+		if (! $this->reg_page_url) {
1805
+			$this->reg_page_url = add_query_arg(
1806
+									  array('uts' => time()),
1807
+									  get_permalink($this->reg_page_id)
1808
+								  ) . '#checkout';
1809
+		}
1810
+		return $this->reg_page_url;
1811
+	}
1812
+
1813
+
1814
+
1815
+	/**
1816
+	 *  gets/returns URL for EE txn_page
1817
+	 *
1818
+	 * @param array $query_args like what gets passed to
1819
+	 *                          add_query_arg() as the first argument
1820
+	 * @access    public
1821
+	 * @return    string
1822
+	 */
1823
+	public function txn_page_url($query_args = array())
1824
+	{
1825
+		if (! $this->txn_page_url) {
1826
+			$this->txn_page_url = get_permalink($this->txn_page_id);
1827
+		}
1828
+		if ($query_args) {
1829
+			return add_query_arg($query_args, $this->txn_page_url);
1830
+		} else {
1831
+			return $this->txn_page_url;
1832
+		}
1833
+	}
1834
+
1835
+
1836
+
1837
+	/**
1838
+	 *  gets/returns URL for EE thank_you_page
1839
+	 *
1840
+	 * @param array $query_args like what gets passed to
1841
+	 *                          add_query_arg() as the first argument
1842
+	 * @access    public
1843
+	 * @return    string
1844
+	 */
1845
+	public function thank_you_page_url($query_args = array())
1846
+	{
1847
+		if (! $this->thank_you_page_url) {
1848
+			$this->thank_you_page_url = get_permalink($this->thank_you_page_id);
1849
+		}
1850
+		if ($query_args) {
1851
+			return add_query_arg($query_args, $this->thank_you_page_url);
1852
+		} else {
1853
+			return $this->thank_you_page_url;
1854
+		}
1855
+	}
1856
+
1857
+
1858
+
1859
+	/**
1860
+	 *  gets/returns URL for EE cancel_page
1861
+	 *
1862
+	 * @access    public
1863
+	 * @return    string
1864
+	 */
1865
+	public function cancel_page_url()
1866
+	{
1867
+		if (! $this->cancel_page_url) {
1868
+			$this->cancel_page_url = get_permalink($this->cancel_page_id);
1869
+		}
1870
+		return $this->cancel_page_url;
1871
+	}
1872
+
1873
+
1874
+
1875
+	/**
1876
+	 * Resets all critical page urls to their original state.  Used primarily by the __sleep() magic method currently.
1877
+	 *
1878
+	 * @since 4.7.5
1879
+	 */
1880
+	protected function _reset_urls()
1881
+	{
1882
+		$this->reg_page_url = '';
1883
+		$this->txn_page_url = '';
1884
+		$this->cancel_page_url = '';
1885
+		$this->thank_you_page_url = '';
1886
+	}
1887
+
1888
+
1889
+
1890
+	/**
1891
+	 * Used to return what the optin value is set for the EE User Experience Program.
1892
+	 * This accounts for multisite and this value being requested for a subsite.  In multisite, the value is set
1893
+	 * on the main site only.
1894
+	 *
1895
+	 * @return mixed|void
1896
+	 */
1897
+	protected function _get_main_ee_ueip_optin()
1898
+	{
1899
+		//if this is the main site then we can just bypass our direct query.
1900
+		if (is_main_site()) {
1901
+			return get_option('ee_ueip_optin', false);
1902
+		}
1903
+		//is this already cached for this request?  If so use it.
1904
+		if ( ! empty(EE_Core_Config::$ee_ueip_option)) {
1905
+			return EE_Core_Config::$ee_ueip_option;
1906
+		}
1907
+		global $wpdb;
1908
+		$current_network_main_site = is_multisite() ? get_current_site() : null;
1909
+		$current_main_site_id = ! empty($current_network_main_site) ? $current_network_main_site->blog_id : 1;
1910
+		$option = 'ee_ueip_optin';
1911
+		//set correct table for query
1912
+		$table_name = $wpdb->get_blog_prefix($current_main_site_id) . 'options';
1913
+		//rather than getting blog option for the $current_main_site_id, we do a direct $wpdb query because
1914
+		//get_blog_option() does a switch_to_blog an that could cause infinite recursion because EE_Core_Config might be
1915
+		//re-constructed on the blog switch.  Note, we are still executing any core wp filters on this option retrieval.
1916
+		//this bit of code is basically a direct copy of get_option without any caching because we are NOT switched to the blog
1917
+		//for the purpose of caching.
1918
+		$pre = apply_filters('pre_option_' . $option, false, $option);
1919
+		if (false !== $pre) {
1920
+			EE_Core_Config::$ee_ueip_option = $pre;
1921
+			return EE_Core_Config::$ee_ueip_option;
1922
+		}
1923
+		$row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $table_name WHERE option_name = %s LIMIT 1",
1924
+			$option));
1925
+		if (is_object($row)) {
1926
+			$value = $row->option_value;
1927
+		} else { //option does not exist so use default.
1928
+			return apply_filters('default_option_' . $option, false, $option);
1929
+		}
1930
+		EE_Core_Config::$ee_ueip_option = apply_filters('option_' . $option, maybe_unserialize($value), $option);
1931
+		return EE_Core_Config::$ee_ueip_option;
1932
+	}
1933
+
1934
+
1935
+
1936
+	/**
1937
+	 * Currently used to ensure critical page urls have initial values saved to the db instead of any current set values
1938
+	 * on the object.
1939
+	 *
1940
+	 * @return array
1941
+	 */
1942
+	public function __sleep()
1943
+	{
1944
+		//reset all url properties
1945
+		$this->_reset_urls();
1946
+		//return what to save to db
1947
+		return array_keys(get_object_vars($this));
1948
+	}
2371 1949
 
1950
+}
2372 1951
 
2373 1952
 
2374
-    /**
2375
-     *    class constructor
2376
-     *
2377
-     * @access    public
2378
-     */
2379
-    public function __construct()
2380
-    {
2381
-        // set default registration settings
2382
-        $this->default_STS_ID = EEM_Registration::status_id_pending_payment;
2383
-        $this->email_validation_level = 'wp_default';
2384
-        $this->show_pending_payment_options = true;
2385
-        $this->skip_reg_confirmation = false;
2386
-        $this->reg_steps = array();
2387
-        $this->reg_confirmation_last = false;
2388
-        $this->use_bot_trap = true;
2389
-        $this->use_encryption = true;
2390
-        $this->use_captcha = false;
2391
-        $this->recaptcha_theme = 'light';
2392
-        $this->recaptcha_type = 'image';
2393
-        $this->recaptcha_language = 'en';
2394
-        $this->recaptcha_publickey = null;
2395
-        $this->recaptcha_privatekey = null;
2396
-        $this->recaptcha_width = 500;
2397
-        $this->default_maximum_number_of_tickets = 10;
2398
-    }
2399
-
2400
-
2401
-
2402
-    /**
2403
-     * This is called by the config loader and hooks are initialized AFTER the config has been populated.
2404
-     *
2405
-     * @since 4.8.8.rc.019
2406
-     */
2407
-    public function do_hooks()
2408
-    {
2409
-        add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_reg_status_on_EEM_Event'));
2410
-        add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_max_ticket_on_EEM_Event'));
2411
-    }
2412 1953
 
1954
+/**
1955
+ * Config class for storing info on the Organization
1956
+ */
1957
+class EE_Organization_Config extends EE_Config_Base
1958
+{
2413 1959
 
1960
+	/**
1961
+	 * @var string $name
1962
+	 * eg EE4.1
1963
+	 */
1964
+	public $name;
1965
+
1966
+	/**
1967
+	 * @var string $address_1
1968
+	 * eg 123 Onna Road
1969
+	 */
1970
+	public $address_1;
1971
+
1972
+	/**
1973
+	 * @var string $address_2
1974
+	 * eg PO Box 123
1975
+	 */
1976
+	public $address_2;
1977
+
1978
+	/**
1979
+	 * @var string $city
1980
+	 * eg Inna City
1981
+	 */
1982
+	public $city;
1983
+
1984
+	/**
1985
+	 * @var int $STA_ID
1986
+	 * eg 4
1987
+	 */
1988
+	public $STA_ID;
1989
+
1990
+	/**
1991
+	 * @var string $CNT_ISO
1992
+	 * eg US
1993
+	 */
1994
+	public $CNT_ISO;
1995
+
1996
+	/**
1997
+	 * @var string $zip
1998
+	 * eg 12345  or V1A 2B3
1999
+	 */
2000
+	public $zip;
2001
+
2002
+	/**
2003
+	 * @var string $email
2004
+	 * eg [email protected]
2005
+	 */
2006
+	public $email;
2007
+
2008
+
2009
+	/**
2010
+	 * @var string $phone
2011
+	 * eg. 111-111-1111
2012
+	 */
2013
+	public $phone;
2014
+
2015
+
2016
+	/**
2017
+	 * @var string $vat
2018
+	 * VAT/Tax Number
2019
+	 */
2020
+	public $vat;
2021
+
2022
+	/**
2023
+	 * @var string $logo_url
2024
+	 * eg http://www.somedomain.com/wp-content/uploads/kittehs.jpg
2025
+	 */
2026
+	public $logo_url;
2027
+
2028
+
2029
+	/**
2030
+	 * The below are all various properties for holding links to organization social network profiles
2031
+	 *
2032
+	 * @var string
2033
+	 */
2034
+	/**
2035
+	 * facebook (facebook.com/profile.name)
2036
+	 *
2037
+	 * @var string
2038
+	 */
2039
+	public $facebook;
2040
+
2041
+
2042
+	/**
2043
+	 * twitter (twitter.com/twitter_handle)
2044
+	 *
2045
+	 * @var string
2046
+	 */
2047
+	public $twitter;
2048
+
2049
+
2050
+	/**
2051
+	 * linkedin (linkedin.com/in/profile_name)
2052
+	 *
2053
+	 * @var string
2054
+	 */
2055
+	public $linkedin;
2056
+
2057
+
2058
+	/**
2059
+	 * pinterest (www.pinterest.com/profile_name)
2060
+	 *
2061
+	 * @var string
2062
+	 */
2063
+	public $pinterest;
2064
+
2065
+
2066
+	/**
2067
+	 * google+ (google.com/+profileName)
2068
+	 *
2069
+	 * @var string
2070
+	 */
2071
+	public $google;
2072
+
2073
+
2074
+	/**
2075
+	 * instagram (instagram.com/handle)
2076
+	 *
2077
+	 * @var string
2078
+	 */
2079
+	public $instagram;
2080
+
2081
+
2082
+
2083
+	/**
2084
+	 *    class constructor
2085
+	 *
2086
+	 * @access    public
2087
+	 */
2088
+	public function __construct()
2089
+	{
2090
+		// set default organization settings
2091
+		$this->name = get_bloginfo('name');
2092
+		$this->address_1 = '123 Onna Road';
2093
+		$this->address_2 = 'PO Box 123';
2094
+		$this->city = 'Inna City';
2095
+		$this->STA_ID = 4;
2096
+		$this->CNT_ISO = 'US';
2097
+		$this->zip = '12345';
2098
+		$this->email = get_bloginfo('admin_email');
2099
+		$this->phone = '';
2100
+		$this->vat = '123456789';
2101
+		$this->logo_url = '';
2102
+		$this->facebook = '';
2103
+		$this->twitter = '';
2104
+		$this->linkedin = '';
2105
+		$this->pinterest = '';
2106
+		$this->google = '';
2107
+		$this->instagram = '';
2108
+	}
2414 2109
 
2415
-    /**
2416
-     * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_default_registration_status
2417
-     * field matches the config setting for default_STS_ID.
2418
-     */
2419
-    public function set_default_reg_status_on_EEM_Event()
2420
-    {
2421
-        EEM_Event::set_default_reg_status($this->default_STS_ID);
2422
-    }
2110
+}
2423 2111
 
2424 2112
 
2425
-    /**
2426
-     * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_additional_limit field
2427
-     * for Events matches the config setting for default_maximum_number_of_tickets
2428
-     */
2429
-    public function set_default_max_ticket_on_EEM_Event()
2430
-    {
2431
-        EEM_Event::set_default_additional_limit($this->default_maximum_number_of_tickets);
2432
-    }
2433 2113
 
2114
+/**
2115
+ * Class for defining what's in the EE_Config relating to currency
2116
+ */
2117
+class EE_Currency_Config extends EE_Config_Base
2118
+{
2434 2119
 
2120
+	/**
2121
+	 * @var string $code
2122
+	 * eg 'US'
2123
+	 */
2124
+	public $code;
2125
+
2126
+	/**
2127
+	 * @var string $name
2128
+	 * eg 'Dollar'
2129
+	 */
2130
+	public $name;
2131
+
2132
+	/**
2133
+	 * plural name
2134
+	 *
2135
+	 * @var string $plural
2136
+	 * eg 'Dollars'
2137
+	 */
2138
+	public $plural;
2139
+
2140
+	/**
2141
+	 * currency sign
2142
+	 *
2143
+	 * @var string $sign
2144
+	 * eg '$'
2145
+	 */
2146
+	public $sign;
2147
+
2148
+	/**
2149
+	 * Whether the currency sign should come before the number or not
2150
+	 *
2151
+	 * @var boolean $sign_b4
2152
+	 */
2153
+	public $sign_b4;
2154
+
2155
+	/**
2156
+	 * How many digits should come after the decimal place
2157
+	 *
2158
+	 * @var int $dec_plc
2159
+	 */
2160
+	public $dec_plc;
2161
+
2162
+	/**
2163
+	 * Symbol to use for decimal mark
2164
+	 *
2165
+	 * @var string $dec_mrk
2166
+	 * eg '.'
2167
+	 */
2168
+	public $dec_mrk;
2169
+
2170
+	/**
2171
+	 * Symbol to use for thousands
2172
+	 *
2173
+	 * @var string $thsnds
2174
+	 * eg ','
2175
+	 */
2176
+	public $thsnds;
2177
+
2178
+
2179
+
2180
+	/**
2181
+	 *    class constructor
2182
+	 *
2183
+	 * @access    public
2184
+	 * @param string $CNT_ISO
2185
+	 * @throws \EE_Error
2186
+	 */
2187
+	public function __construct($CNT_ISO = '')
2188
+	{
2189
+		/** @var \EventEspresso\core\services\database\TableAnalysis $table_analysis */
2190
+		$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
2191
+		// get country code from organization settings or use default
2192
+		$ORG_CNT = isset(EE_Registry::instance()->CFG->organization)
2193
+				   && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
2194
+			? EE_Registry::instance()->CFG->organization->CNT_ISO
2195
+			: '';
2196
+		// but override if requested
2197
+		$CNT_ISO = ! empty($CNT_ISO) ? $CNT_ISO : $ORG_CNT;
2198
+		// 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
2199
+		if (
2200
+			! empty($CNT_ISO)
2201
+			&& EE_Maintenance_Mode::instance()->models_can_query()
2202
+			&& $table_analysis->tableExists(EE_Registry::instance()->load_model('Country')->table())
2203
+		) {
2204
+			// retrieve the country settings from the db, just in case they have been customized
2205
+			$country = EE_Registry::instance()->load_model('Country')->get_one_by_ID($CNT_ISO);
2206
+			if ($country instanceof EE_Country) {
2207
+				$this->code = $country->currency_code();    // currency code: USD, CAD, EUR
2208
+				$this->name = $country->currency_name_single();    // Dollar
2209
+				$this->plural = $country->currency_name_plural();    // Dollars
2210
+				$this->sign = $country->currency_sign();            // currency sign: $
2211
+				$this->sign_b4 = $country->currency_sign_before();        // currency sign before or after: $TRUE  or  FALSE$
2212
+				$this->dec_plc = $country->currency_decimal_places();    // decimal places: 2 = 0.00  3 = 0.000
2213
+				$this->dec_mrk = $country->currency_decimal_mark();    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2214
+				$this->thsnds = $country->currency_thousands_separator();    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2215
+			}
2216
+		}
2217
+		// fallback to hardcoded defaults, in case the above failed
2218
+		if (empty($this->code)) {
2219
+			// set default currency settings
2220
+			$this->code = 'USD';    // currency code: USD, CAD, EUR
2221
+			$this->name = __('Dollar', 'event_espresso');    // Dollar
2222
+			$this->plural = __('Dollars', 'event_espresso');    // Dollars
2223
+			$this->sign = '$';    // currency sign: $
2224
+			$this->sign_b4 = true;    // currency sign before or after: $TRUE  or  FALSE$
2225
+			$this->dec_plc = 2;    // decimal places: 2 = 0.00  3 = 0.000
2226
+			$this->dec_mrk = '.';    // decimal mark: (comma) ',' = 0,01   or (decimal) '.' = 0.01
2227
+			$this->thsnds = ',';    // thousands separator: (comma) ',' = 1,000   or (decimal) '.' = 1.000
2228
+		}
2229
+	}
2230
+}
2435 2231
 
2436
-    /**
2437
-     * @return boolean
2438
-     */
2439
-    public function track_invalid_checkout_access()
2440
-    {
2441
-        return $this->track_invalid_checkout_access;
2442
-    }
2443 2232
 
2444 2233
 
2234
+/**
2235
+ * Class for defining what's in the EE_Config relating to registration settings
2236
+ */
2237
+class EE_Registration_Config extends EE_Config_Base
2238
+{
2445 2239
 
2446
-    /**
2447
-     * @param boolean $track_invalid_checkout_access
2448
-     */
2449
-    public function set_track_invalid_checkout_access($track_invalid_checkout_access)
2450
-    {
2451
-        $this->track_invalid_checkout_access = filter_var(
2452
-            $track_invalid_checkout_access,
2453
-            FILTER_VALIDATE_BOOLEAN
2454
-        );
2455
-    }
2240
+	/**
2241
+	 * Default registration status
2242
+	 *
2243
+	 * @var string $default_STS_ID
2244
+	 * eg 'RPP'
2245
+	 */
2246
+	public $default_STS_ID;
2247
+
2248
+
2249
+	/**
2250
+	 * For new events, this will be the default value for the maximum number of tickets (equivalent to maximum number of
2251
+	 * registrations)
2252
+	 * @var int
2253
+	 */
2254
+	public $default_maximum_number_of_tickets;
2255
+
2256
+
2257
+	/**
2258
+	 * level of validation to apply to email addresses
2259
+	 *
2260
+	 * @var string $email_validation_level
2261
+	 * options: 'basic', 'wp_default', 'i18n', 'i18n_dns'
2262
+	 */
2263
+	public $email_validation_level;
2264
+
2265
+	/**
2266
+	 *    whether or not to show alternate payment options during the reg process if payment status is pending
2267
+	 *
2268
+	 * @var boolean $show_pending_payment_options
2269
+	 */
2270
+	public $show_pending_payment_options;
2271
+
2272
+	/**
2273
+	 * Whether to skip the registration confirmation page
2274
+	 *
2275
+	 * @var boolean $skip_reg_confirmation
2276
+	 */
2277
+	public $skip_reg_confirmation;
2278
+
2279
+	/**
2280
+	 * an array of SPCO reg steps where:
2281
+	 *        the keys denotes the reg step order
2282
+	 *        each element consists of an array with the following elements:
2283
+	 *            "file_path" => the file path to the EE_SPCO_Reg_Step class
2284
+	 *            "class_name" => the specific EE_SPCO_Reg_Step child class name
2285
+	 *            "slug" => the URL param used to trigger the reg step
2286
+	 *
2287
+	 * @var array $reg_steps
2288
+	 */
2289
+	public $reg_steps;
2290
+
2291
+	/**
2292
+	 * Whether registration confirmation should be the last page of SPCO
2293
+	 *
2294
+	 * @var boolean $reg_confirmation_last
2295
+	 */
2296
+	public $reg_confirmation_last;
2297
+
2298
+	/**
2299
+	 * Whether or not to enable the EE Bot Trap
2300
+	 *
2301
+	 * @var boolean $use_bot_trap
2302
+	 */
2303
+	public $use_bot_trap;
2304
+
2305
+	/**
2306
+	 * Whether or not to encrypt some data sent by the EE Bot Trap
2307
+	 *
2308
+	 * @var boolean $use_encryption
2309
+	 */
2310
+	public $use_encryption;
2311
+
2312
+	/**
2313
+	 * Whether or not to use ReCaptcha
2314
+	 *
2315
+	 * @var boolean $use_captcha
2316
+	 */
2317
+	public $use_captcha;
2318
+
2319
+	/**
2320
+	 * ReCaptcha Theme
2321
+	 *
2322
+	 * @var string $recaptcha_theme
2323
+	 *    options: 'dark    ', 'light'
2324
+	 */
2325
+	public $recaptcha_theme;
2326
+
2327
+	/**
2328
+	 * ReCaptcha Type
2329
+	 *
2330
+	 * @var string $recaptcha_type
2331
+	 *    options: 'audio', 'image'
2332
+	 */
2333
+	public $recaptcha_type;
2334
+
2335
+	/**
2336
+	 * ReCaptcha language
2337
+	 *
2338
+	 * @var string $recaptcha_language
2339
+	 * eg 'en'
2340
+	 */
2341
+	public $recaptcha_language;
2342
+
2343
+	/**
2344
+	 * ReCaptcha public key
2345
+	 *
2346
+	 * @var string $recaptcha_publickey
2347
+	 */
2348
+	public $recaptcha_publickey;
2349
+
2350
+	/**
2351
+	 * ReCaptcha private key
2352
+	 *
2353
+	 * @var string $recaptcha_privatekey
2354
+	 */
2355
+	public $recaptcha_privatekey;
2356
+
2357
+	/**
2358
+	 * ReCaptcha width
2359
+	 *
2360
+	 * @var int $recaptcha_width
2361
+	 * @deprecated
2362
+	 */
2363
+	public $recaptcha_width;
2364
+
2365
+	/**
2366
+	 * Whether or not invalid attempts to directly access the registration checkout page should be tracked.
2367
+	 *
2368
+	 * @var boolean $track_invalid_checkout_access
2369
+	 */
2370
+	protected $track_invalid_checkout_access = true;
2371
+
2372
+
2373
+
2374
+	/**
2375
+	 *    class constructor
2376
+	 *
2377
+	 * @access    public
2378
+	 */
2379
+	public function __construct()
2380
+	{
2381
+		// set default registration settings
2382
+		$this->default_STS_ID = EEM_Registration::status_id_pending_payment;
2383
+		$this->email_validation_level = 'wp_default';
2384
+		$this->show_pending_payment_options = true;
2385
+		$this->skip_reg_confirmation = false;
2386
+		$this->reg_steps = array();
2387
+		$this->reg_confirmation_last = false;
2388
+		$this->use_bot_trap = true;
2389
+		$this->use_encryption = true;
2390
+		$this->use_captcha = false;
2391
+		$this->recaptcha_theme = 'light';
2392
+		$this->recaptcha_type = 'image';
2393
+		$this->recaptcha_language = 'en';
2394
+		$this->recaptcha_publickey = null;
2395
+		$this->recaptcha_privatekey = null;
2396
+		$this->recaptcha_width = 500;
2397
+		$this->default_maximum_number_of_tickets = 10;
2398
+	}
2399
+
2400
+
2401
+
2402
+	/**
2403
+	 * This is called by the config loader and hooks are initialized AFTER the config has been populated.
2404
+	 *
2405
+	 * @since 4.8.8.rc.019
2406
+	 */
2407
+	public function do_hooks()
2408
+	{
2409
+		add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_reg_status_on_EEM_Event'));
2410
+		add_action('AHEE__EE_Config___load_core_config__end', array($this, 'set_default_max_ticket_on_EEM_Event'));
2411
+	}
2412
+
2413
+
2414
+
2415
+	/**
2416
+	 * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_default_registration_status
2417
+	 * field matches the config setting for default_STS_ID.
2418
+	 */
2419
+	public function set_default_reg_status_on_EEM_Event()
2420
+	{
2421
+		EEM_Event::set_default_reg_status($this->default_STS_ID);
2422
+	}
2423
+
2424
+
2425
+	/**
2426
+	 * Hooked into `AHEE__EE_Config___load_core_config__end` to ensure the default for the EVT_additional_limit field
2427
+	 * for Events matches the config setting for default_maximum_number_of_tickets
2428
+	 */
2429
+	public function set_default_max_ticket_on_EEM_Event()
2430
+	{
2431
+		EEM_Event::set_default_additional_limit($this->default_maximum_number_of_tickets);
2432
+	}
2433
+
2434
+
2435
+
2436
+	/**
2437
+	 * @return boolean
2438
+	 */
2439
+	public function track_invalid_checkout_access()
2440
+	{
2441
+		return $this->track_invalid_checkout_access;
2442
+	}
2443
+
2444
+
2445
+
2446
+	/**
2447
+	 * @param boolean $track_invalid_checkout_access
2448
+	 */
2449
+	public function set_track_invalid_checkout_access($track_invalid_checkout_access)
2450
+	{
2451
+		$this->track_invalid_checkout_access = filter_var(
2452
+			$track_invalid_checkout_access,
2453
+			FILTER_VALIDATE_BOOLEAN
2454
+		);
2455
+	}
2456 2456
 
2457 2457
 
2458 2458
 
@@ -2466,160 +2466,160 @@  discard block
 block discarded – undo
2466 2466
 class EE_Admin_Config extends EE_Config_Base
2467 2467
 {
2468 2468
 
2469
-    /**
2470
-     * @var boolean $use_personnel_manager
2471
-     */
2472
-    public $use_personnel_manager;
2473
-
2474
-    /**
2475
-     * @var boolean $use_dashboard_widget
2476
-     */
2477
-    public $use_dashboard_widget;
2478
-
2479
-    /**
2480
-     * @var int $events_in_dashboard
2481
-     */
2482
-    public $events_in_dashboard;
2483
-
2484
-    /**
2485
-     * @var boolean $use_event_timezones
2486
-     */
2487
-    public $use_event_timezones;
2488
-
2489
-    /**
2490
-     * @var boolean $use_full_logging
2491
-     */
2492
-    public $use_full_logging;
2493
-
2494
-    /**
2495
-     * @var string $log_file_name
2496
-     */
2497
-    public $log_file_name;
2498
-
2499
-    /**
2500
-     * @var string $debug_file_name
2501
-     */
2502
-    public $debug_file_name;
2503
-
2504
-    /**
2505
-     * @var boolean $use_remote_logging
2506
-     */
2507
-    public $use_remote_logging;
2508
-
2509
-    /**
2510
-     * @var string $remote_logging_url
2511
-     */
2512
-    public $remote_logging_url;
2513
-
2514
-    /**
2515
-     * @var boolean $show_reg_footer
2516
-     */
2517
-    public $show_reg_footer;
2518
-
2519
-    /**
2520
-     * @var string $affiliate_id
2521
-     */
2522
-    public $affiliate_id;
2523
-
2524
-    /**
2525
-     * help tours on or off (global setting)
2526
-     *
2527
-     * @var boolean
2528
-     */
2529
-    public $help_tour_activation;
2530
-
2531
-    /**
2532
-     * adds extra layer of encoding to session data to prevent serialization errors
2533
-     * but is incompatible with some server configuration errors
2534
-     * if you get "500 internal server errors" during registration, try turning this on
2535
-     * if you get PHP fatal errors regarding base 64 methods not defined, then turn this off
2536
-     *
2537
-     * @var boolean $encode_session_data
2538
-     */
2539
-    private $encode_session_data = false;
2540
-
2541
-
2542
-
2543
-    /**
2544
-     *    class constructor
2545
-     *
2546
-     * @access    public
2547
-     */
2548
-    public function __construct()
2549
-    {
2550
-        // set default general admin settings
2551
-        $this->use_personnel_manager = true;
2552
-        $this->use_dashboard_widget = true;
2553
-        $this->events_in_dashboard = 30;
2554
-        $this->use_event_timezones = false;
2555
-        $this->use_full_logging = false;
2556
-        $this->use_remote_logging = false;
2557
-        $this->remote_logging_url = null;
2558
-        $this->show_reg_footer = true;
2559
-        $this->affiliate_id = 'default';
2560
-        $this->help_tour_activation = true;
2561
-        $this->encode_session_data = false;
2562
-    }
2563
-
2564
-
2565
-
2566
-    /**
2567
-     * @param bool $reset
2568
-     * @return string
2569
-     */
2570
-    public function log_file_name($reset = false)
2571
-    {
2572
-        if (empty($this->log_file_name) || $reset) {
2573
-            $this->log_file_name = sanitize_key('espresso_log_' . md5(uniqid('', true))) . '.txt';
2574
-            EE_Config::instance()->update_espresso_config(false, false);
2575
-        }
2576
-        return $this->log_file_name;
2577
-    }
2578
-
2579
-
2580
-
2581
-    /**
2582
-     * @param bool $reset
2583
-     * @return string
2584
-     */
2585
-    public function debug_file_name($reset = false)
2586
-    {
2587
-        if (empty($this->debug_file_name) || $reset) {
2588
-            $this->debug_file_name = sanitize_key('espresso_debug_' . md5(uniqid('', true))) . '.txt';
2589
-            EE_Config::instance()->update_espresso_config(false, false);
2590
-        }
2591
-        return $this->debug_file_name;
2592
-    }
2593
-
2594
-
2595
-
2596
-    /**
2597
-     * @return string
2598
-     */
2599
-    public function affiliate_id()
2600
-    {
2601
-        return ! empty($this->affiliate_id) ? $this->affiliate_id : 'default';
2602
-    }
2603
-
2604
-
2605
-
2606
-    /**
2607
-     * @return boolean
2608
-     */
2609
-    public function encode_session_data()
2610
-    {
2611
-        return filter_var($this->encode_session_data, FILTER_VALIDATE_BOOLEAN);
2612
-    }
2613
-
2614
-
2615
-
2616
-    /**
2617
-     * @param boolean $encode_session_data
2618
-     */
2619
-    public function set_encode_session_data($encode_session_data)
2620
-    {
2621
-        $this->encode_session_data = filter_var($encode_session_data, FILTER_VALIDATE_BOOLEAN);
2622
-    }
2469
+	/**
2470
+	 * @var boolean $use_personnel_manager
2471
+	 */
2472
+	public $use_personnel_manager;
2473
+
2474
+	/**
2475
+	 * @var boolean $use_dashboard_widget
2476
+	 */
2477
+	public $use_dashboard_widget;
2478
+
2479
+	/**
2480
+	 * @var int $events_in_dashboard
2481
+	 */
2482
+	public $events_in_dashboard;
2483
+
2484
+	/**
2485
+	 * @var boolean $use_event_timezones
2486
+	 */
2487
+	public $use_event_timezones;
2488
+
2489
+	/**
2490
+	 * @var boolean $use_full_logging
2491
+	 */
2492
+	public $use_full_logging;
2493
+
2494
+	/**
2495
+	 * @var string $log_file_name
2496
+	 */
2497
+	public $log_file_name;
2498
+
2499
+	/**
2500
+	 * @var string $debug_file_name
2501
+	 */
2502
+	public $debug_file_name;
2503
+
2504
+	/**
2505
+	 * @var boolean $use_remote_logging
2506
+	 */
2507
+	public $use_remote_logging;
2508
+
2509
+	/**
2510
+	 * @var string $remote_logging_url
2511
+	 */
2512
+	public $remote_logging_url;
2513
+
2514
+	/**
2515
+	 * @var boolean $show_reg_footer
2516
+	 */
2517
+	public $show_reg_footer;
2518
+
2519
+	/**
2520
+	 * @var string $affiliate_id
2521
+	 */
2522
+	public $affiliate_id;
2523
+
2524
+	/**
2525
+	 * help tours on or off (global setting)
2526
+	 *
2527
+	 * @var boolean
2528
+	 */
2529
+	public $help_tour_activation;
2530
+
2531
+	/**
2532
+	 * adds extra layer of encoding to session data to prevent serialization errors
2533
+	 * but is incompatible with some server configuration errors
2534
+	 * if you get "500 internal server errors" during registration, try turning this on
2535
+	 * if you get PHP fatal errors regarding base 64 methods not defined, then turn this off
2536
+	 *
2537
+	 * @var boolean $encode_session_data
2538
+	 */
2539
+	private $encode_session_data = false;
2540
+
2541
+
2542
+
2543
+	/**
2544
+	 *    class constructor
2545
+	 *
2546
+	 * @access    public
2547
+	 */
2548
+	public function __construct()
2549
+	{
2550
+		// set default general admin settings
2551
+		$this->use_personnel_manager = true;
2552
+		$this->use_dashboard_widget = true;
2553
+		$this->events_in_dashboard = 30;
2554
+		$this->use_event_timezones = false;
2555
+		$this->use_full_logging = false;
2556
+		$this->use_remote_logging = false;
2557
+		$this->remote_logging_url = null;
2558
+		$this->show_reg_footer = true;
2559
+		$this->affiliate_id = 'default';
2560
+		$this->help_tour_activation = true;
2561
+		$this->encode_session_data = false;
2562
+	}
2563
+
2564
+
2565
+
2566
+	/**
2567
+	 * @param bool $reset
2568
+	 * @return string
2569
+	 */
2570
+	public function log_file_name($reset = false)
2571
+	{
2572
+		if (empty($this->log_file_name) || $reset) {
2573
+			$this->log_file_name = sanitize_key('espresso_log_' . md5(uniqid('', true))) . '.txt';
2574
+			EE_Config::instance()->update_espresso_config(false, false);
2575
+		}
2576
+		return $this->log_file_name;
2577
+	}
2578
+
2579
+
2580
+
2581
+	/**
2582
+	 * @param bool $reset
2583
+	 * @return string
2584
+	 */
2585
+	public function debug_file_name($reset = false)
2586
+	{
2587
+		if (empty($this->debug_file_name) || $reset) {
2588
+			$this->debug_file_name = sanitize_key('espresso_debug_' . md5(uniqid('', true))) . '.txt';
2589
+			EE_Config::instance()->update_espresso_config(false, false);
2590
+		}
2591
+		return $this->debug_file_name;
2592
+	}
2593
+
2594
+
2595
+
2596
+	/**
2597
+	 * @return string
2598
+	 */
2599
+	public function affiliate_id()
2600
+	{
2601
+		return ! empty($this->affiliate_id) ? $this->affiliate_id : 'default';
2602
+	}
2603
+
2604
+
2605
+
2606
+	/**
2607
+	 * @return boolean
2608
+	 */
2609
+	public function encode_session_data()
2610
+	{
2611
+		return filter_var($this->encode_session_data, FILTER_VALIDATE_BOOLEAN);
2612
+	}
2613
+
2614
+
2615
+
2616
+	/**
2617
+	 * @param boolean $encode_session_data
2618
+	 */
2619
+	public function set_encode_session_data($encode_session_data)
2620
+	{
2621
+		$this->encode_session_data = filter_var($encode_session_data, FILTER_VALIDATE_BOOLEAN);
2622
+	}
2623 2623
 
2624 2624
 
2625 2625
 
@@ -2633,71 +2633,71 @@  discard block
 block discarded – undo
2633 2633
 class EE_Template_Config extends EE_Config_Base
2634 2634
 {
2635 2635
 
2636
-    /**
2637
-     * @var boolean $enable_default_style
2638
-     */
2639
-    public $enable_default_style;
2640
-
2641
-    /**
2642
-     * @var string $custom_style_sheet
2643
-     */
2644
-    public $custom_style_sheet;
2645
-
2646
-    /**
2647
-     * @var boolean $display_address_in_regform
2648
-     */
2649
-    public $display_address_in_regform;
2650
-
2651
-    /**
2652
-     * @var int $display_description_on_multi_reg_page
2653
-     */
2654
-    public $display_description_on_multi_reg_page;
2655
-
2656
-    /**
2657
-     * @var boolean $use_custom_templates
2658
-     */
2659
-    public $use_custom_templates;
2660
-
2661
-    /**
2662
-     * @var string $current_espresso_theme
2663
-     */
2664
-    public $current_espresso_theme;
2665
-
2666
-    /**
2667
-     * @var EE_Ticket_Selector_Config $EED_Ticket_Selector
2668
-     */
2669
-    public $EED_Ticket_Selector;
2670
-
2671
-    /**
2672
-     * @var EE_Event_Single_Config $EED_Event_Single
2673
-     */
2674
-    public $EED_Event_Single;
2675
-
2676
-    /**
2677
-     * @var EE_Events_Archive_Config $EED_Events_Archive
2678
-     */
2679
-    public $EED_Events_Archive;
2680
-
2681
-
2682
-
2683
-    /**
2684
-     *    class constructor
2685
-     *
2686
-     * @access    public
2687
-     */
2688
-    public function __construct()
2689
-    {
2690
-        // set default template settings
2691
-        $this->enable_default_style = true;
2692
-        $this->custom_style_sheet = null;
2693
-        $this->display_address_in_regform = true;
2694
-        $this->display_description_on_multi_reg_page = false;
2695
-        $this->use_custom_templates = false;
2696
-        $this->current_espresso_theme = 'Espresso_Arabica_2014';
2697
-        $this->EED_Event_Single = null;
2698
-        $this->EED_Events_Archive = null;
2699
-        $this->EED_Ticket_Selector = null;
2700
-    }
2636
+	/**
2637
+	 * @var boolean $enable_default_style
2638
+	 */
2639
+	public $enable_default_style;
2640
+
2641
+	/**
2642
+	 * @var string $custom_style_sheet
2643
+	 */
2644
+	public $custom_style_sheet;
2645
+
2646
+	/**
2647
+	 * @var boolean $display_address_in_regform
2648
+	 */
2649
+	public $display_address_in_regform;
2650
+
2651
+	/**
2652
+	 * @var int $display_description_on_multi_reg_page
2653
+	 */
2654
+	public $display_description_on_multi_reg_page;
2655
+
2656
+	/**
2657
+	 * @var boolean $use_custom_templates
2658
+	 */
2659
+	public $use_custom_templates;
2660
+
2661
+	/**
2662
+	 * @var string $current_espresso_theme
2663
+	 */
2664
+	public $current_espresso_theme;
2665
+
2666
+	/**
2667
+	 * @var EE_Ticket_Selector_Config $EED_Ticket_Selector
2668
+	 */
2669
+	public $EED_Ticket_Selector;
2670
+
2671
+	/**
2672
+	 * @var EE_Event_Single_Config $EED_Event_Single
2673
+	 */
2674
+	public $EED_Event_Single;
2675
+
2676
+	/**
2677
+	 * @var EE_Events_Archive_Config $EED_Events_Archive
2678
+	 */
2679
+	public $EED_Events_Archive;
2680
+
2681
+
2682
+
2683
+	/**
2684
+	 *    class constructor
2685
+	 *
2686
+	 * @access    public
2687
+	 */
2688
+	public function __construct()
2689
+	{
2690
+		// set default template settings
2691
+		$this->enable_default_style = true;
2692
+		$this->custom_style_sheet = null;
2693
+		$this->display_address_in_regform = true;
2694
+		$this->display_description_on_multi_reg_page = false;
2695
+		$this->use_custom_templates = false;
2696
+		$this->current_espresso_theme = 'Espresso_Arabica_2014';
2697
+		$this->EED_Event_Single = null;
2698
+		$this->EED_Events_Archive = null;
2699
+		$this->EED_Ticket_Selector = null;
2700
+	}
2701 2701
 
2702 2702
 }
2703 2703
 
@@ -2709,115 +2709,115 @@  discard block
 block discarded – undo
2709 2709
 class EE_Map_Config extends EE_Config_Base
2710 2710
 {
2711 2711
 
2712
-    /**
2713
-     * @var boolean $use_google_maps
2714
-     */
2715
-    public $use_google_maps;
2716
-
2717
-    /**
2718
-     * @var string $api_key
2719
-     */
2720
-    public $google_map_api_key;
2721
-
2722
-    /**
2723
-     * @var int $event_details_map_width
2724
-     */
2725
-    public $event_details_map_width;
2726
-
2727
-    /**
2728
-     * @var int $event_details_map_height
2729
-     */
2730
-    public $event_details_map_height;
2731
-
2732
-    /**
2733
-     * @var int $event_details_map_zoom
2734
-     */
2735
-    public $event_details_map_zoom;
2736
-
2737
-    /**
2738
-     * @var boolean $event_details_display_nav
2739
-     */
2740
-    public $event_details_display_nav;
2741
-
2742
-    /**
2743
-     * @var boolean $event_details_nav_size
2744
-     */
2745
-    public $event_details_nav_size;
2746
-
2747
-    /**
2748
-     * @var string $event_details_control_type
2749
-     */
2750
-    public $event_details_control_type;
2751
-
2752
-    /**
2753
-     * @var string $event_details_map_align
2754
-     */
2755
-    public $event_details_map_align;
2756
-
2757
-    /**
2758
-     * @var int $event_list_map_width
2759
-     */
2760
-    public $event_list_map_width;
2761
-
2762
-    /**
2763
-     * @var int $event_list_map_height
2764
-     */
2765
-    public $event_list_map_height;
2766
-
2767
-    /**
2768
-     * @var int $event_list_map_zoom
2769
-     */
2770
-    public $event_list_map_zoom;
2771
-
2772
-    /**
2773
-     * @var boolean $event_list_display_nav
2774
-     */
2775
-    public $event_list_display_nav;
2776
-
2777
-    /**
2778
-     * @var boolean $event_list_nav_size
2779
-     */
2780
-    public $event_list_nav_size;
2781
-
2782
-    /**
2783
-     * @var string $event_list_control_type
2784
-     */
2785
-    public $event_list_control_type;
2786
-
2787
-    /**
2788
-     * @var string $event_list_map_align
2789
-     */
2790
-    public $event_list_map_align;
2791
-
2792
-
2793
-
2794
-    /**
2795
-     *    class constructor
2796
-     *
2797
-     * @access    public
2798
-     */
2799
-    public function __construct()
2800
-    {
2801
-        // set default map settings
2802
-        $this->use_google_maps = true;
2803
-        $this->google_map_api_key = '';
2804
-        // for event details pages (reg page)
2805
-        $this->event_details_map_width = 585;            // ee_map_width_single
2806
-        $this->event_details_map_height = 362;            // ee_map_height_single
2807
-        $this->event_details_map_zoom = 14;            // ee_map_zoom_single
2808
-        $this->event_details_display_nav = true;            // ee_map_nav_display_single
2809
-        $this->event_details_nav_size = false;            // ee_map_nav_size_single
2810
-        $this->event_details_control_type = 'default';        // ee_map_type_control_single
2811
-        $this->event_details_map_align = 'center';            // ee_map_align_single
2812
-        // for event list pages
2813
-        $this->event_list_map_width = 300;            // ee_map_width
2814
-        $this->event_list_map_height = 185;        // ee_map_height
2815
-        $this->event_list_map_zoom = 12;            // ee_map_zoom
2816
-        $this->event_list_display_nav = false;        // ee_map_nav_display
2817
-        $this->event_list_nav_size = true;            // ee_map_nav_size
2818
-        $this->event_list_control_type = 'dropdown';        // ee_map_type_control
2819
-        $this->event_list_map_align = 'center';            // ee_map_align
2820
-    }
2712
+	/**
2713
+	 * @var boolean $use_google_maps
2714
+	 */
2715
+	public $use_google_maps;
2716
+
2717
+	/**
2718
+	 * @var string $api_key
2719
+	 */
2720
+	public $google_map_api_key;
2721
+
2722
+	/**
2723
+	 * @var int $event_details_map_width
2724
+	 */
2725
+	public $event_details_map_width;
2726
+
2727
+	/**
2728
+	 * @var int $event_details_map_height
2729
+	 */
2730
+	public $event_details_map_height;
2731
+
2732
+	/**
2733
+	 * @var int $event_details_map_zoom
2734
+	 */
2735
+	public $event_details_map_zoom;
2736
+
2737
+	/**
2738
+	 * @var boolean $event_details_display_nav
2739
+	 */
2740
+	public $event_details_display_nav;
2741
+
2742
+	/**
2743
+	 * @var boolean $event_details_nav_size
2744
+	 */
2745
+	public $event_details_nav_size;
2746
+
2747
+	/**
2748
+	 * @var string $event_details_control_type
2749
+	 */
2750
+	public $event_details_control_type;
2751
+
2752
+	/**
2753
+	 * @var string $event_details_map_align
2754
+	 */
2755
+	public $event_details_map_align;
2756
+
2757
+	/**
2758
+	 * @var int $event_list_map_width
2759
+	 */
2760
+	public $event_list_map_width;
2761
+
2762
+	/**
2763
+	 * @var int $event_list_map_height
2764
+	 */
2765
+	public $event_list_map_height;
2766
+
2767
+	/**
2768
+	 * @var int $event_list_map_zoom
2769
+	 */
2770
+	public $event_list_map_zoom;
2771
+
2772
+	/**
2773
+	 * @var boolean $event_list_display_nav
2774
+	 */
2775
+	public $event_list_display_nav;
2776
+
2777
+	/**
2778
+	 * @var boolean $event_list_nav_size
2779
+	 */
2780
+	public $event_list_nav_size;
2781
+
2782
+	/**
2783
+	 * @var string $event_list_control_type
2784
+	 */
2785
+	public $event_list_control_type;
2786
+
2787
+	/**
2788
+	 * @var string $event_list_map_align
2789
+	 */
2790
+	public $event_list_map_align;
2791
+
2792
+
2793
+
2794
+	/**
2795
+	 *    class constructor
2796
+	 *
2797
+	 * @access    public
2798
+	 */
2799
+	public function __construct()
2800
+	{
2801
+		// set default map settings
2802
+		$this->use_google_maps = true;
2803
+		$this->google_map_api_key = '';
2804
+		// for event details pages (reg page)
2805
+		$this->event_details_map_width = 585;            // ee_map_width_single
2806
+		$this->event_details_map_height = 362;            // ee_map_height_single
2807
+		$this->event_details_map_zoom = 14;            // ee_map_zoom_single
2808
+		$this->event_details_display_nav = true;            // ee_map_nav_display_single
2809
+		$this->event_details_nav_size = false;            // ee_map_nav_size_single
2810
+		$this->event_details_control_type = 'default';        // ee_map_type_control_single
2811
+		$this->event_details_map_align = 'center';            // ee_map_align_single
2812
+		// for event list pages
2813
+		$this->event_list_map_width = 300;            // ee_map_width
2814
+		$this->event_list_map_height = 185;        // ee_map_height
2815
+		$this->event_list_map_zoom = 12;            // ee_map_zoom
2816
+		$this->event_list_display_nav = false;        // ee_map_nav_display
2817
+		$this->event_list_nav_size = true;            // ee_map_nav_size
2818
+		$this->event_list_control_type = 'dropdown';        // ee_map_type_control
2819
+		$this->event_list_map_align = 'center';            // ee_map_align
2820
+	}
2821 2821
 
2822 2822
 }
2823 2823
 
@@ -2829,47 +2829,47 @@  discard block
 block discarded – undo
2829 2829
 class EE_Events_Archive_Config extends EE_Config_Base
2830 2830
 {
2831 2831
 
2832
-    public $display_status_banner;
2832
+	public $display_status_banner;
2833 2833
 
2834
-    public $display_description;
2834
+	public $display_description;
2835 2835
 
2836
-    public $display_ticket_selector;
2836
+	public $display_ticket_selector;
2837 2837
 
2838
-    public $display_datetimes;
2838
+	public $display_datetimes;
2839 2839
 
2840
-    public $display_venue;
2840
+	public $display_venue;
2841 2841
 
2842
-    public $display_expired_events;
2842
+	public $display_expired_events;
2843 2843
 
2844
-    public $use_sortable_display_order;
2844
+	public $use_sortable_display_order;
2845 2845
 
2846
-    public $display_order_tickets;
2846
+	public $display_order_tickets;
2847 2847
 
2848
-    public $display_order_datetimes;
2848
+	public $display_order_datetimes;
2849 2849
 
2850
-    public $display_order_event;
2850
+	public $display_order_event;
2851 2851
 
2852
-    public $display_order_venue;
2852
+	public $display_order_venue;
2853 2853
 
2854 2854
 
2855 2855
 
2856
-    /**
2857
-     *    class constructor
2858
-     */
2859
-    public function __construct()
2860
-    {
2861
-        $this->display_status_banner = 0;
2862
-        $this->display_description = 1;
2863
-        $this->display_ticket_selector = 0;
2864
-        $this->display_datetimes = 1;
2865
-        $this->display_venue = 0;
2866
-        $this->display_expired_events = 0;
2867
-        $this->use_sortable_display_order = false;
2868
-        $this->display_order_tickets = 100;
2869
-        $this->display_order_datetimes = 110;
2870
-        $this->display_order_event = 120;
2871
-        $this->display_order_venue = 130;
2872
-    }
2856
+	/**
2857
+	 *    class constructor
2858
+	 */
2859
+	public function __construct()
2860
+	{
2861
+		$this->display_status_banner = 0;
2862
+		$this->display_description = 1;
2863
+		$this->display_ticket_selector = 0;
2864
+		$this->display_datetimes = 1;
2865
+		$this->display_venue = 0;
2866
+		$this->display_expired_events = 0;
2867
+		$this->use_sortable_display_order = false;
2868
+		$this->display_order_tickets = 100;
2869
+		$this->display_order_datetimes = 110;
2870
+		$this->display_order_event = 120;
2871
+		$this->display_order_venue = 130;
2872
+	}
2873 2873
 }
2874 2874
 
2875 2875
 
@@ -2880,35 +2880,35 @@  discard block
 block discarded – undo
2880 2880
 class EE_Event_Single_Config extends EE_Config_Base
2881 2881
 {
2882 2882
 
2883
-    public $display_status_banner_single;
2883
+	public $display_status_banner_single;
2884 2884
 
2885
-    public $display_venue;
2885
+	public $display_venue;
2886 2886
 
2887
-    public $use_sortable_display_order;
2887
+	public $use_sortable_display_order;
2888 2888
 
2889
-    public $display_order_tickets;
2889
+	public $display_order_tickets;
2890 2890
 
2891
-    public $display_order_datetimes;
2891
+	public $display_order_datetimes;
2892 2892
 
2893
-    public $display_order_event;
2893
+	public $display_order_event;
2894 2894
 
2895
-    public $display_order_venue;
2895
+	public $display_order_venue;
2896 2896
 
2897 2897
 
2898 2898
 
2899
-    /**
2900
-     *    class constructor
2901
-     */
2902
-    public function __construct()
2903
-    {
2904
-        $this->display_status_banner_single = 0;
2905
-        $this->display_venue = 1;
2906
-        $this->use_sortable_display_order = false;
2907
-        $this->display_order_tickets = 100;
2908
-        $this->display_order_datetimes = 110;
2909
-        $this->display_order_event = 120;
2910
-        $this->display_order_venue = 130;
2911
-    }
2899
+	/**
2900
+	 *    class constructor
2901
+	 */
2902
+	public function __construct()
2903
+	{
2904
+		$this->display_status_banner_single = 0;
2905
+		$this->display_venue = 1;
2906
+		$this->use_sortable_display_order = false;
2907
+		$this->display_order_tickets = 100;
2908
+		$this->display_order_datetimes = 110;
2909
+		$this->display_order_event = 120;
2910
+		$this->display_order_venue = 130;
2911
+	}
2912 2912
 }
2913 2913
 
2914 2914
 
@@ -2919,152 +2919,152 @@  discard block
 block discarded – undo
2919 2919
 class EE_Ticket_Selector_Config extends EE_Config_Base
2920 2920
 {
2921 2921
 
2922
-    /**
2923
-     * constant to indicate that a datetime selector should NEVER be shown for ticket selectors
2924
-     */
2925
-    const DO_NOT_SHOW_DATETIME_SELECTOR = 'no_datetime_selector';
2926
-
2927
-    /**
2928
-     * constant to indicate that a datetime selector should only be shown for ticket selectors
2929
-     * when the number of datetimes for the event matches the value set for $datetime_selector_threshold
2930
-     */
2931
-    const MAYBE_SHOW_DATETIME_SELECTOR = 'maybe_datetime_selector';
2932
-
2933
-    /**
2934
-     * @var boolean $show_ticket_sale_columns
2935
-     */
2936
-    public $show_ticket_sale_columns;
2937
-
2938
-    /**
2939
-     * @var boolean $show_ticket_details
2940
-     */
2941
-    public $show_ticket_details;
2942
-
2943
-    /**
2944
-     * @var boolean $show_expired_tickets
2945
-     */
2946
-    public $show_expired_tickets;
2947
-
2948
-    /**
2949
-     * whether or not to display a dropdown box populated with event datetimes
2950
-     * that toggles which tickets are displayed for a ticket selector.
2951
-     * uses one of the *_DATETIME_SELECTOR constants defined above
2952
-     *
2953
-     * @var string $show_datetime_selector
2954
-     */
2955
-    private $show_datetime_selector = 'no_datetime_selector';
2956
-
2957
-    /**
2958
-     * the number of datetimes an event has to have before conditionally displaying a datetime selector
2959
-     *
2960
-     * @var int $datetime_selector_threshold
2961
-     */
2962
-    private $datetime_selector_threshold = 3;
2963
-
2964
-
2965
-
2966
-    /**
2967
-     *    class constructor
2968
-     */
2969
-    public function __construct()
2970
-    {
2971
-        $this->show_ticket_sale_columns = true;
2972
-        $this->show_ticket_details = true;
2973
-        $this->show_expired_tickets = true;
2974
-        $this->show_datetime_selector = \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
2975
-        $this->datetime_selector_threshold = 3;
2976
-    }
2977
-
2978
-
2979
-
2980
-    /**
2981
-     * returns true if a datetime selector should be displayed
2982
-     *
2983
-     * @param array $datetimes
2984
-     * @return bool
2985
-     */
2986
-    public function showDatetimeSelector(array $datetimes)
2987
-    {
2988
-        // if the settings are NOT: don't show OR below threshold, THEN active = true
2989
-        return ! (
2990
-            $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
2991
-            || (
2992
-                $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR
2993
-                && count($datetimes) < $this->getDatetimeSelectorThreshold()
2994
-            )
2995
-        );
2996
-    }
2997
-
2998
-
2999
-
3000
-    /**
3001
-     * @return string
3002
-     */
3003
-    public function getShowDatetimeSelector()
3004
-    {
3005
-        return $this->show_datetime_selector;
3006
-    }
3007
-
3008
-
3009
-
3010
-    /**
3011
-     * @param bool $keys_only
3012
-     * @return array
3013
-     */
3014
-    public function getShowDatetimeSelectorOptions($keys_only = true)
3015
-    {
3016
-        return $keys_only
3017
-            ? array(
3018
-                \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
3019
-                \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR,
3020
-            )
3021
-            : array(
3022
-                \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR => esc_html__(
3023
-                    'Do not show date & time filter', 'event_espresso'
3024
-                ),
3025
-                \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR  => esc_html__(
3026
-                    'Maybe show date & time filter', 'event_espresso'
3027
-                ),
3028
-            );
3029
-    }
3030
-
3031
-
3032
-
3033
-    /**
3034
-     * @param string $show_datetime_selector
3035
-     */
3036
-    public function setShowDatetimeSelector($show_datetime_selector)
3037
-    {
3038
-        $this->show_datetime_selector = in_array(
3039
-            $show_datetime_selector,
3040
-            $this->getShowDatetimeSelectorOptions(),
3041
-            true
3042
-        )
3043
-            ? $show_datetime_selector
3044
-            : \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3045
-    }
3046
-
3047
-
3048
-
3049
-    /**
3050
-     * @return int
3051
-     */
3052
-    public function getDatetimeSelectorThreshold()
3053
-    {
3054
-        return $this->datetime_selector_threshold;
3055
-    }
3056
-
3057
-
3058
-
3059
-
3060
-    /**
3061
-     * @param int $datetime_selector_threshold
3062
-     */
3063
-    public function setDatetimeSelectorThreshold($datetime_selector_threshold)
3064
-    {
3065
-        $datetime_selector_threshold = absint($datetime_selector_threshold);
3066
-        $this->datetime_selector_threshold = $datetime_selector_threshold ? $datetime_selector_threshold : 3;
3067
-    }
2922
+	/**
2923
+	 * constant to indicate that a datetime selector should NEVER be shown for ticket selectors
2924
+	 */
2925
+	const DO_NOT_SHOW_DATETIME_SELECTOR = 'no_datetime_selector';
2926
+
2927
+	/**
2928
+	 * constant to indicate that a datetime selector should only be shown for ticket selectors
2929
+	 * when the number of datetimes for the event matches the value set for $datetime_selector_threshold
2930
+	 */
2931
+	const MAYBE_SHOW_DATETIME_SELECTOR = 'maybe_datetime_selector';
2932
+
2933
+	/**
2934
+	 * @var boolean $show_ticket_sale_columns
2935
+	 */
2936
+	public $show_ticket_sale_columns;
2937
+
2938
+	/**
2939
+	 * @var boolean $show_ticket_details
2940
+	 */
2941
+	public $show_ticket_details;
2942
+
2943
+	/**
2944
+	 * @var boolean $show_expired_tickets
2945
+	 */
2946
+	public $show_expired_tickets;
2947
+
2948
+	/**
2949
+	 * whether or not to display a dropdown box populated with event datetimes
2950
+	 * that toggles which tickets are displayed for a ticket selector.
2951
+	 * uses one of the *_DATETIME_SELECTOR constants defined above
2952
+	 *
2953
+	 * @var string $show_datetime_selector
2954
+	 */
2955
+	private $show_datetime_selector = 'no_datetime_selector';
2956
+
2957
+	/**
2958
+	 * the number of datetimes an event has to have before conditionally displaying a datetime selector
2959
+	 *
2960
+	 * @var int $datetime_selector_threshold
2961
+	 */
2962
+	private $datetime_selector_threshold = 3;
2963
+
2964
+
2965
+
2966
+	/**
2967
+	 *    class constructor
2968
+	 */
2969
+	public function __construct()
2970
+	{
2971
+		$this->show_ticket_sale_columns = true;
2972
+		$this->show_ticket_details = true;
2973
+		$this->show_expired_tickets = true;
2974
+		$this->show_datetime_selector = \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
2975
+		$this->datetime_selector_threshold = 3;
2976
+	}
2977
+
2978
+
2979
+
2980
+	/**
2981
+	 * returns true if a datetime selector should be displayed
2982
+	 *
2983
+	 * @param array $datetimes
2984
+	 * @return bool
2985
+	 */
2986
+	public function showDatetimeSelector(array $datetimes)
2987
+	{
2988
+		// if the settings are NOT: don't show OR below threshold, THEN active = true
2989
+		return ! (
2990
+			$this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
2991
+			|| (
2992
+				$this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR
2993
+				&& count($datetimes) < $this->getDatetimeSelectorThreshold()
2994
+			)
2995
+		);
2996
+	}
2997
+
2998
+
2999
+
3000
+	/**
3001
+	 * @return string
3002
+	 */
3003
+	public function getShowDatetimeSelector()
3004
+	{
3005
+		return $this->show_datetime_selector;
3006
+	}
3007
+
3008
+
3009
+
3010
+	/**
3011
+	 * @param bool $keys_only
3012
+	 * @return array
3013
+	 */
3014
+	public function getShowDatetimeSelectorOptions($keys_only = true)
3015
+	{
3016
+		return $keys_only
3017
+			? array(
3018
+				\EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
3019
+				\EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR,
3020
+			)
3021
+			: array(
3022
+				\EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR => esc_html__(
3023
+					'Do not show date & time filter', 'event_espresso'
3024
+				),
3025
+				\EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR  => esc_html__(
3026
+					'Maybe show date & time filter', 'event_espresso'
3027
+				),
3028
+			);
3029
+	}
3030
+
3031
+
3032
+
3033
+	/**
3034
+	 * @param string $show_datetime_selector
3035
+	 */
3036
+	public function setShowDatetimeSelector($show_datetime_selector)
3037
+	{
3038
+		$this->show_datetime_selector = in_array(
3039
+			$show_datetime_selector,
3040
+			$this->getShowDatetimeSelectorOptions(),
3041
+			true
3042
+		)
3043
+			? $show_datetime_selector
3044
+			: \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3045
+	}
3046
+
3047
+
3048
+
3049
+	/**
3050
+	 * @return int
3051
+	 */
3052
+	public function getDatetimeSelectorThreshold()
3053
+	{
3054
+		return $this->datetime_selector_threshold;
3055
+	}
3056
+
3057
+
3058
+
3059
+
3060
+	/**
3061
+	 * @param int $datetime_selector_threshold
3062
+	 */
3063
+	public function setDatetimeSelectorThreshold($datetime_selector_threshold)
3064
+	{
3065
+		$datetime_selector_threshold = absint($datetime_selector_threshold);
3066
+		$this->datetime_selector_threshold = $datetime_selector_threshold ? $datetime_selector_threshold : 3;
3067
+	}
3068 3068
 
3069 3069
 
3070 3070
 
@@ -3082,85 +3082,85 @@  discard block
 block discarded – undo
3082 3082
 class EE_Environment_Config extends EE_Config_Base
3083 3083
 {
3084 3084
 
3085
-    /**
3086
-     * Hold any php environment variables that we want to track.
3087
-     *
3088
-     * @var stdClass;
3089
-     */
3090
-    public $php;
3091
-
3092
-
3093
-
3094
-    /**
3095
-     *    constructor
3096
-     */
3097
-    public function __construct()
3098
-    {
3099
-        $this->php = new stdClass();
3100
-        $this->_set_php_values();
3101
-    }
3102
-
3103
-
3104
-
3105
-    /**
3106
-     * This sets the php environment variables.
3107
-     *
3108
-     * @since 4.4.0
3109
-     * @return void
3110
-     */
3111
-    protected function _set_php_values()
3112
-    {
3113
-        $this->php->max_input_vars = ini_get('max_input_vars');
3114
-        $this->php->version = phpversion();
3115
-    }
3116
-
3117
-
3118
-
3119
-    /**
3120
-     * helper method for determining whether input_count is
3121
-     * reaching the potential maximum the server can handle
3122
-     * according to max_input_vars
3123
-     *
3124
-     * @param int   $input_count the count of input vars.
3125
-     * @return array {
3126
-     *                           An array that represents whether available space and if no available space the error
3127
-     *                           message.
3128
-     * @type bool   $has_space   whether more inputs can be added.
3129
-     * @type string $msg         Any message to be displayed.
3130
-     *                           }
3131
-     */
3132
-    public function max_input_vars_limit_check($input_count = 0)
3133
-    {
3134
-        if (! empty($this->php->max_input_vars)
3135
-            && ($input_count >= $this->php->max_input_vars)
3136
-            && (PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9)
3137
-        ) {
3138
-            return sprintf(
3139
-                __(
3140
-                    '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.',
3141
-                    'event_espresso'
3142
-                ),
3143
-                '<br>',
3144
-                $input_count,
3145
-                $this->php->max_input_vars
3146
-            );
3147
-        } else {
3148
-            return '';
3149
-        }
3150
-    }
3151
-
3152
-
3153
-
3154
-    /**
3155
-     * The purpose of this method is just to force rechecking php values so if they've changed, they get updated.
3156
-     *
3157
-     * @since 4.4.1
3158
-     * @return void
3159
-     */
3160
-    public function recheck_values()
3161
-    {
3162
-        $this->_set_php_values();
3163
-    }
3085
+	/**
3086
+	 * Hold any php environment variables that we want to track.
3087
+	 *
3088
+	 * @var stdClass;
3089
+	 */
3090
+	public $php;
3091
+
3092
+
3093
+
3094
+	/**
3095
+	 *    constructor
3096
+	 */
3097
+	public function __construct()
3098
+	{
3099
+		$this->php = new stdClass();
3100
+		$this->_set_php_values();
3101
+	}
3102
+
3103
+
3104
+
3105
+	/**
3106
+	 * This sets the php environment variables.
3107
+	 *
3108
+	 * @since 4.4.0
3109
+	 * @return void
3110
+	 */
3111
+	protected function _set_php_values()
3112
+	{
3113
+		$this->php->max_input_vars = ini_get('max_input_vars');
3114
+		$this->php->version = phpversion();
3115
+	}
3116
+
3117
+
3118
+
3119
+	/**
3120
+	 * helper method for determining whether input_count is
3121
+	 * reaching the potential maximum the server can handle
3122
+	 * according to max_input_vars
3123
+	 *
3124
+	 * @param int   $input_count the count of input vars.
3125
+	 * @return array {
3126
+	 *                           An array that represents whether available space and if no available space the error
3127
+	 *                           message.
3128
+	 * @type bool   $has_space   whether more inputs can be added.
3129
+	 * @type string $msg         Any message to be displayed.
3130
+	 *                           }
3131
+	 */
3132
+	public function max_input_vars_limit_check($input_count = 0)
3133
+	{
3134
+		if (! empty($this->php->max_input_vars)
3135
+			&& ($input_count >= $this->php->max_input_vars)
3136
+			&& (PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9)
3137
+		) {
3138
+			return sprintf(
3139
+				__(
3140
+					'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.',
3141
+					'event_espresso'
3142
+				),
3143
+				'<br>',
3144
+				$input_count,
3145
+				$this->php->max_input_vars
3146
+			);
3147
+		} else {
3148
+			return '';
3149
+		}
3150
+	}
3151
+
3152
+
3153
+
3154
+	/**
3155
+	 * The purpose of this method is just to force rechecking php values so if they've changed, they get updated.
3156
+	 *
3157
+	 * @since 4.4.1
3158
+	 * @return void
3159
+	 */
3160
+	public function recheck_values()
3161
+	{
3162
+		$this->_set_php_values();
3163
+	}
3164 3164
 
3165 3165
 
3166 3166
 
@@ -3178,22 +3178,22 @@  discard block
 block discarded – undo
3178 3178
 class EE_Tax_Config extends EE_Config_Base
3179 3179
 {
3180 3180
 
3181
-    /*
3181
+	/*
3182 3182
      * flag to indicate whether or not to display ticket prices with the taxes included
3183 3183
      *
3184 3184
      * @var boolean $prices_displayed_including_taxes
3185 3185
      */
3186
-    public $prices_displayed_including_taxes;
3186
+	public $prices_displayed_including_taxes;
3187 3187
 
3188 3188
 
3189 3189
 
3190
-    /**
3191
-     *    class constructor
3192
-     */
3193
-    public function __construct()
3194
-    {
3195
-        $this->prices_displayed_including_taxes = true;
3196
-    }
3190
+	/**
3191
+	 *    class constructor
3192
+	 */
3193
+	public function __construct()
3194
+	{
3195
+		$this->prices_displayed_including_taxes = true;
3196
+	}
3197 3197
 }
3198 3198
 
3199 3199
 
@@ -3208,17 +3208,17 @@  discard block
 block discarded – undo
3208 3208
 class EE_Messages_Config extends EE_Config_Base
3209 3209
 {
3210 3210
 
3211
-    /**
3212
-     * This is an integer representing the deletion threshold in months for when old messages will get deleted.
3213
-     * A value of 0 represents never deleting.  Default is 0.
3214
-     *
3215
-     * @var integer
3216
-     */
3217
-    public $delete_threshold;
3218
-
3219
-    public function __construct() {
3220
-        $this->delete_threshold = 0;
3221
-    }
3211
+	/**
3212
+	 * This is an integer representing the deletion threshold in months for when old messages will get deleted.
3213
+	 * A value of 0 represents never deleting.  Default is 0.
3214
+	 *
3215
+	 * @var integer
3216
+	 */
3217
+	public $delete_threshold;
3218
+
3219
+	public function __construct() {
3220
+		$this->delete_threshold = 0;
3221
+	}
3222 3222
 }
3223 3223
 
3224 3224
 
@@ -3230,34 +3230,34 @@  discard block
 block discarded – undo
3230 3230
 class EE_Gateway_Config extends EE_Config_Base
3231 3231
 {
3232 3232
 
3233
-    /**
3234
-     * Array with keys that are payment gateways slugs, and values are arrays
3235
-     * with any config info the gateway wants to store
3236
-     *
3237
-     * @var array
3238
-     */
3239
-    public $payment_settings;
3240
-
3241
-    /**
3242
-     * Where keys are gateway slugs, and values are booleans indicating whether or not
3243
-     * the gateway is stored in the uploads directory
3244
-     *
3245
-     * @var array
3246
-     */
3247
-    public $active_gateways;
3248
-
3249
-
3250
-
3251
-    /**
3252
-     *    class constructor
3253
-     *
3254
-     * @deprecated
3255
-     */
3256
-    public function __construct()
3257
-    {
3258
-        $this->payment_settings = array();
3259
-        $this->active_gateways = array('Invoice' => false);
3260
-    }
3233
+	/**
3234
+	 * Array with keys that are payment gateways slugs, and values are arrays
3235
+	 * with any config info the gateway wants to store
3236
+	 *
3237
+	 * @var array
3238
+	 */
3239
+	public $payment_settings;
3240
+
3241
+	/**
3242
+	 * Where keys are gateway slugs, and values are booleans indicating whether or not
3243
+	 * the gateway is stored in the uploads directory
3244
+	 *
3245
+	 * @var array
3246
+	 */
3247
+	public $active_gateways;
3248
+
3249
+
3250
+
3251
+	/**
3252
+	 *    class constructor
3253
+	 *
3254
+	 * @deprecated
3255
+	 */
3256
+	public function __construct()
3257
+	{
3258
+		$this->payment_settings = array();
3259
+		$this->active_gateways = array('Invoice' => false);
3260
+	}
3261 3261
 }
3262 3262
 
3263 3263
 // End of file EE_Config.core.php
Please login to merge, or discard this patch.
core/EE_System.core.php 1 patch
Indentation   +1236 added lines, -1236 removed lines patch added patch discarded remove patch
@@ -21,1242 +21,1242 @@
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    /**
25
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
26
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
27
-     */
28
-    const req_type_normal = 0;
29
-
30
-    /**
31
-     * Indicates this is a brand new installation of EE so we should install
32
-     * tables and default data etc
33
-     */
34
-    const req_type_new_activation = 1;
35
-
36
-    /**
37
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
38
-     * and we just exited maintenance mode). We MUST check the database is setup properly
39
-     * and that default data is setup too
40
-     */
41
-    const req_type_reactivation = 2;
42
-
43
-    /**
44
-     * indicates that EE has been upgraded since its previous request.
45
-     * We may have data migration scripts to call and will want to trigger maintenance mode
46
-     */
47
-    const req_type_upgrade = 3;
48
-
49
-    /**
50
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
51
-     */
52
-    const req_type_downgrade = 4;
53
-
54
-    /**
55
-     * @deprecated since version 4.6.0.dev.006
56
-     * Now whenever a new_activation is detected the request type is still just
57
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
58
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
59
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
60
-     * (Specifically, when the migration manager indicates migrations are finished
61
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
62
-     */
63
-    const req_type_activation_but_not_installed = 5;
64
-
65
-    /**
66
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
67
-     */
68
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
69
-
70
-
71
-    /**
72
-     * @var EE_System $_instance
73
-     */
74
-    private static $_instance;
75
-
76
-    /**
77
-     * @var EE_Registry $registry
78
-     */
79
-    private $registry;
80
-
81
-    /**
82
-     * @var LoaderInterface $loader
83
-     */
84
-    private $loader;
85
-
86
-    /**
87
-     * @var EE_Capabilities $capabilities
88
-     */
89
-    private $capabilities;
90
-
91
-    /**
92
-     * @var EE_Request $request
93
-     */
94
-    private $request;
95
-
96
-    /**
97
-     * @var EE_Maintenance_Mode $maintenance_mode
98
-     */
99
-    private $maintenance_mode;
100
-
101
-    /**
102
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
103
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
104
-     *
105
-     * @var int $_req_type
106
-     */
107
-    private $_req_type;
108
-
109
-    /**
110
-     * Whether or not there was a non-micro version change in EE core version during this request
111
-     *
112
-     * @var boolean $_major_version_change
113
-     */
114
-    private $_major_version_change = false;
115
-
116
-
117
-
118
-    /**
119
-     * @singleton method used to instantiate class object
120
-     * @param EE_Registry|null         $registry
121
-     * @param LoaderInterface|null     $loader
122
-     * @param EE_Capabilities|null     $capabilities
123
-     * @param EE_Request|null          $request
124
-     * @param EE_Maintenance_Mode|null $maintenance_mode
125
-     * @return EE_System
126
-     */
127
-    public static function instance(
128
-        EE_Registry $registry = null,
129
-        LoaderInterface $loader = null,
130
-        EE_Capabilities $capabilities = null,
131
-        EE_Request $request = null,
132
-        EE_Maintenance_Mode $maintenance_mode = null
133
-    ) {
134
-        // check if class object is instantiated
135
-        if (! self::$_instance instanceof EE_System) {
136
-            self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137
-        }
138
-        return self::$_instance;
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * resets the instance and returns it
145
-     *
146
-     * @return EE_System
147
-     */
148
-    public static function reset()
149
-    {
150
-        self::$_instance->_req_type = null;
151
-        //make sure none of the old hooks are left hanging around
152
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
153
-        //we need to reset the migration manager in order for it to detect DMSs properly
154
-        EE_Data_Migration_Manager::reset();
155
-        self::instance()->detect_activations_or_upgrades();
156
-        self::instance()->perform_activations_upgrades_and_migrations();
157
-        return self::instance();
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     * sets hooks for running rest of system
164
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
165
-     * starting EE Addons from any other point may lead to problems
166
-     *
167
-     * @param EE_Registry         $registry
168
-     * @param LoaderInterface     $loader
169
-     * @param EE_Capabilities     $capabilities
170
-     * @param EE_Request          $request
171
-     * @param EE_Maintenance_Mode $maintenance_mode
172
-     */
173
-    private function __construct(
174
-        EE_Registry $registry,
175
-        LoaderInterface $loader,
176
-        EE_Capabilities $capabilities,
177
-        EE_Request $request,
178
-        EE_Maintenance_Mode $maintenance_mode
179
-    ) {
180
-        $this->registry = $registry;
181
-        $this->loader = $loader;
182
-        $this->capabilities = $capabilities;
183
-        $this->request = $request;
184
-        $this->maintenance_mode = $maintenance_mode;
185
-        do_action('AHEE__EE_System__construct__begin', $this);
186
-        add_action(
187
-            'AHEE__EE_Bootstrap__load_espresso_addons',
188
-            array($this, 'loadCapabilities'),
189
-            5
190
-        );
191
-        add_action(
192
-            'AHEE__EE_Bootstrap__load_espresso_addons',
193
-            array($this, 'loadCommandBus'),
194
-            7
195
-        );
196
-        add_action(
197
-            'AHEE__EE_Bootstrap__load_espresso_addons',
198
-            array($this, 'loadPluginApi'),
199
-            9
200
-        );
201
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
202
-        add_action(
203
-            'AHEE__EE_Bootstrap__load_espresso_addons',
204
-            array($this, 'load_espresso_addons')
205
-        );
206
-        // when an ee addon is activated, we want to call the core hook(s) again
207
-        // because the newly-activated addon didn't get a chance to run at all
208
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
209
-        // detect whether install or upgrade
210
-        add_action(
211
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
212
-            array($this, 'detect_activations_or_upgrades'),
213
-            3
214
-        );
215
-        // load EE_Config, EE_Textdomain, etc
216
-        add_action(
217
-            'AHEE__EE_Bootstrap__load_core_configuration',
218
-            array($this, 'load_core_configuration'),
219
-            5
220
-        );
221
-        // load EE_Config, EE_Textdomain, etc
222
-        add_action(
223
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
224
-            array($this, 'register_shortcodes_modules_and_widgets'),
225
-            7
226
-        );
227
-        // you wanna get going? I wanna get going... let's get going!
228
-        add_action(
229
-            'AHEE__EE_Bootstrap__brew_espresso',
230
-            array($this, 'brew_espresso'),
231
-            9
232
-        );
233
-        //other housekeeping
234
-        //exclude EE critical pages from wp_list_pages
235
-        add_filter(
236
-            'wp_list_pages_excludes',
237
-            array($this, 'remove_pages_from_wp_list_pages'),
238
-            10
239
-        );
240
-        // ALL EE Addons should use the following hook point to attach their initial setup too
241
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
242
-        do_action('AHEE__EE_System__construct__complete', $this);
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * load and setup EE_Capabilities
249
-     *
250
-     * @return void
251
-     * @throws EE_Error
252
-     */
253
-    public function loadCapabilities()
254
-    {
255
-        $this->loader->getShared('EE_Capabilities');
256
-        add_action(
257
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
258
-            function() {
259
-                LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
260
-            }
261
-        );
262
-    }
263
-
264
-
265
-
266
-    /**
267
-     * create and cache the CommandBus, and also add middleware
268
-     * The CapChecker middleware requires the use of EE_Capabilities
269
-     * which is why we need to load the CommandBus after Caps are set up
270
-     *
271
-     * @return void
272
-     * @throws EE_Error
273
-     */
274
-    public function loadCommandBus()
275
-    {
276
-        $this->loader->getShared(
277
-            'CommandBusInterface',
278
-            array(
279
-                null,
280
-                apply_filters(
281
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
-                    array(
283
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
284
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
285
-                    )
286
-                ),
287
-            )
288
-        );
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * @return void
295
-     * @throws EE_Error
296
-     */
297
-    public function loadPluginApi()
298
-    {
299
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
300
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
301
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
-    }
303
-
304
-
305
-    /**
306
-     * @param string $addon_name
307
-     * @param string $version_constant
308
-     * @param string $min_version_required
309
-     * @param string $load_callback
310
-     * @param string $plugin_file_constant
311
-     * @return void
312
-     */
313
-    private function deactivateIncompatibleAddon(
314
-        $addon_name,
315
-        $version_constant,
316
-        $min_version_required,
317
-        $load_callback,
318
-        $plugin_file_constant
319
-    ) {
320
-        if (! defined($version_constant)) {
321
-            return;
322
-        }
323
-        $addon_version = constant($version_constant);
324
-        if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
325
-            remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
326
-            if (! function_exists('deactivate_plugins')) {
327
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
328
-            }
329
-            deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
330
-            unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
331
-            EE_Error::add_error(
332
-                sprintf(
333
-                    esc_html__(
334
-                        'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
335
-                        'event_espresso'
336
-                    ),
337
-                    $addon_name,
338
-                    $min_version_required
339
-                ),
340
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
341
-            );
342
-            EE_Error::get_notices(false, true);
343
-        }
344
-    }
345
-
346
-
347
-    /**
348
-     * load_espresso_addons
349
-     * allow addons to load first so that they can set hooks for running DMS's, etc
350
-     * this is hooked into both:
351
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
352
-     *        which runs during the WP 'plugins_loaded' action at priority 5
353
-     *    and the WP 'activate_plugin' hook point
354
-     *
355
-     * @access public
356
-     * @return void
357
-     */
358
-    public function load_espresso_addons()
359
-    {
360
-        $this->deactivateIncompatibleAddon(
361
-            'Wait Lists',
362
-            'EE_WAIT_LISTS_VERSION',
363
-            '1.0.0.beta.074',
364
-            'load_espresso_wait_lists',
365
-            'EE_WAIT_LISTS_PLUGIN_FILE'
366
-        );
367
-        $this->deactivateIncompatibleAddon(
368
-            'Automated Upcoming Event Notifications',
369
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
370
-            '1.0.0.beta.091',
371
-            'load_espresso_automated_upcoming_event_notification',
372
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
373
-        );
374
-        do_action('AHEE__EE_System__load_espresso_addons');
375
-        //if the WP API basic auth plugin isn't already loaded, load it now.
376
-        //We want it for mobile apps. Just include the entire plugin
377
-        //also, don't load the basic auth when a plugin is getting activated, because
378
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
379
-        //and causes a fatal error
380
-        if (
381
-            ! (
382
-                isset($_GET['activate'])
383
-                && $_GET['activate'] === 'true'
384
-            )
385
-            && ! function_exists('json_basic_auth_handler')
386
-            && ! function_exists('json_basic_auth_error')
387
-            && ! (
388
-                isset($_GET['action'])
389
-                && in_array($_GET['action'], array('activate', 'activate-selected'), true)
390
-            )
391
-        ) {
392
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
393
-        }
394
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
395
-    }
396
-
397
-
398
-
399
-    /**
400
-     * detect_activations_or_upgrades
401
-     * Checks for activation or upgrade of core first;
402
-     * then also checks if any registered addons have been activated or upgraded
403
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
404
-     * which runs during the WP 'plugins_loaded' action at priority 3
405
-     *
406
-     * @access public
407
-     * @return void
408
-     */
409
-    public function detect_activations_or_upgrades()
410
-    {
411
-        //first off: let's make sure to handle core
412
-        $this->detect_if_activation_or_upgrade();
413
-        foreach ($this->registry->addons as $addon) {
414
-            if ($addon instanceof EE_Addon) {
415
-                //detect teh request type for that addon
416
-                $addon->detect_activation_or_upgrade();
417
-            }
418
-        }
419
-    }
420
-
421
-
422
-
423
-    /**
424
-     * detect_if_activation_or_upgrade
425
-     * Takes care of detecting whether this is a brand new install or code upgrade,
426
-     * and either setting up the DB or setting up maintenance mode etc.
427
-     *
428
-     * @access public
429
-     * @return void
430
-     */
431
-    public function detect_if_activation_or_upgrade()
432
-    {
433
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
434
-        // check if db has been updated, or if its a brand-new installation
435
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
436
-        $request_type = $this->detect_req_type($espresso_db_update);
437
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
438
-        switch ($request_type) {
439
-            case EE_System::req_type_new_activation:
440
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
441
-                $this->_handle_core_version_change($espresso_db_update);
442
-                break;
443
-            case EE_System::req_type_reactivation:
444
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
445
-                $this->_handle_core_version_change($espresso_db_update);
446
-                break;
447
-            case EE_System::req_type_upgrade:
448
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
449
-                //migrations may be required now that we've upgraded
450
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
451
-                $this->_handle_core_version_change($espresso_db_update);
452
-                //				echo "done upgrade";die;
453
-                break;
454
-            case EE_System::req_type_downgrade:
455
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
456
-                //its possible migrations are no longer required
457
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
458
-                $this->_handle_core_version_change($espresso_db_update);
459
-                break;
460
-            case EE_System::req_type_normal:
461
-            default:
462
-                //				$this->_maybe_redirect_to_ee_about();
463
-                break;
464
-        }
465
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
466
-    }
467
-
468
-
469
-
470
-    /**
471
-     * Updates the list of installed versions and sets hooks for
472
-     * initializing the database later during the request
473
-     *
474
-     * @param array $espresso_db_update
475
-     */
476
-    private function _handle_core_version_change($espresso_db_update)
477
-    {
478
-        $this->update_list_of_installed_versions($espresso_db_update);
479
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
480
-        add_action(
481
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
482
-            array($this, 'initialize_db_if_no_migrations_required')
483
-        );
484
-    }
485
-
486
-
487
-
488
-    /**
489
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
490
-     * information about what versions of EE have been installed and activated,
491
-     * NOT necessarily the state of the database
492
-     *
493
-     * @param mixed $espresso_db_update the value of the WordPress option.
494
-     *                                            If not supplied, fetches it from the options table
495
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
496
-     */
497
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
498
-    {
499
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
500
-        if (! $espresso_db_update) {
501
-            $espresso_db_update = get_option('espresso_db_update');
502
-        }
503
-        // check that option is an array
504
-        if (! is_array($espresso_db_update)) {
505
-            // if option is FALSE, then it never existed
506
-            if ($espresso_db_update === false) {
507
-                // make $espresso_db_update an array and save option with autoload OFF
508
-                $espresso_db_update = array();
509
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
510
-            } else {
511
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
512
-                $espresso_db_update = array($espresso_db_update => array());
513
-                update_option('espresso_db_update', $espresso_db_update);
514
-            }
515
-        } else {
516
-            $corrected_db_update = array();
517
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
518
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
519
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
520
-                    //the key is an int, and the value IS NOT an array
521
-                    //so it must be numerically-indexed, where values are versions installed...
522
-                    //fix it!
523
-                    $version_string = $should_be_array;
524
-                    $corrected_db_update[$version_string] = array('unknown-date');
525
-                } else {
526
-                    //ok it checks out
527
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
528
-                }
529
-            }
530
-            $espresso_db_update = $corrected_db_update;
531
-            update_option('espresso_db_update', $espresso_db_update);
532
-        }
533
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
534
-        return $espresso_db_update;
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Does the traditional work of setting up the plugin's database and adding default data.
541
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
542
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
543
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
544
-     * so that it will be done when migrations are finished
545
-     *
546
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
547
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
548
-     *                                       This is a resource-intensive job
549
-     *                                       so we prefer to only do it when necessary
550
-     * @return void
551
-     * @throws EE_Error
552
-     */
553
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
554
-    {
555
-        $request_type = $this->detect_req_type();
556
-        //only initialize system if we're not in maintenance mode.
557
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
558
-            update_option('ee_flush_rewrite_rules', true);
559
-            if ($verify_schema) {
560
-                EEH_Activation::initialize_db_and_folders();
561
-            }
562
-            EEH_Activation::initialize_db_content();
563
-            EEH_Activation::system_initialization();
564
-            if ($initialize_addons_too) {
565
-                $this->initialize_addons();
566
-            }
567
-        } else {
568
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
569
-        }
570
-        if ($request_type === EE_System::req_type_new_activation
571
-            || $request_type === EE_System::req_type_reactivation
572
-            || (
573
-                $request_type === EE_System::req_type_upgrade
574
-                && $this->is_major_version_change()
575
-            )
576
-        ) {
577
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
578
-        }
579
-    }
580
-
581
-
582
-
583
-    /**
584
-     * Initializes the db for all registered addons
585
-     *
586
-     * @throws EE_Error
587
-     */
588
-    public function initialize_addons()
589
-    {
590
-        //foreach registered addon, make sure its db is up-to-date too
591
-        foreach ($this->registry->addons as $addon) {
592
-            if ($addon instanceof EE_Addon) {
593
-                $addon->initialize_db_if_no_migrations_required();
594
-            }
595
-        }
596
-    }
597
-
598
-
599
-
600
-    /**
601
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
602
-     *
603
-     * @param    array  $version_history
604
-     * @param    string $current_version_to_add version to be added to the version history
605
-     * @return    boolean success as to whether or not this option was changed
606
-     */
607
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
608
-    {
609
-        if (! $version_history) {
610
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
611
-        }
612
-        if ($current_version_to_add === null) {
613
-            $current_version_to_add = espresso_version();
614
-        }
615
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
616
-        // re-save
617
-        return update_option('espresso_db_update', $version_history);
618
-    }
619
-
620
-
621
-
622
-    /**
623
-     * Detects if the current version indicated in the has existed in the list of
624
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
625
-     *
626
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
627
-     *                                  If not supplied, fetches it from the options table.
628
-     *                                  Also, caches its result so later parts of the code can also know whether
629
-     *                                  there's been an update or not. This way we can add the current version to
630
-     *                                  espresso_db_update, but still know if this is a new install or not
631
-     * @return int one of the constants on EE_System::req_type_
632
-     */
633
-    public function detect_req_type($espresso_db_update = null)
634
-    {
635
-        if ($this->_req_type === null) {
636
-            $espresso_db_update = ! empty($espresso_db_update)
637
-                ? $espresso_db_update
638
-                : $this->fix_espresso_db_upgrade_option();
639
-            $this->_req_type = EE_System::detect_req_type_given_activation_history(
640
-                $espresso_db_update,
641
-                'ee_espresso_activation', espresso_version()
642
-            );
643
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
644
-        }
645
-        return $this->_req_type;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     * Returns whether or not there was a non-micro version change (ie, change in either
652
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
653
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
654
-     *
655
-     * @param $activation_history
656
-     * @return bool
657
-     */
658
-    private function _detect_major_version_change($activation_history)
659
-    {
660
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
661
-        $previous_version_parts = explode('.', $previous_version);
662
-        $current_version_parts = explode('.', espresso_version());
663
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
664
-               && ($previous_version_parts[0] !== $current_version_parts[0]
665
-                   || $previous_version_parts[1] !== $current_version_parts[1]
666
-               );
667
-    }
668
-
669
-
670
-
671
-    /**
672
-     * Returns true if either the major or minor version of EE changed during this request.
673
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
674
-     *
675
-     * @return bool
676
-     */
677
-    public function is_major_version_change()
678
-    {
679
-        return $this->_major_version_change;
680
-    }
681
-
682
-
683
-
684
-    /**
685
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
686
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
687
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
688
-     * just activated to (for core that will always be espresso_version())
689
-     *
690
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
691
-     *                                                 ee plugin. for core that's 'espresso_db_update'
692
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
693
-     *                                                 indicate that this plugin was just activated
694
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
695
-     *                                                 espresso_version())
696
-     * @return int one of the constants on EE_System::req_type_*
697
-     */
698
-    public static function detect_req_type_given_activation_history(
699
-        $activation_history_for_addon,
700
-        $activation_indicator_option_name,
701
-        $version_to_upgrade_to
702
-    ) {
703
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
704
-        if ($activation_history_for_addon) {
705
-            //it exists, so this isn't a completely new install
706
-            //check if this version already in that list of previously installed versions
707
-            if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
708
-                //it a version we haven't seen before
709
-                if ($version_is_higher === 1) {
710
-                    $req_type = EE_System::req_type_upgrade;
711
-                } else {
712
-                    $req_type = EE_System::req_type_downgrade;
713
-                }
714
-                delete_option($activation_indicator_option_name);
715
-            } else {
716
-                // its not an update. maybe a reactivation?
717
-                if (get_option($activation_indicator_option_name, false)) {
718
-                    if ($version_is_higher === -1) {
719
-                        $req_type = EE_System::req_type_downgrade;
720
-                    } else if ($version_is_higher === 0) {
721
-                        //we've seen this version before, but it's an activation. must be a reactivation
722
-                        $req_type = EE_System::req_type_reactivation;
723
-                    } else {//$version_is_higher === 1
724
-                        $req_type = EE_System::req_type_upgrade;
725
-                    }
726
-                    delete_option($activation_indicator_option_name);
727
-                } else {
728
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
729
-                    if ($version_is_higher === -1) {
730
-                        $req_type = EE_System::req_type_downgrade;
731
-                    } else if ($version_is_higher === 0) {
732
-                        //we've seen this version before and it's not an activation. its normal request
733
-                        $req_type = EE_System::req_type_normal;
734
-                    } else {//$version_is_higher === 1
735
-                        $req_type = EE_System::req_type_upgrade;
736
-                    }
737
-                }
738
-            }
739
-        } else {
740
-            //brand new install
741
-            $req_type = EE_System::req_type_new_activation;
742
-            delete_option($activation_indicator_option_name);
743
-        }
744
-        return $req_type;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
751
-     * the $activation_history_for_addon
752
-     *
753
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
754
-     *                                             sometimes containing 'unknown-date'
755
-     * @param string $version_to_upgrade_to        (current version)
756
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
757
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
758
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
759
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
760
-     */
761
-    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
762
-    {
763
-        //find the most recently-activated version
764
-        $most_recently_active_version =
765
-            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
766
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
767
-    }
768
-
769
-
770
-
771
-    /**
772
-     * Gets the most recently active version listed in the activation history,
773
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
774
-     *
775
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
776
-     *                                   sometimes containing 'unknown-date'
777
-     * @return string
778
-     */
779
-    private static function _get_most_recently_active_version_from_activation_history($activation_history)
780
-    {
781
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
782
-        $most_recently_active_version = '0.0.0.dev.000';
783
-        if (is_array($activation_history)) {
784
-            foreach ($activation_history as $version => $times_activated) {
785
-                //check there is a record of when this version was activated. Otherwise,
786
-                //mark it as unknown
787
-                if (! $times_activated) {
788
-                    $times_activated = array('unknown-date');
789
-                }
790
-                if (is_string($times_activated)) {
791
-                    $times_activated = array($times_activated);
792
-                }
793
-                foreach ($times_activated as $an_activation) {
794
-                    if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
795
-                        $most_recently_active_version = $version;
796
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
797
-                            ? '1970-01-01 00:00:00'
798
-                            : $an_activation;
799
-                    }
800
-                }
801
-            }
802
-        }
803
-        return $most_recently_active_version;
804
-    }
805
-
806
-
807
-
808
-    /**
809
-     * This redirects to the about EE page after activation
810
-     *
811
-     * @return void
812
-     */
813
-    public function redirect_to_about_ee()
814
-    {
815
-        $notices = EE_Error::get_notices(false);
816
-        //if current user is an admin and it's not an ajax or rest request
817
-        if (
818
-            ! (defined('DOING_AJAX') && DOING_AJAX)
819
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
820
-            && ! isset($notices['errors'])
821
-            && apply_filters(
822
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
823
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
824
-            )
825
-        ) {
826
-            $query_params = array('page' => 'espresso_about');
827
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
828
-                $query_params['new_activation'] = true;
829
-            }
830
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
831
-                $query_params['reactivation'] = true;
832
-            }
833
-            $url = add_query_arg($query_params, admin_url('admin.php'));
834
-            wp_safe_redirect($url);
835
-            exit();
836
-        }
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * load_core_configuration
843
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
844
-     * which runs during the WP 'plugins_loaded' action at priority 5
845
-     *
846
-     * @return void
847
-     * @throws ReflectionException
848
-     */
849
-    public function load_core_configuration()
850
-    {
851
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
852
-        $this->loader->getShared('EE_Load_Textdomain');
853
-        //load textdomain
854
-        EE_Load_Textdomain::load_textdomain();
855
-        // load and setup EE_Config and EE_Network_Config
856
-        $config = $this->loader->getShared('EE_Config');
857
-        $this->loader->getShared('EE_Network_Config');
858
-        // setup autoloaders
859
-        // enable logging?
860
-        if ($config->admin->use_full_logging) {
861
-            $this->loader->getShared('EE_Log');
862
-        }
863
-        // check for activation errors
864
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
865
-        if ($activation_errors) {
866
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
867
-            update_option('ee_plugin_activation_errors', false);
868
-        }
869
-        // get model names
870
-        $this->_parse_model_names();
871
-        //load caf stuff a chance to play during the activation process too.
872
-        $this->_maybe_brew_regular();
873
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
874
-    }
875
-
876
-
877
-
878
-    /**
879
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
880
-     *
881
-     * @return void
882
-     * @throws ReflectionException
883
-     */
884
-    private function _parse_model_names()
885
-    {
886
-        //get all the files in the EE_MODELS folder that end in .model.php
887
-        $models = glob(EE_MODELS . '*.model.php');
888
-        $model_names = array();
889
-        $non_abstract_db_models = array();
890
-        foreach ($models as $model) {
891
-            // get model classname
892
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
893
-            $short_name = str_replace('EEM_', '', $classname);
894
-            $reflectionClass = new ReflectionClass($classname);
895
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
-                $non_abstract_db_models[$short_name] = $classname;
897
-            }
898
-            $model_names[$short_name] = $classname;
899
-        }
900
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901
-        $this->registry->non_abstract_db_models = apply_filters(
902
-            'FHEE__EE_System__parse_implemented_model_names',
903
-            $non_abstract_db_models
904
-        );
905
-    }
906
-
907
-
908
-
909
-    /**
910
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
911
-     * that need to be setup before our EE_System launches.
912
-     *
913
-     * @return void
914
-     */
915
-    private function _maybe_brew_regular()
916
-    {
917
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
918
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
919
-        }
920
-    }
921
-
922
-
923
-
924
-    /**
925
-     * register_shortcodes_modules_and_widgets
926
-     * generate lists of shortcodes and modules, then verify paths and classes
927
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
928
-     * which runs during the WP 'plugins_loaded' action at priority 7
929
-     *
930
-     * @access public
931
-     * @return void
932
-     * @throws Exception
933
-     */
934
-    public function register_shortcodes_modules_and_widgets()
935
-    {
936
-        try {
937
-            // load, register, and add shortcodes the new way
938
-            $this->loader->getShared(
939
-                'EventEspresso\core\services\shortcodes\ShortcodesManager',
940
-                array(
941
-                    // and the old way, but we'll put it under control of the new system
942
-                    EE_Config::getLegacyShortcodesManager()
943
-                )
944
-            );
945
-        } catch (Exception $exception) {
946
-            new ExceptionStackTraceDisplay($exception);
947
-        }
948
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
949
-        // check for addons using old hook point
950
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
951
-            $this->_incompatible_addon_error();
952
-        }
953
-    }
954
-
955
-
956
-
957
-    /**
958
-     * _incompatible_addon_error
959
-     *
960
-     * @access public
961
-     * @return void
962
-     */
963
-    private function _incompatible_addon_error()
964
-    {
965
-        // get array of classes hooking into here
966
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
967
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
968
-        );
969
-        if (! empty($class_names)) {
970
-            $msg = __(
971
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
972
-                'event_espresso'
973
-            );
974
-            $msg .= '<ul>';
975
-            foreach ($class_names as $class_name) {
976
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
977
-                        array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
978
-                        $class_name
979
-                    ) . '</b></li>';
980
-            }
981
-            $msg .= '</ul>';
982
-            $msg .= __(
983
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
984
-                'event_espresso'
985
-            );
986
-            // save list of incompatible addons to wp-options for later use
987
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
988
-            if (is_admin()) {
989
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
990
-            }
991
-        }
992
-    }
993
-
994
-
995
-
996
-    /**
997
-     * brew_espresso
998
-     * begins the process of setting hooks for initializing EE in the correct order
999
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1000
-     * which runs during the WP 'plugins_loaded' action at priority 9
1001
-     *
1002
-     * @return void
1003
-     */
1004
-    public function brew_espresso()
1005
-    {
1006
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
1007
-        // load some final core systems
1008
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
1009
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1010
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
1011
-        add_action('init', array($this, 'load_controllers'), 7);
1012
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
1013
-        add_action('init', array($this, 'initialize'), 10);
1014
-        add_action('init', array($this, 'initialize_last'), 100);
1015
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1016
-            // pew pew pew
1017
-            $this->loader->getShared('EE_PUE');
1018
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1019
-        }
1020
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
1021
-    }
1022
-
1023
-
1024
-
1025
-    /**
1026
-     *    set_hooks_for_core
1027
-     *
1028
-     * @access public
1029
-     * @return    void
1030
-     * @throws EE_Error
1031
-     */
1032
-    public function set_hooks_for_core()
1033
-    {
1034
-        $this->_deactivate_incompatible_addons();
1035
-        do_action('AHEE__EE_System__set_hooks_for_core');
1036
-        //caps need to be initialized on every request so that capability maps are set.
1037
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1038
-        $this->registry->CAP->init_caps();
1039
-    }
1040
-
1041
-
1042
-
1043
-    /**
1044
-     * Using the information gathered in EE_System::_incompatible_addon_error,
1045
-     * deactivates any addons considered incompatible with the current version of EE
1046
-     */
1047
-    private function _deactivate_incompatible_addons()
1048
-    {
1049
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
1050
-        if (! empty($incompatible_addons)) {
1051
-            $active_plugins = get_option('active_plugins', array());
1052
-            foreach ($active_plugins as $active_plugin) {
1053
-                foreach ($incompatible_addons as $incompatible_addon) {
1054
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1055
-                        unset($_GET['activate']);
1056
-                        espresso_deactivate_plugin($active_plugin);
1057
-                    }
1058
-                }
1059
-            }
1060
-        }
1061
-    }
1062
-
1063
-
1064
-
1065
-    /**
1066
-     *    perform_activations_upgrades_and_migrations
1067
-     *
1068
-     * @access public
1069
-     * @return    void
1070
-     */
1071
-    public function perform_activations_upgrades_and_migrations()
1072
-    {
1073
-        //first check if we had previously attempted to setup EE's directories but failed
1074
-        if (EEH_Activation::upload_directories_incomplete()) {
1075
-            EEH_Activation::create_upload_directories();
1076
-        }
1077
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1078
-    }
1079
-
1080
-
1081
-
1082
-    /**
1083
-     *    load_CPTs_and_session
1084
-     *
1085
-     * @access public
1086
-     * @return    void
1087
-     */
1088
-    public function load_CPTs_and_session()
1089
-    {
1090
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1091
-        // register Custom Post Types
1092
-        $this->loader->getShared('EE_Register_CPTs');
1093
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * load_controllers
1100
-     * this is the best place to load any additional controllers that needs access to EE core.
1101
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1102
-     * time
1103
-     *
1104
-     * @access public
1105
-     * @return void
1106
-     */
1107
-    public function load_controllers()
1108
-    {
1109
-        do_action('AHEE__EE_System__load_controllers__start');
1110
-        // let's get it started
1111
-        if (! is_admin() && ! $this->maintenance_mode->level()) {
1112
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1113
-            $this->loader->getShared('EE_Front_Controller');
1114
-        } else if (! EE_FRONT_AJAX) {
1115
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1116
-            $this->loader->getShared('EE_Admin');
1117
-        }
1118
-        do_action('AHEE__EE_System__load_controllers__complete');
1119
-    }
1120
-
1121
-
1122
-
1123
-    /**
1124
-     * core_loaded_and_ready
1125
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1126
-     *
1127
-     * @access public
1128
-     * @return void
1129
-     */
1130
-    public function core_loaded_and_ready()
1131
-    {
1132
-        $this->loader->getShared('EE_Session');
1133
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1134
-        // load_espresso_template_tags
1135
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1136
-            require_once(EE_PUBLIC . 'template_tags.php');
1137
-        }
1138
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1139
-        $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1140
-    }
1141
-
1142
-
1143
-
1144
-    /**
1145
-     * initialize
1146
-     * this is the best place to begin initializing client code
1147
-     *
1148
-     * @access public
1149
-     * @return void
1150
-     */
1151
-    public function initialize()
1152
-    {
1153
-        do_action('AHEE__EE_System__initialize');
1154
-    }
1155
-
1156
-
1157
-
1158
-    /**
1159
-     * initialize_last
1160
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1161
-     * initialize has done so
1162
-     *
1163
-     * @access public
1164
-     * @return void
1165
-     */
1166
-    public function initialize_last()
1167
-    {
1168
-        do_action('AHEE__EE_System__initialize_last');
1169
-        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * @return void
1176
-     * @throws EE_Error
1177
-     */
1178
-    public function addEspressoToolbar()
1179
-    {
1180
-        $this->loader->getShared(
1181
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1182
-            array($this->registry->CAP)
1183
-        );
1184
-    }
1185
-
1186
-
1187
-
1188
-    /**
1189
-     * do_not_cache
1190
-     * sets no cache headers and defines no cache constants for WP plugins
1191
-     *
1192
-     * @access public
1193
-     * @return void
1194
-     */
1195
-    public static function do_not_cache()
1196
-    {
1197
-        // set no cache constants
1198
-        if (! defined('DONOTCACHEPAGE')) {
1199
-            define('DONOTCACHEPAGE', true);
1200
-        }
1201
-        if (! defined('DONOTCACHCEOBJECT')) {
1202
-            define('DONOTCACHCEOBJECT', true);
1203
-        }
1204
-        if (! defined('DONOTCACHEDB')) {
1205
-            define('DONOTCACHEDB', true);
1206
-        }
1207
-        // add no cache headers
1208
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1209
-        // plus a little extra for nginx and Google Chrome
1210
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1211
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1212
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1213
-    }
1214
-
1215
-
1216
-
1217
-    /**
1218
-     *    extra_nocache_headers
1219
-     *
1220
-     * @access    public
1221
-     * @param $headers
1222
-     * @return    array
1223
-     */
1224
-    public static function extra_nocache_headers($headers)
1225
-    {
1226
-        // for NGINX
1227
-        $headers['X-Accel-Expires'] = 0;
1228
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1229
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1230
-        return $headers;
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     *    nocache_headers
1237
-     *
1238
-     * @access    public
1239
-     * @return    void
1240
-     */
1241
-    public static function nocache_headers()
1242
-    {
1243
-        nocache_headers();
1244
-    }
1245
-
1246
-
1247
-
1248
-
1249
-    /**
1250
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1251
-     * never returned with the function.
1252
-     *
1253
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1254
-     * @return array
1255
-     */
1256
-    public function remove_pages_from_wp_list_pages($exclude_array)
1257
-    {
1258
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1259
-    }
24
+	/**
25
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
26
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
27
+	 */
28
+	const req_type_normal = 0;
29
+
30
+	/**
31
+	 * Indicates this is a brand new installation of EE so we should install
32
+	 * tables and default data etc
33
+	 */
34
+	const req_type_new_activation = 1;
35
+
36
+	/**
37
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
38
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
39
+	 * and that default data is setup too
40
+	 */
41
+	const req_type_reactivation = 2;
42
+
43
+	/**
44
+	 * indicates that EE has been upgraded since its previous request.
45
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
46
+	 */
47
+	const req_type_upgrade = 3;
48
+
49
+	/**
50
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
51
+	 */
52
+	const req_type_downgrade = 4;
53
+
54
+	/**
55
+	 * @deprecated since version 4.6.0.dev.006
56
+	 * Now whenever a new_activation is detected the request type is still just
57
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
58
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
59
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
60
+	 * (Specifically, when the migration manager indicates migrations are finished
61
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
62
+	 */
63
+	const req_type_activation_but_not_installed = 5;
64
+
65
+	/**
66
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
67
+	 */
68
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
69
+
70
+
71
+	/**
72
+	 * @var EE_System $_instance
73
+	 */
74
+	private static $_instance;
75
+
76
+	/**
77
+	 * @var EE_Registry $registry
78
+	 */
79
+	private $registry;
80
+
81
+	/**
82
+	 * @var LoaderInterface $loader
83
+	 */
84
+	private $loader;
85
+
86
+	/**
87
+	 * @var EE_Capabilities $capabilities
88
+	 */
89
+	private $capabilities;
90
+
91
+	/**
92
+	 * @var EE_Request $request
93
+	 */
94
+	private $request;
95
+
96
+	/**
97
+	 * @var EE_Maintenance_Mode $maintenance_mode
98
+	 */
99
+	private $maintenance_mode;
100
+
101
+	/**
102
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
103
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
104
+	 *
105
+	 * @var int $_req_type
106
+	 */
107
+	private $_req_type;
108
+
109
+	/**
110
+	 * Whether or not there was a non-micro version change in EE core version during this request
111
+	 *
112
+	 * @var boolean $_major_version_change
113
+	 */
114
+	private $_major_version_change = false;
115
+
116
+
117
+
118
+	/**
119
+	 * @singleton method used to instantiate class object
120
+	 * @param EE_Registry|null         $registry
121
+	 * @param LoaderInterface|null     $loader
122
+	 * @param EE_Capabilities|null     $capabilities
123
+	 * @param EE_Request|null          $request
124
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
125
+	 * @return EE_System
126
+	 */
127
+	public static function instance(
128
+		EE_Registry $registry = null,
129
+		LoaderInterface $loader = null,
130
+		EE_Capabilities $capabilities = null,
131
+		EE_Request $request = null,
132
+		EE_Maintenance_Mode $maintenance_mode = null
133
+	) {
134
+		// check if class object is instantiated
135
+		if (! self::$_instance instanceof EE_System) {
136
+			self::$_instance = new self($registry, $loader, $capabilities, $request, $maintenance_mode);
137
+		}
138
+		return self::$_instance;
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * resets the instance and returns it
145
+	 *
146
+	 * @return EE_System
147
+	 */
148
+	public static function reset()
149
+	{
150
+		self::$_instance->_req_type = null;
151
+		//make sure none of the old hooks are left hanging around
152
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
153
+		//we need to reset the migration manager in order for it to detect DMSs properly
154
+		EE_Data_Migration_Manager::reset();
155
+		self::instance()->detect_activations_or_upgrades();
156
+		self::instance()->perform_activations_upgrades_and_migrations();
157
+		return self::instance();
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 * sets hooks for running rest of system
164
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
165
+	 * starting EE Addons from any other point may lead to problems
166
+	 *
167
+	 * @param EE_Registry         $registry
168
+	 * @param LoaderInterface     $loader
169
+	 * @param EE_Capabilities     $capabilities
170
+	 * @param EE_Request          $request
171
+	 * @param EE_Maintenance_Mode $maintenance_mode
172
+	 */
173
+	private function __construct(
174
+		EE_Registry $registry,
175
+		LoaderInterface $loader,
176
+		EE_Capabilities $capabilities,
177
+		EE_Request $request,
178
+		EE_Maintenance_Mode $maintenance_mode
179
+	) {
180
+		$this->registry = $registry;
181
+		$this->loader = $loader;
182
+		$this->capabilities = $capabilities;
183
+		$this->request = $request;
184
+		$this->maintenance_mode = $maintenance_mode;
185
+		do_action('AHEE__EE_System__construct__begin', $this);
186
+		add_action(
187
+			'AHEE__EE_Bootstrap__load_espresso_addons',
188
+			array($this, 'loadCapabilities'),
189
+			5
190
+		);
191
+		add_action(
192
+			'AHEE__EE_Bootstrap__load_espresso_addons',
193
+			array($this, 'loadCommandBus'),
194
+			7
195
+		);
196
+		add_action(
197
+			'AHEE__EE_Bootstrap__load_espresso_addons',
198
+			array($this, 'loadPluginApi'),
199
+			9
200
+		);
201
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
202
+		add_action(
203
+			'AHEE__EE_Bootstrap__load_espresso_addons',
204
+			array($this, 'load_espresso_addons')
205
+		);
206
+		// when an ee addon is activated, we want to call the core hook(s) again
207
+		// because the newly-activated addon didn't get a chance to run at all
208
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
209
+		// detect whether install or upgrade
210
+		add_action(
211
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
212
+			array($this, 'detect_activations_or_upgrades'),
213
+			3
214
+		);
215
+		// load EE_Config, EE_Textdomain, etc
216
+		add_action(
217
+			'AHEE__EE_Bootstrap__load_core_configuration',
218
+			array($this, 'load_core_configuration'),
219
+			5
220
+		);
221
+		// load EE_Config, EE_Textdomain, etc
222
+		add_action(
223
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
224
+			array($this, 'register_shortcodes_modules_and_widgets'),
225
+			7
226
+		);
227
+		// you wanna get going? I wanna get going... let's get going!
228
+		add_action(
229
+			'AHEE__EE_Bootstrap__brew_espresso',
230
+			array($this, 'brew_espresso'),
231
+			9
232
+		);
233
+		//other housekeeping
234
+		//exclude EE critical pages from wp_list_pages
235
+		add_filter(
236
+			'wp_list_pages_excludes',
237
+			array($this, 'remove_pages_from_wp_list_pages'),
238
+			10
239
+		);
240
+		// ALL EE Addons should use the following hook point to attach their initial setup too
241
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
242
+		do_action('AHEE__EE_System__construct__complete', $this);
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * load and setup EE_Capabilities
249
+	 *
250
+	 * @return void
251
+	 * @throws EE_Error
252
+	 */
253
+	public function loadCapabilities()
254
+	{
255
+		$this->loader->getShared('EE_Capabilities');
256
+		add_action(
257
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
258
+			function() {
259
+				LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
260
+			}
261
+		);
262
+	}
263
+
264
+
265
+
266
+	/**
267
+	 * create and cache the CommandBus, and also add middleware
268
+	 * The CapChecker middleware requires the use of EE_Capabilities
269
+	 * which is why we need to load the CommandBus after Caps are set up
270
+	 *
271
+	 * @return void
272
+	 * @throws EE_Error
273
+	 */
274
+	public function loadCommandBus()
275
+	{
276
+		$this->loader->getShared(
277
+			'CommandBusInterface',
278
+			array(
279
+				null,
280
+				apply_filters(
281
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
282
+					array(
283
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
284
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
285
+					)
286
+				),
287
+			)
288
+		);
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * @return void
295
+	 * @throws EE_Error
296
+	 */
297
+	public function loadPluginApi()
298
+	{
299
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
300
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
301
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
302
+	}
303
+
304
+
305
+	/**
306
+	 * @param string $addon_name
307
+	 * @param string $version_constant
308
+	 * @param string $min_version_required
309
+	 * @param string $load_callback
310
+	 * @param string $plugin_file_constant
311
+	 * @return void
312
+	 */
313
+	private function deactivateIncompatibleAddon(
314
+		$addon_name,
315
+		$version_constant,
316
+		$min_version_required,
317
+		$load_callback,
318
+		$plugin_file_constant
319
+	) {
320
+		if (! defined($version_constant)) {
321
+			return;
322
+		}
323
+		$addon_version = constant($version_constant);
324
+		if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
325
+			remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
326
+			if (! function_exists('deactivate_plugins')) {
327
+				require_once ABSPATH . 'wp-admin/includes/plugin.php';
328
+			}
329
+			deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
330
+			unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
331
+			EE_Error::add_error(
332
+				sprintf(
333
+					esc_html__(
334
+						'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
335
+						'event_espresso'
336
+					),
337
+					$addon_name,
338
+					$min_version_required
339
+				),
340
+				__FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
341
+			);
342
+			EE_Error::get_notices(false, true);
343
+		}
344
+	}
345
+
346
+
347
+	/**
348
+	 * load_espresso_addons
349
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
350
+	 * this is hooked into both:
351
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
352
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
353
+	 *    and the WP 'activate_plugin' hook point
354
+	 *
355
+	 * @access public
356
+	 * @return void
357
+	 */
358
+	public function load_espresso_addons()
359
+	{
360
+		$this->deactivateIncompatibleAddon(
361
+			'Wait Lists',
362
+			'EE_WAIT_LISTS_VERSION',
363
+			'1.0.0.beta.074',
364
+			'load_espresso_wait_lists',
365
+			'EE_WAIT_LISTS_PLUGIN_FILE'
366
+		);
367
+		$this->deactivateIncompatibleAddon(
368
+			'Automated Upcoming Event Notifications',
369
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
370
+			'1.0.0.beta.091',
371
+			'load_espresso_automated_upcoming_event_notification',
372
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
373
+		);
374
+		do_action('AHEE__EE_System__load_espresso_addons');
375
+		//if the WP API basic auth plugin isn't already loaded, load it now.
376
+		//We want it for mobile apps. Just include the entire plugin
377
+		//also, don't load the basic auth when a plugin is getting activated, because
378
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
379
+		//and causes a fatal error
380
+		if (
381
+			! (
382
+				isset($_GET['activate'])
383
+				&& $_GET['activate'] === 'true'
384
+			)
385
+			&& ! function_exists('json_basic_auth_handler')
386
+			&& ! function_exists('json_basic_auth_error')
387
+			&& ! (
388
+				isset($_GET['action'])
389
+				&& in_array($_GET['action'], array('activate', 'activate-selected'), true)
390
+			)
391
+		) {
392
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
393
+		}
394
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
395
+	}
396
+
397
+
398
+
399
+	/**
400
+	 * detect_activations_or_upgrades
401
+	 * Checks for activation or upgrade of core first;
402
+	 * then also checks if any registered addons have been activated or upgraded
403
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
404
+	 * which runs during the WP 'plugins_loaded' action at priority 3
405
+	 *
406
+	 * @access public
407
+	 * @return void
408
+	 */
409
+	public function detect_activations_or_upgrades()
410
+	{
411
+		//first off: let's make sure to handle core
412
+		$this->detect_if_activation_or_upgrade();
413
+		foreach ($this->registry->addons as $addon) {
414
+			if ($addon instanceof EE_Addon) {
415
+				//detect teh request type for that addon
416
+				$addon->detect_activation_or_upgrade();
417
+			}
418
+		}
419
+	}
420
+
421
+
422
+
423
+	/**
424
+	 * detect_if_activation_or_upgrade
425
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
426
+	 * and either setting up the DB or setting up maintenance mode etc.
427
+	 *
428
+	 * @access public
429
+	 * @return void
430
+	 */
431
+	public function detect_if_activation_or_upgrade()
432
+	{
433
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
434
+		// check if db has been updated, or if its a brand-new installation
435
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
436
+		$request_type = $this->detect_req_type($espresso_db_update);
437
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
438
+		switch ($request_type) {
439
+			case EE_System::req_type_new_activation:
440
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
441
+				$this->_handle_core_version_change($espresso_db_update);
442
+				break;
443
+			case EE_System::req_type_reactivation:
444
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
445
+				$this->_handle_core_version_change($espresso_db_update);
446
+				break;
447
+			case EE_System::req_type_upgrade:
448
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
449
+				//migrations may be required now that we've upgraded
450
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
451
+				$this->_handle_core_version_change($espresso_db_update);
452
+				//				echo "done upgrade";die;
453
+				break;
454
+			case EE_System::req_type_downgrade:
455
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
456
+				//its possible migrations are no longer required
457
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
458
+				$this->_handle_core_version_change($espresso_db_update);
459
+				break;
460
+			case EE_System::req_type_normal:
461
+			default:
462
+				//				$this->_maybe_redirect_to_ee_about();
463
+				break;
464
+		}
465
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
466
+	}
467
+
468
+
469
+
470
+	/**
471
+	 * Updates the list of installed versions and sets hooks for
472
+	 * initializing the database later during the request
473
+	 *
474
+	 * @param array $espresso_db_update
475
+	 */
476
+	private function _handle_core_version_change($espresso_db_update)
477
+	{
478
+		$this->update_list_of_installed_versions($espresso_db_update);
479
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
480
+		add_action(
481
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
482
+			array($this, 'initialize_db_if_no_migrations_required')
483
+		);
484
+	}
485
+
486
+
487
+
488
+	/**
489
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
490
+	 * information about what versions of EE have been installed and activated,
491
+	 * NOT necessarily the state of the database
492
+	 *
493
+	 * @param mixed $espresso_db_update the value of the WordPress option.
494
+	 *                                            If not supplied, fetches it from the options table
495
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
496
+	 */
497
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
498
+	{
499
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
500
+		if (! $espresso_db_update) {
501
+			$espresso_db_update = get_option('espresso_db_update');
502
+		}
503
+		// check that option is an array
504
+		if (! is_array($espresso_db_update)) {
505
+			// if option is FALSE, then it never existed
506
+			if ($espresso_db_update === false) {
507
+				// make $espresso_db_update an array and save option with autoload OFF
508
+				$espresso_db_update = array();
509
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
510
+			} else {
511
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
512
+				$espresso_db_update = array($espresso_db_update => array());
513
+				update_option('espresso_db_update', $espresso_db_update);
514
+			}
515
+		} else {
516
+			$corrected_db_update = array();
517
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
518
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
519
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
520
+					//the key is an int, and the value IS NOT an array
521
+					//so it must be numerically-indexed, where values are versions installed...
522
+					//fix it!
523
+					$version_string = $should_be_array;
524
+					$corrected_db_update[$version_string] = array('unknown-date');
525
+				} else {
526
+					//ok it checks out
527
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
528
+				}
529
+			}
530
+			$espresso_db_update = $corrected_db_update;
531
+			update_option('espresso_db_update', $espresso_db_update);
532
+		}
533
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
534
+		return $espresso_db_update;
535
+	}
536
+
537
+
538
+
539
+	/**
540
+	 * Does the traditional work of setting up the plugin's database and adding default data.
541
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
542
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
543
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
544
+	 * so that it will be done when migrations are finished
545
+	 *
546
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
547
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
548
+	 *                                       This is a resource-intensive job
549
+	 *                                       so we prefer to only do it when necessary
550
+	 * @return void
551
+	 * @throws EE_Error
552
+	 */
553
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
554
+	{
555
+		$request_type = $this->detect_req_type();
556
+		//only initialize system if we're not in maintenance mode.
557
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
558
+			update_option('ee_flush_rewrite_rules', true);
559
+			if ($verify_schema) {
560
+				EEH_Activation::initialize_db_and_folders();
561
+			}
562
+			EEH_Activation::initialize_db_content();
563
+			EEH_Activation::system_initialization();
564
+			if ($initialize_addons_too) {
565
+				$this->initialize_addons();
566
+			}
567
+		} else {
568
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
569
+		}
570
+		if ($request_type === EE_System::req_type_new_activation
571
+			|| $request_type === EE_System::req_type_reactivation
572
+			|| (
573
+				$request_type === EE_System::req_type_upgrade
574
+				&& $this->is_major_version_change()
575
+			)
576
+		) {
577
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
578
+		}
579
+	}
580
+
581
+
582
+
583
+	/**
584
+	 * Initializes the db for all registered addons
585
+	 *
586
+	 * @throws EE_Error
587
+	 */
588
+	public function initialize_addons()
589
+	{
590
+		//foreach registered addon, make sure its db is up-to-date too
591
+		foreach ($this->registry->addons as $addon) {
592
+			if ($addon instanceof EE_Addon) {
593
+				$addon->initialize_db_if_no_migrations_required();
594
+			}
595
+		}
596
+	}
597
+
598
+
599
+
600
+	/**
601
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
602
+	 *
603
+	 * @param    array  $version_history
604
+	 * @param    string $current_version_to_add version to be added to the version history
605
+	 * @return    boolean success as to whether or not this option was changed
606
+	 */
607
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
608
+	{
609
+		if (! $version_history) {
610
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
611
+		}
612
+		if ($current_version_to_add === null) {
613
+			$current_version_to_add = espresso_version();
614
+		}
615
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
616
+		// re-save
617
+		return update_option('espresso_db_update', $version_history);
618
+	}
619
+
620
+
621
+
622
+	/**
623
+	 * Detects if the current version indicated in the has existed in the list of
624
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
625
+	 *
626
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
627
+	 *                                  If not supplied, fetches it from the options table.
628
+	 *                                  Also, caches its result so later parts of the code can also know whether
629
+	 *                                  there's been an update or not. This way we can add the current version to
630
+	 *                                  espresso_db_update, but still know if this is a new install or not
631
+	 * @return int one of the constants on EE_System::req_type_
632
+	 */
633
+	public function detect_req_type($espresso_db_update = null)
634
+	{
635
+		if ($this->_req_type === null) {
636
+			$espresso_db_update = ! empty($espresso_db_update)
637
+				? $espresso_db_update
638
+				: $this->fix_espresso_db_upgrade_option();
639
+			$this->_req_type = EE_System::detect_req_type_given_activation_history(
640
+				$espresso_db_update,
641
+				'ee_espresso_activation', espresso_version()
642
+			);
643
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
644
+		}
645
+		return $this->_req_type;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 * Returns whether or not there was a non-micro version change (ie, change in either
652
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
653
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
654
+	 *
655
+	 * @param $activation_history
656
+	 * @return bool
657
+	 */
658
+	private function _detect_major_version_change($activation_history)
659
+	{
660
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
661
+		$previous_version_parts = explode('.', $previous_version);
662
+		$current_version_parts = explode('.', espresso_version());
663
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
664
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
665
+				   || $previous_version_parts[1] !== $current_version_parts[1]
666
+			   );
667
+	}
668
+
669
+
670
+
671
+	/**
672
+	 * Returns true if either the major or minor version of EE changed during this request.
673
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
674
+	 *
675
+	 * @return bool
676
+	 */
677
+	public function is_major_version_change()
678
+	{
679
+		return $this->_major_version_change;
680
+	}
681
+
682
+
683
+
684
+	/**
685
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
686
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
687
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
688
+	 * just activated to (for core that will always be espresso_version())
689
+	 *
690
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
691
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
692
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
693
+	 *                                                 indicate that this plugin was just activated
694
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
695
+	 *                                                 espresso_version())
696
+	 * @return int one of the constants on EE_System::req_type_*
697
+	 */
698
+	public static function detect_req_type_given_activation_history(
699
+		$activation_history_for_addon,
700
+		$activation_indicator_option_name,
701
+		$version_to_upgrade_to
702
+	) {
703
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
704
+		if ($activation_history_for_addon) {
705
+			//it exists, so this isn't a completely new install
706
+			//check if this version already in that list of previously installed versions
707
+			if (! isset($activation_history_for_addon[$version_to_upgrade_to])) {
708
+				//it a version we haven't seen before
709
+				if ($version_is_higher === 1) {
710
+					$req_type = EE_System::req_type_upgrade;
711
+				} else {
712
+					$req_type = EE_System::req_type_downgrade;
713
+				}
714
+				delete_option($activation_indicator_option_name);
715
+			} else {
716
+				// its not an update. maybe a reactivation?
717
+				if (get_option($activation_indicator_option_name, false)) {
718
+					if ($version_is_higher === -1) {
719
+						$req_type = EE_System::req_type_downgrade;
720
+					} else if ($version_is_higher === 0) {
721
+						//we've seen this version before, but it's an activation. must be a reactivation
722
+						$req_type = EE_System::req_type_reactivation;
723
+					} else {//$version_is_higher === 1
724
+						$req_type = EE_System::req_type_upgrade;
725
+					}
726
+					delete_option($activation_indicator_option_name);
727
+				} else {
728
+					//we've seen this version before and the activation indicate doesn't show it was just activated
729
+					if ($version_is_higher === -1) {
730
+						$req_type = EE_System::req_type_downgrade;
731
+					} else if ($version_is_higher === 0) {
732
+						//we've seen this version before and it's not an activation. its normal request
733
+						$req_type = EE_System::req_type_normal;
734
+					} else {//$version_is_higher === 1
735
+						$req_type = EE_System::req_type_upgrade;
736
+					}
737
+				}
738
+			}
739
+		} else {
740
+			//brand new install
741
+			$req_type = EE_System::req_type_new_activation;
742
+			delete_option($activation_indicator_option_name);
743
+		}
744
+		return $req_type;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
751
+	 * the $activation_history_for_addon
752
+	 *
753
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
754
+	 *                                             sometimes containing 'unknown-date'
755
+	 * @param string $version_to_upgrade_to        (current version)
756
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
757
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
758
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
759
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
760
+	 */
761
+	private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
762
+	{
763
+		//find the most recently-activated version
764
+		$most_recently_active_version =
765
+			EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
766
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
767
+	}
768
+
769
+
770
+
771
+	/**
772
+	 * Gets the most recently active version listed in the activation history,
773
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
774
+	 *
775
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
776
+	 *                                   sometimes containing 'unknown-date'
777
+	 * @return string
778
+	 */
779
+	private static function _get_most_recently_active_version_from_activation_history($activation_history)
780
+	{
781
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
782
+		$most_recently_active_version = '0.0.0.dev.000';
783
+		if (is_array($activation_history)) {
784
+			foreach ($activation_history as $version => $times_activated) {
785
+				//check there is a record of when this version was activated. Otherwise,
786
+				//mark it as unknown
787
+				if (! $times_activated) {
788
+					$times_activated = array('unknown-date');
789
+				}
790
+				if (is_string($times_activated)) {
791
+					$times_activated = array($times_activated);
792
+				}
793
+				foreach ($times_activated as $an_activation) {
794
+					if ($an_activation !== 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
795
+						$most_recently_active_version = $version;
796
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
797
+							? '1970-01-01 00:00:00'
798
+							: $an_activation;
799
+					}
800
+				}
801
+			}
802
+		}
803
+		return $most_recently_active_version;
804
+	}
805
+
806
+
807
+
808
+	/**
809
+	 * This redirects to the about EE page after activation
810
+	 *
811
+	 * @return void
812
+	 */
813
+	public function redirect_to_about_ee()
814
+	{
815
+		$notices = EE_Error::get_notices(false);
816
+		//if current user is an admin and it's not an ajax or rest request
817
+		if (
818
+			! (defined('DOING_AJAX') && DOING_AJAX)
819
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
820
+			&& ! isset($notices['errors'])
821
+			&& apply_filters(
822
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
823
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
824
+			)
825
+		) {
826
+			$query_params = array('page' => 'espresso_about');
827
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
828
+				$query_params['new_activation'] = true;
829
+			}
830
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
831
+				$query_params['reactivation'] = true;
832
+			}
833
+			$url = add_query_arg($query_params, admin_url('admin.php'));
834
+			wp_safe_redirect($url);
835
+			exit();
836
+		}
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * load_core_configuration
843
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
844
+	 * which runs during the WP 'plugins_loaded' action at priority 5
845
+	 *
846
+	 * @return void
847
+	 * @throws ReflectionException
848
+	 */
849
+	public function load_core_configuration()
850
+	{
851
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
852
+		$this->loader->getShared('EE_Load_Textdomain');
853
+		//load textdomain
854
+		EE_Load_Textdomain::load_textdomain();
855
+		// load and setup EE_Config and EE_Network_Config
856
+		$config = $this->loader->getShared('EE_Config');
857
+		$this->loader->getShared('EE_Network_Config');
858
+		// setup autoloaders
859
+		// enable logging?
860
+		if ($config->admin->use_full_logging) {
861
+			$this->loader->getShared('EE_Log');
862
+		}
863
+		// check for activation errors
864
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
865
+		if ($activation_errors) {
866
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
867
+			update_option('ee_plugin_activation_errors', false);
868
+		}
869
+		// get model names
870
+		$this->_parse_model_names();
871
+		//load caf stuff a chance to play during the activation process too.
872
+		$this->_maybe_brew_regular();
873
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
874
+	}
875
+
876
+
877
+
878
+	/**
879
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
880
+	 *
881
+	 * @return void
882
+	 * @throws ReflectionException
883
+	 */
884
+	private function _parse_model_names()
885
+	{
886
+		//get all the files in the EE_MODELS folder that end in .model.php
887
+		$models = glob(EE_MODELS . '*.model.php');
888
+		$model_names = array();
889
+		$non_abstract_db_models = array();
890
+		foreach ($models as $model) {
891
+			// get model classname
892
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
893
+			$short_name = str_replace('EEM_', '', $classname);
894
+			$reflectionClass = new ReflectionClass($classname);
895
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
+				$non_abstract_db_models[$short_name] = $classname;
897
+			}
898
+			$model_names[$short_name] = $classname;
899
+		}
900
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901
+		$this->registry->non_abstract_db_models = apply_filters(
902
+			'FHEE__EE_System__parse_implemented_model_names',
903
+			$non_abstract_db_models
904
+		);
905
+	}
906
+
907
+
908
+
909
+	/**
910
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
911
+	 * that need to be setup before our EE_System launches.
912
+	 *
913
+	 * @return void
914
+	 */
915
+	private function _maybe_brew_regular()
916
+	{
917
+		if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
918
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
919
+		}
920
+	}
921
+
922
+
923
+
924
+	/**
925
+	 * register_shortcodes_modules_and_widgets
926
+	 * generate lists of shortcodes and modules, then verify paths and classes
927
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
928
+	 * which runs during the WP 'plugins_loaded' action at priority 7
929
+	 *
930
+	 * @access public
931
+	 * @return void
932
+	 * @throws Exception
933
+	 */
934
+	public function register_shortcodes_modules_and_widgets()
935
+	{
936
+		try {
937
+			// load, register, and add shortcodes the new way
938
+			$this->loader->getShared(
939
+				'EventEspresso\core\services\shortcodes\ShortcodesManager',
940
+				array(
941
+					// and the old way, but we'll put it under control of the new system
942
+					EE_Config::getLegacyShortcodesManager()
943
+				)
944
+			);
945
+		} catch (Exception $exception) {
946
+			new ExceptionStackTraceDisplay($exception);
947
+		}
948
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
949
+		// check for addons using old hook point
950
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
951
+			$this->_incompatible_addon_error();
952
+		}
953
+	}
954
+
955
+
956
+
957
+	/**
958
+	 * _incompatible_addon_error
959
+	 *
960
+	 * @access public
961
+	 * @return void
962
+	 */
963
+	private function _incompatible_addon_error()
964
+	{
965
+		// get array of classes hooking into here
966
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
967
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
968
+		);
969
+		if (! empty($class_names)) {
970
+			$msg = __(
971
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
972
+				'event_espresso'
973
+			);
974
+			$msg .= '<ul>';
975
+			foreach ($class_names as $class_name) {
976
+				$msg .= '<li><b>Event Espresso - ' . str_replace(
977
+						array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
978
+						$class_name
979
+					) . '</b></li>';
980
+			}
981
+			$msg .= '</ul>';
982
+			$msg .= __(
983
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
984
+				'event_espresso'
985
+			);
986
+			// save list of incompatible addons to wp-options for later use
987
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
988
+			if (is_admin()) {
989
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
990
+			}
991
+		}
992
+	}
993
+
994
+
995
+
996
+	/**
997
+	 * brew_espresso
998
+	 * begins the process of setting hooks for initializing EE in the correct order
999
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1000
+	 * which runs during the WP 'plugins_loaded' action at priority 9
1001
+	 *
1002
+	 * @return void
1003
+	 */
1004
+	public function brew_espresso()
1005
+	{
1006
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
1007
+		// load some final core systems
1008
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
1009
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1010
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
1011
+		add_action('init', array($this, 'load_controllers'), 7);
1012
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
1013
+		add_action('init', array($this, 'initialize'), 10);
1014
+		add_action('init', array($this, 'initialize_last'), 100);
1015
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1016
+			// pew pew pew
1017
+			$this->loader->getShared('EE_PUE');
1018
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1019
+		}
1020
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
1021
+	}
1022
+
1023
+
1024
+
1025
+	/**
1026
+	 *    set_hooks_for_core
1027
+	 *
1028
+	 * @access public
1029
+	 * @return    void
1030
+	 * @throws EE_Error
1031
+	 */
1032
+	public function set_hooks_for_core()
1033
+	{
1034
+		$this->_deactivate_incompatible_addons();
1035
+		do_action('AHEE__EE_System__set_hooks_for_core');
1036
+		//caps need to be initialized on every request so that capability maps are set.
1037
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1038
+		$this->registry->CAP->init_caps();
1039
+	}
1040
+
1041
+
1042
+
1043
+	/**
1044
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
1045
+	 * deactivates any addons considered incompatible with the current version of EE
1046
+	 */
1047
+	private function _deactivate_incompatible_addons()
1048
+	{
1049
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
1050
+		if (! empty($incompatible_addons)) {
1051
+			$active_plugins = get_option('active_plugins', array());
1052
+			foreach ($active_plugins as $active_plugin) {
1053
+				foreach ($incompatible_addons as $incompatible_addon) {
1054
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1055
+						unset($_GET['activate']);
1056
+						espresso_deactivate_plugin($active_plugin);
1057
+					}
1058
+				}
1059
+			}
1060
+		}
1061
+	}
1062
+
1063
+
1064
+
1065
+	/**
1066
+	 *    perform_activations_upgrades_and_migrations
1067
+	 *
1068
+	 * @access public
1069
+	 * @return    void
1070
+	 */
1071
+	public function perform_activations_upgrades_and_migrations()
1072
+	{
1073
+		//first check if we had previously attempted to setup EE's directories but failed
1074
+		if (EEH_Activation::upload_directories_incomplete()) {
1075
+			EEH_Activation::create_upload_directories();
1076
+		}
1077
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1078
+	}
1079
+
1080
+
1081
+
1082
+	/**
1083
+	 *    load_CPTs_and_session
1084
+	 *
1085
+	 * @access public
1086
+	 * @return    void
1087
+	 */
1088
+	public function load_CPTs_and_session()
1089
+	{
1090
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1091
+		// register Custom Post Types
1092
+		$this->loader->getShared('EE_Register_CPTs');
1093
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * load_controllers
1100
+	 * this is the best place to load any additional controllers that needs access to EE core.
1101
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1102
+	 * time
1103
+	 *
1104
+	 * @access public
1105
+	 * @return void
1106
+	 */
1107
+	public function load_controllers()
1108
+	{
1109
+		do_action('AHEE__EE_System__load_controllers__start');
1110
+		// let's get it started
1111
+		if (! is_admin() && ! $this->maintenance_mode->level()) {
1112
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1113
+			$this->loader->getShared('EE_Front_Controller');
1114
+		} else if (! EE_FRONT_AJAX) {
1115
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1116
+			$this->loader->getShared('EE_Admin');
1117
+		}
1118
+		do_action('AHEE__EE_System__load_controllers__complete');
1119
+	}
1120
+
1121
+
1122
+
1123
+	/**
1124
+	 * core_loaded_and_ready
1125
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1126
+	 *
1127
+	 * @access public
1128
+	 * @return void
1129
+	 */
1130
+	public function core_loaded_and_ready()
1131
+	{
1132
+		$this->loader->getShared('EE_Session');
1133
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1134
+		// load_espresso_template_tags
1135
+		if (is_readable(EE_PUBLIC . 'template_tags.php')) {
1136
+			require_once(EE_PUBLIC . 'template_tags.php');
1137
+		}
1138
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1139
+		$this->loader->getShared('EventEspresso\core\services\assets\Registry');
1140
+	}
1141
+
1142
+
1143
+
1144
+	/**
1145
+	 * initialize
1146
+	 * this is the best place to begin initializing client code
1147
+	 *
1148
+	 * @access public
1149
+	 * @return void
1150
+	 */
1151
+	public function initialize()
1152
+	{
1153
+		do_action('AHEE__EE_System__initialize');
1154
+	}
1155
+
1156
+
1157
+
1158
+	/**
1159
+	 * initialize_last
1160
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1161
+	 * initialize has done so
1162
+	 *
1163
+	 * @access public
1164
+	 * @return void
1165
+	 */
1166
+	public function initialize_last()
1167
+	{
1168
+		do_action('AHEE__EE_System__initialize_last');
1169
+		add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * @return void
1176
+	 * @throws EE_Error
1177
+	 */
1178
+	public function addEspressoToolbar()
1179
+	{
1180
+		$this->loader->getShared(
1181
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1182
+			array($this->registry->CAP)
1183
+		);
1184
+	}
1185
+
1186
+
1187
+
1188
+	/**
1189
+	 * do_not_cache
1190
+	 * sets no cache headers and defines no cache constants for WP plugins
1191
+	 *
1192
+	 * @access public
1193
+	 * @return void
1194
+	 */
1195
+	public static function do_not_cache()
1196
+	{
1197
+		// set no cache constants
1198
+		if (! defined('DONOTCACHEPAGE')) {
1199
+			define('DONOTCACHEPAGE', true);
1200
+		}
1201
+		if (! defined('DONOTCACHCEOBJECT')) {
1202
+			define('DONOTCACHCEOBJECT', true);
1203
+		}
1204
+		if (! defined('DONOTCACHEDB')) {
1205
+			define('DONOTCACHEDB', true);
1206
+		}
1207
+		// add no cache headers
1208
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1209
+		// plus a little extra for nginx and Google Chrome
1210
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1211
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1212
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1213
+	}
1214
+
1215
+
1216
+
1217
+	/**
1218
+	 *    extra_nocache_headers
1219
+	 *
1220
+	 * @access    public
1221
+	 * @param $headers
1222
+	 * @return    array
1223
+	 */
1224
+	public static function extra_nocache_headers($headers)
1225
+	{
1226
+		// for NGINX
1227
+		$headers['X-Accel-Expires'] = 0;
1228
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1229
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1230
+		return $headers;
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 *    nocache_headers
1237
+	 *
1238
+	 * @access    public
1239
+	 * @return    void
1240
+	 */
1241
+	public static function nocache_headers()
1242
+	{
1243
+		nocache_headers();
1244
+	}
1245
+
1246
+
1247
+
1248
+
1249
+	/**
1250
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1251
+	 * never returned with the function.
1252
+	 *
1253
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1254
+	 * @return array
1255
+	 */
1256
+	public function remove_pages_from_wp_list_pages($exclude_array)
1257
+	{
1258
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1259
+	}
1260 1260
 
1261 1261
 
1262 1262
 
Please login to merge, or discard this patch.
core/libraries/payment_methods/EE_Payment_Method_Manager.lib.php 2 patches
Indentation   +571 added lines, -571 removed lines patch added patch discarded remove patch
@@ -21,577 +21,577 @@
 block discarded – undo
21 21
 class EE_Payment_Method_Manager implements ResettableInterface
22 22
 {
23 23
 
24
-    /**
25
-     * prefix added to all payment method capabilities names
26
-     */
27
-    const   CAPABILITIES_PREFIX= 'ee_payment_method_';
28
-
29
-    /**
30
-     * @var EE_Payment_Method_Manager $_instance
31
-     */
32
-    private static $_instance;
33
-
34
-    /**
35
-     * @var boolean
36
-     */
37
-    protected $payment_method_caps_initialized = false;
38
-
39
-    /**
40
-     * @var array keys are class names without 'EE_PMT_', values are their filepaths
41
-     */
42
-    protected $_payment_method_types = array();
43
-
44
-    /**
45
-     * @var EE_PMT_Base[]
46
-     */
47
-    protected $payment_method_objects = array();
48
-
49
-
50
-
51
-    /**
52
-     * EE_Payment_Method_Manager constructor.
53
-     *
54
-     * @throws EE_Error
55
-     * @throws DomainException
56
-     */
57
-    public function __construct()
58
-    {
59
-        // if in admin lets ensure caps are set.
60
-        if (is_admin()) {
61
-            $this->_register_payment_methods();
62
-            // set them immediately
63
-            $this->initializePaymentMethodCaps();
64
-            // plus any time they get reset
65
-            add_filter(
66
-                'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
67
-                array($this, 'addPaymentMethodCapsDuringReset')
68
-            );
69
-        }
70
-    }
71
-
72
-
73
-
74
-    /**
75
-     * @singleton method used to instantiate class object
76
-     * @return EE_Payment_Method_Manager instance
77
-     * @throws DomainException
78
-     * @throws EE_Error
79
-     */
80
-    public static function instance()
81
-    {
82
-        // check if class object is instantiated, and instantiated properly
83
-        if (! self::$_instance instanceof EE_Payment_Method_Manager) {
84
-            EE_Registry::instance()->load_lib('PMT_Base');
85
-            self::$_instance = new self();
86
-        }
87
-        return self::$_instance;
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     * Resets the instance and returns a new one
94
-     *
95
-     * @return EE_Payment_Method_Manager
96
-     * @throws DomainException
97
-     * @throws EE_Error
98
-     */
99
-    public static function reset()
100
-    {
101
-        self::$_instance = null;
102
-        return self::instance();
103
-    }
104
-
105
-
106
-
107
-    /**
108
-     * If necessary, re-register payment methods
109
-     *
110
-     * @param boolean $force_recheck whether to recheck for payment method types,
111
-     *                               or just re-use the PMTs we found last time we checked during this request (if
112
-     *                               we have not yet checked during this request, then we need to check anyways)
113
-     */
114
-    public function maybe_register_payment_methods($force_recheck = false)
115
-    {
116
-        if (! $this->_payment_method_types || $force_recheck) {
117
-            $this->_register_payment_methods();
118
-        }
119
-    }
120
-
121
-
122
-
123
-    /**
124
-     * register_payment_methods
125
-     *
126
-     * @return array
127
-     */
128
-    protected function _register_payment_methods()
129
-    {
130
-        // grab list of installed modules
131
-        $pm_to_register = glob(EE_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
132
-        // filter list of modules to register
133
-        $pm_to_register = apply_filters(
134
-            'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
135
-            $pm_to_register
136
-        );
137
-        // remove any duplicates if that should happen for some reason
138
-        $pm_to_register = array_unique($pm_to_register);
139
-        // loop through folders
140
-        foreach ($pm_to_register as $pm_path) {
141
-            $this->register_payment_method($pm_path);
142
-        }
143
-        do_action('FHEE__EE_Payment_Method_Manager__register_payment_methods__registered_payment_methods');
144
-        // filter list of installed modules
145
-        //keep them organized alphabetically by the payment method type's name
146
-        ksort($this->_payment_method_types);
147
-        return apply_filters(
148
-            'FHEE__EE_Payment_Method_Manager__register_payment_methods__installed_payment_methods',
149
-            $this->_payment_method_types
150
-        );
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * register_payment_method- makes core aware of this payment method
157
-     *
158
-     * @param string $payment_method_path - full path up to and including payment method folder
159
-     * @return boolean
160
-     */
161
-    public function register_payment_method($payment_method_path = '')
162
-    {
163
-        do_action('AHEE__EE_Payment_Method_Manager__register_payment_method__begin', $payment_method_path);
164
-        $module_ext = '.pm.php';
165
-        // make all separators match
166
-        $payment_method_path = rtrim(str_replace('/\\', DS, $payment_method_path), DS);
167
-        // grab and sanitize module name
168
-        $module_dir = basename($payment_method_path);
169
-        // create class name from module directory name
170
-        $module = str_replace(array('_', ' '), array(' ', '_'), $module_dir);
171
-        // add class prefix
172
-        $module_class = 'EE_PMT_' . $module;
173
-        // does the module exist ?
174
-        if (! is_readable($payment_method_path . DS . $module_class . $module_ext)) {
175
-            $msg = sprintf(
176
-                esc_html__(
177
-                    'The requested %s payment method file could not be found or is not readable due to file permissions.',
178
-                    'event_espresso'
179
-                ), $module
180
-            );
181
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
182
-            return false;
183
-        }
184
-        // load the module class file
185
-        require_once($payment_method_path . DS . $module_class . $module_ext);
186
-        // verify that class exists
187
-        if (! class_exists($module_class)) {
188
-            $msg = sprintf(
189
-                esc_html__('The requested %s module class does not exist.', 'event_espresso'),
190
-                $module_class
191
-            );
192
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
193
-            return false;
194
-        }
195
-        // add to array of registered modules
196
-        $this->_payment_method_types[$module] = $payment_method_path . DS . $module_class . $module_ext;
197
-        ksort($this->_payment_method_types);
198
-        return true;
199
-    }
200
-
201
-
202
-
203
-    /**
204
-     * Checks if a payment method has been registered, and if so includes it
205
-     *
206
-     * @param string  $payment_method_name like 'PayPal_Pro', (ie class name without the prefix 'EEPM_')
207
-     * @param boolean $force_recheck       whether to force re-checking for new payment method types
208
-     * @return boolean
209
-     */
210
-    public function payment_method_type_exists($payment_method_name, $force_recheck = false)
211
-    {
212
-        if (
213
-            $force_recheck
214
-            || ! is_array($this->_payment_method_types)
215
-            || ! isset($this->_payment_method_types[$payment_method_name])
216
-        ) {
217
-            $this->maybe_register_payment_methods($force_recheck);
218
-        }
219
-        if (isset($this->_payment_method_types[$payment_method_name])) {
220
-            require_once($this->_payment_method_types[$payment_method_name]);
221
-            return true;
222
-        }
223
-        return false;
224
-    }
225
-
226
-
227
-
228
-    /**
229
-     * Returns all the class names of the various payment method types
230
-     *
231
-     * @param boolean $with_prefixes TRUE: get payment method type class names; false just their 'names'
232
-     *                               (what you'd find in wp_esp_payment_method.PMD_type)
233
-     * @param boolean $force_recheck whether to force re-checking for new payment method types
234
-     * @return array
235
-     */
236
-    public function payment_method_type_names($with_prefixes = false, $force_recheck = false)
237
-    {
238
-        $this->maybe_register_payment_methods($force_recheck);
239
-        if ($with_prefixes) {
240
-            $classnames = array_keys($this->_payment_method_types);
241
-            $payment_methods = array();
242
-            foreach ($classnames as $classname) {
243
-                $payment_methods[] = $this->payment_method_class_from_type($classname);
244
-            }
245
-            return $payment_methods;
246
-        }
247
-        return array_keys($this->_payment_method_types);
248
-    }
249
-
250
-
251
-
252
-    /**
253
-     * Gets an object of each payment method type, none of which are bound to a
254
-     * payment method instance
255
-     *
256
-     * @param boolean $force_recheck whether to force re-checking for new payment method types
257
-     * @return EE_PMT_Base[]
258
-     */
259
-    public function payment_method_types($force_recheck = false)
260
-    {
261
-        if ($force_recheck || empty($this->payment_method_objects)) {
262
-            $this->maybe_register_payment_methods($force_recheck);
263
-            foreach ($this->payment_method_type_names(true) as $classname) {
264
-                if (! isset($this->payment_method_objects[$classname])) {
265
-                    $this->payment_method_objects[$classname] = new $classname;
266
-                }
267
-            }
268
-        }
269
-        return $this->payment_method_objects;
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * Changes the payment method's class name into the payment method type's name
276
-     * (as used on the payment method's table's PMD_type field)
277
-     *
278
-     * @param string $classname
279
-     * @return string
280
-     */
281
-    public function payment_method_type_sans_class_prefix($classname)
282
-    {
283
-        return str_replace('EE_PMT_', '', $classname);
284
-    }
285
-
286
-
287
-
288
-    /**
289
-     * Does the opposite of payment-method_type_sans_prefix
290
-     *
291
-     * @param string $type
292
-     * @return string
293
-     */
294
-    public function payment_method_class_from_type($type)
295
-    {
296
-        return 'EE_PMT_' . $type;
297
-    }
298
-
299
-
300
-
301
-    /**
302
-     * Activates a payment method of the given type.
303
-     *
304
-     * @param string $payment_method_type the PMT_type; for EE_PMT_Invoice this would be 'Invoice'
305
-     * @return EE_Payment_Method
306
-     * @throws InvalidDataTypeException
307
-     * @throws EE_Error
308
-     */
309
-    public function activate_a_payment_method_of_type($payment_method_type)
310
-    {
311
-        $this->maybe_register_payment_methods();
312
-        $payment_method = EEM_Payment_Method::instance()->get_one_of_type($payment_method_type);
313
-        if (! $payment_method instanceof EE_Payment_Method) {
314
-            $pm_type_class = $this->payment_method_class_from_type($payment_method_type);
315
-            if (class_exists($pm_type_class)) {
316
-                /** @var $pm_type_obj EE_PMT_Base */
317
-                $pm_type_obj = new $pm_type_class;
318
-                $payment_method = EEM_Payment_Method::instance()->get_one_by_slug($pm_type_obj->system_name());
319
-                if (! $payment_method) {
320
-                    $payment_method = $this->create_payment_method_of_type($pm_type_obj);
321
-                }
322
-                $payment_method->set_type($payment_method_type);
323
-                $this->initialize_payment_method($payment_method);
324
-            } else {
325
-                throw new EE_Error(
326
-                    sprintf(
327
-                        esc_html__(
328
-                            'There is no payment method of type %1$s, so it could not be activated',
329
-                            'event_espresso'
330
-                        ),
331
-                        $pm_type_class
332
-                    )
333
-                );
334
-            }
335
-        }
336
-        $payment_method->set_active();
337
-        $payment_method->save();
338
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
339
-        //if this was the invoice message type, make sure users can view their invoices
340
-        if ($payment_method->type() === 'Invoice'
341
-            && (
342
-                ! EEH_MSG_Template::is_mt_active('invoice')
343
-            )
344
-        ) {
345
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
346
-            /** @type EE_Message_Resource_Manager $message_resource_manager */
347
-            $message_resource_manager->ensure_message_type_is_active('invoice', 'html');
348
-            new PersistentAdminNotice(
349
-                'invoice_pm_requirements_notice',
350
-                sprintf(
351
-                    esc_html__(
352
-                        'The Invoice payment method has been activated. It requires the %1$sinvoice message%2$s type to be active, so it was automatically activated for you.',
353
-                        'event_espresso'
354
-                    ),
355
-                    '<a href="' . admin_url('admin.php?page=espresso_messages&action=settings') . '">',
356
-                    '</a>'
357
-                ),
358
-                true
359
-            );
360
-        }
361
-        return $payment_method;
362
-    }
363
-
364
-
365
-
366
-    /**
367
-     * Creates a payment method of the specified type. Does not save it.
368
-     *
369
-     * @global WP_User    $current_user
370
-     * @param EE_PMT_Base $pm_type_obj
371
-     * @return EE_Payment_Method
372
-     * @throws EE_Error
373
-     */
374
-    public function create_payment_method_of_type($pm_type_obj)
375
-    {
376
-        global $current_user;
377
-        $payment_method = EE_Payment_Method::new_instance(
378
-            array(
379
-                'PMD_type'       => $pm_type_obj->system_name(),
380
-                'PMD_name'       => $pm_type_obj->pretty_name(),
381
-                'PMD_admin_name' => $pm_type_obj->pretty_name(),
382
-                'PMD_slug'       => $pm_type_obj->system_name(),//automatically converted to slug
383
-                'PMD_wp_user'    => $current_user->ID,
384
-                'PMD_order'      => EEM_Payment_Method::instance()->count(
385
-                        array(array('PMD_type' => array('!=', 'Admin_Only')))
386
-                    ) * 10,
387
-            )
388
-        );
389
-        return $payment_method;
390
-    }
391
-
392
-
393
-
394
-    /**
395
-     * Sets the initial payment method properties (including extra meta)
396
-     *
397
-     * @param EE_Payment_Method $payment_method
398
-     * @return EE_Payment_Method
399
-     * @throws EE_Error
400
-     */
401
-    public function initialize_payment_method($payment_method)
402
-    {
403
-        $pm_type_obj = $payment_method->type_obj();
404
-        $payment_method->set_description($pm_type_obj->default_description());
405
-        if (! $payment_method->button_url()) {
406
-            $payment_method->set_button_url($pm_type_obj->default_button_url());
407
-        }
408
-        //now add setup its default extra meta properties
409
-        $extra_metas = $pm_type_obj->settings_form()->extra_meta_inputs();
410
-        if (! empty($extra_metas)) {
411
-            //verify the payment method has an ID before adding extra meta
412
-            if (! $payment_method->ID()) {
413
-                $payment_method->save();
414
-            }
415
-            foreach ($extra_metas as $meta_name => $input) {
416
-                $payment_method->update_extra_meta($meta_name, $input->raw_value());
417
-            }
418
-        }
419
-        return $payment_method;
420
-    }
421
-
422
-
423
-
424
-    /**
425
-     * Makes sure the payment method is related to the specified payment method
426
-     *
427
-     * @deprecated in 4.9.40 because the currency payment method table is being deprecated
428
-     * @param EE_Payment_Method $payment_method
429
-     * @return EE_Payment_Method
430
-     * @throws EE_Error
431
-     */
432
-    public function set_usable_currencies_on_payment_method($payment_method)
433
-    {
434
-        EE_Error::doing_it_wrong(
435
-            'EE_Payment_Method_Manager::set_usable_currencies_on_payment_method',
436
-            esc_html__(
437
-                'We no longer define what currencies are usable by payment methods. Its not used nor efficient.',
438
-                'event_espresso'
439
-            ),
440
-            '4.9.40'
441
-        );
442
-        return $payment_method;
443
-    }
444
-
445
-
446
-
447
-    /**
448
-     * Deactivates a payment method of the given payment method slug.
449
-     *
450
-     * @param string $payment_method_slug The slug for the payment method to deactivate.
451
-     * @return int count of rows updated.
452
-     * @throws EE_Error
453
-     */
454
-    public function deactivate_payment_method($payment_method_slug)
455
-    {
456
-        EE_Log::instance()->log(
457
-            __FILE__,
458
-            __FUNCTION__,
459
-            sprintf(
460
-                esc_html__(
461
-                    'Payment method with slug %1$s is being deactivated by site admin',
462
-                    'event_espresso'
463
-                ),
464
-                $payment_method_slug
465
-            ),
466
-            'payment_method_change'
467
-        );
468
-        $count_updated = EEM_Payment_Method::instance()->update(
469
-            array('PMD_scope' => array()),
470
-            array(array('PMD_slug' => $payment_method_slug))
471
-        );
472
-        return $count_updated;
473
-    }
474
-
475
-
476
-
477
-    /**
478
-     * initializes payment method access caps via EE_Capabilities::init_role_caps()
479
-     * upon EE_Payment_Method_Manager construction
480
-     *
481
-     * @throws EE_Error
482
-     * @throws DomainException
483
-     */
484
-    protected function initializePaymentMethodCaps()
485
-    {
486
-        // don't do this twice
487
-        if ($this->payment_method_caps_initialized) {
488
-            return;
489
-        }
490
-        EE_Capabilities::instance()->addCaps(
491
-            $this->getPaymentMethodCaps()
492
-        );
493
-        $this->payment_method_caps_initialized = true;
494
-    }
495
-
496
-
497
-
498
-    /**
499
-     * array  of dynamic payment method access caps.
500
-     * at the time of writing, october 20 2014, these are the caps added:
501
-     *  ee_payment_method_admin_only
502
-     *  ee_payment_method_aim
503
-     *  ee_payment_method_bank
504
-     *  ee_payment_method_check
505
-     *  ee_payment_method_invoice
506
-     *  ee_payment_method_mijireh
507
-     *  ee_payment_method_paypal_pro
508
-     *  ee_payment_method_paypal_standard
509
-     * Any other payment methods added to core or via addons will also get
510
-     * their related capability automatically added too, so long as they are
511
-     * registered properly using EE_Register_Payment_Method::register()
512
-     *
513
-     * @return array
514
-     * @throws DomainException
515
-     */
516
-    protected function getPaymentMethodCaps()
517
-    {
518
-        $caps = array();
519
-        foreach ($this->payment_method_type_names() as $payment_method_name) {
520
-            $caps = $this->addPaymentMethodCap($payment_method_name,$caps);
521
-        }
522
-        return $caps;
523
-    }
524
-
525
-
526
-
527
-    /**
528
-     * @param string $payment_method_name
529
-     * @param array  $payment_method_caps
530
-     * @param string $role
531
-     * @return array
532
-     * @throws DomainException
533
-     */
534
-    public function addPaymentMethodCap($payment_method_name, array $payment_method_caps, $role = 'administrator')
535
-    {
536
-        if (empty($payment_method_name)) {
537
-            throw new DomainException(
538
-                esc_html__(
539
-                    'The name of a payment method must be specified to add capabilities.',
540
-                    'event_espresso'
541
-                )
542
-            );
543
-        }
544
-        if (empty($role)) {
545
-            throw new DomainException(
546
-                sprintf(
547
-                    esc_html__(
548
-                        'No role was supplied while trying to add capabilities for the %1$s payment method.',
549
-                        'event_espresso'
550
-                    ),
551
-                    $payment_method_name
552
-                )
553
-            );
554
-        }
555
-        if(! isset($payment_method_caps[$role])) {
556
-            $payment_method_caps[$role] = array();
557
-        }
558
-        $payment_method_caps[$role][] = EE_Payment_Method_Manager::CAPABILITIES_PREFIX
559
-                                                  . strtolower($payment_method_name);
560
-        return $payment_method_caps;
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     * callback for FHEE__EE_Capabilities__init_role_caps__caps_map filter
567
-     * to add dynamic payment method access caps when capabilities are reset
568
-     * (or if that filter is called and PM caps are not already set)
569
-     *
570
-     * @param array $caps capabilities being filtered
571
-     * @param bool  $reset
572
-     * @return array
573
-     * @throws DomainException
574
-     */
575
-    public function addPaymentMethodCapsDuringReset(array $caps, $reset = false)
576
-    {
577
-        if ($reset || ! $this->payment_method_caps_initialized) {
578
-            $this->payment_method_caps_initialized = true;
579
-            $caps = array_merge_recursive($caps, $this->getPaymentMethodCaps());
580
-        }
581
-        return $caps;
582
-    }
583
-
584
-
585
-
586
-    /**
587
-     * @deprecated 4.9.42
588
-     * @param $caps
589
-     * @return mixed
590
-     */
591
-    public function add_payment_method_caps($caps)
592
-    {
593
-        return $caps;
594
-    }
24
+	/**
25
+	 * prefix added to all payment method capabilities names
26
+	 */
27
+	const   CAPABILITIES_PREFIX= 'ee_payment_method_';
28
+
29
+	/**
30
+	 * @var EE_Payment_Method_Manager $_instance
31
+	 */
32
+	private static $_instance;
33
+
34
+	/**
35
+	 * @var boolean
36
+	 */
37
+	protected $payment_method_caps_initialized = false;
38
+
39
+	/**
40
+	 * @var array keys are class names without 'EE_PMT_', values are their filepaths
41
+	 */
42
+	protected $_payment_method_types = array();
43
+
44
+	/**
45
+	 * @var EE_PMT_Base[]
46
+	 */
47
+	protected $payment_method_objects = array();
48
+
49
+
50
+
51
+	/**
52
+	 * EE_Payment_Method_Manager constructor.
53
+	 *
54
+	 * @throws EE_Error
55
+	 * @throws DomainException
56
+	 */
57
+	public function __construct()
58
+	{
59
+		// if in admin lets ensure caps are set.
60
+		if (is_admin()) {
61
+			$this->_register_payment_methods();
62
+			// set them immediately
63
+			$this->initializePaymentMethodCaps();
64
+			// plus any time they get reset
65
+			add_filter(
66
+				'FHEE__EE_Capabilities__addCaps__capabilities_to_add',
67
+				array($this, 'addPaymentMethodCapsDuringReset')
68
+			);
69
+		}
70
+	}
71
+
72
+
73
+
74
+	/**
75
+	 * @singleton method used to instantiate class object
76
+	 * @return EE_Payment_Method_Manager instance
77
+	 * @throws DomainException
78
+	 * @throws EE_Error
79
+	 */
80
+	public static function instance()
81
+	{
82
+		// check if class object is instantiated, and instantiated properly
83
+		if (! self::$_instance instanceof EE_Payment_Method_Manager) {
84
+			EE_Registry::instance()->load_lib('PMT_Base');
85
+			self::$_instance = new self();
86
+		}
87
+		return self::$_instance;
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 * Resets the instance and returns a new one
94
+	 *
95
+	 * @return EE_Payment_Method_Manager
96
+	 * @throws DomainException
97
+	 * @throws EE_Error
98
+	 */
99
+	public static function reset()
100
+	{
101
+		self::$_instance = null;
102
+		return self::instance();
103
+	}
104
+
105
+
106
+
107
+	/**
108
+	 * If necessary, re-register payment methods
109
+	 *
110
+	 * @param boolean $force_recheck whether to recheck for payment method types,
111
+	 *                               or just re-use the PMTs we found last time we checked during this request (if
112
+	 *                               we have not yet checked during this request, then we need to check anyways)
113
+	 */
114
+	public function maybe_register_payment_methods($force_recheck = false)
115
+	{
116
+		if (! $this->_payment_method_types || $force_recheck) {
117
+			$this->_register_payment_methods();
118
+		}
119
+	}
120
+
121
+
122
+
123
+	/**
124
+	 * register_payment_methods
125
+	 *
126
+	 * @return array
127
+	 */
128
+	protected function _register_payment_methods()
129
+	{
130
+		// grab list of installed modules
131
+		$pm_to_register = glob(EE_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
132
+		// filter list of modules to register
133
+		$pm_to_register = apply_filters(
134
+			'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
135
+			$pm_to_register
136
+		);
137
+		// remove any duplicates if that should happen for some reason
138
+		$pm_to_register = array_unique($pm_to_register);
139
+		// loop through folders
140
+		foreach ($pm_to_register as $pm_path) {
141
+			$this->register_payment_method($pm_path);
142
+		}
143
+		do_action('FHEE__EE_Payment_Method_Manager__register_payment_methods__registered_payment_methods');
144
+		// filter list of installed modules
145
+		//keep them organized alphabetically by the payment method type's name
146
+		ksort($this->_payment_method_types);
147
+		return apply_filters(
148
+			'FHEE__EE_Payment_Method_Manager__register_payment_methods__installed_payment_methods',
149
+			$this->_payment_method_types
150
+		);
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * register_payment_method- makes core aware of this payment method
157
+	 *
158
+	 * @param string $payment_method_path - full path up to and including payment method folder
159
+	 * @return boolean
160
+	 */
161
+	public function register_payment_method($payment_method_path = '')
162
+	{
163
+		do_action('AHEE__EE_Payment_Method_Manager__register_payment_method__begin', $payment_method_path);
164
+		$module_ext = '.pm.php';
165
+		// make all separators match
166
+		$payment_method_path = rtrim(str_replace('/\\', DS, $payment_method_path), DS);
167
+		// grab and sanitize module name
168
+		$module_dir = basename($payment_method_path);
169
+		// create class name from module directory name
170
+		$module = str_replace(array('_', ' '), array(' ', '_'), $module_dir);
171
+		// add class prefix
172
+		$module_class = 'EE_PMT_' . $module;
173
+		// does the module exist ?
174
+		if (! is_readable($payment_method_path . DS . $module_class . $module_ext)) {
175
+			$msg = sprintf(
176
+				esc_html__(
177
+					'The requested %s payment method file could not be found or is not readable due to file permissions.',
178
+					'event_espresso'
179
+				), $module
180
+			);
181
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
182
+			return false;
183
+		}
184
+		// load the module class file
185
+		require_once($payment_method_path . DS . $module_class . $module_ext);
186
+		// verify that class exists
187
+		if (! class_exists($module_class)) {
188
+			$msg = sprintf(
189
+				esc_html__('The requested %s module class does not exist.', 'event_espresso'),
190
+				$module_class
191
+			);
192
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
193
+			return false;
194
+		}
195
+		// add to array of registered modules
196
+		$this->_payment_method_types[$module] = $payment_method_path . DS . $module_class . $module_ext;
197
+		ksort($this->_payment_method_types);
198
+		return true;
199
+	}
200
+
201
+
202
+
203
+	/**
204
+	 * Checks if a payment method has been registered, and if so includes it
205
+	 *
206
+	 * @param string  $payment_method_name like 'PayPal_Pro', (ie class name without the prefix 'EEPM_')
207
+	 * @param boolean $force_recheck       whether to force re-checking for new payment method types
208
+	 * @return boolean
209
+	 */
210
+	public function payment_method_type_exists($payment_method_name, $force_recheck = false)
211
+	{
212
+		if (
213
+			$force_recheck
214
+			|| ! is_array($this->_payment_method_types)
215
+			|| ! isset($this->_payment_method_types[$payment_method_name])
216
+		) {
217
+			$this->maybe_register_payment_methods($force_recheck);
218
+		}
219
+		if (isset($this->_payment_method_types[$payment_method_name])) {
220
+			require_once($this->_payment_method_types[$payment_method_name]);
221
+			return true;
222
+		}
223
+		return false;
224
+	}
225
+
226
+
227
+
228
+	/**
229
+	 * Returns all the class names of the various payment method types
230
+	 *
231
+	 * @param boolean $with_prefixes TRUE: get payment method type class names; false just their 'names'
232
+	 *                               (what you'd find in wp_esp_payment_method.PMD_type)
233
+	 * @param boolean $force_recheck whether to force re-checking for new payment method types
234
+	 * @return array
235
+	 */
236
+	public function payment_method_type_names($with_prefixes = false, $force_recheck = false)
237
+	{
238
+		$this->maybe_register_payment_methods($force_recheck);
239
+		if ($with_prefixes) {
240
+			$classnames = array_keys($this->_payment_method_types);
241
+			$payment_methods = array();
242
+			foreach ($classnames as $classname) {
243
+				$payment_methods[] = $this->payment_method_class_from_type($classname);
244
+			}
245
+			return $payment_methods;
246
+		}
247
+		return array_keys($this->_payment_method_types);
248
+	}
249
+
250
+
251
+
252
+	/**
253
+	 * Gets an object of each payment method type, none of which are bound to a
254
+	 * payment method instance
255
+	 *
256
+	 * @param boolean $force_recheck whether to force re-checking for new payment method types
257
+	 * @return EE_PMT_Base[]
258
+	 */
259
+	public function payment_method_types($force_recheck = false)
260
+	{
261
+		if ($force_recheck || empty($this->payment_method_objects)) {
262
+			$this->maybe_register_payment_methods($force_recheck);
263
+			foreach ($this->payment_method_type_names(true) as $classname) {
264
+				if (! isset($this->payment_method_objects[$classname])) {
265
+					$this->payment_method_objects[$classname] = new $classname;
266
+				}
267
+			}
268
+		}
269
+		return $this->payment_method_objects;
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * Changes the payment method's class name into the payment method type's name
276
+	 * (as used on the payment method's table's PMD_type field)
277
+	 *
278
+	 * @param string $classname
279
+	 * @return string
280
+	 */
281
+	public function payment_method_type_sans_class_prefix($classname)
282
+	{
283
+		return str_replace('EE_PMT_', '', $classname);
284
+	}
285
+
286
+
287
+
288
+	/**
289
+	 * Does the opposite of payment-method_type_sans_prefix
290
+	 *
291
+	 * @param string $type
292
+	 * @return string
293
+	 */
294
+	public function payment_method_class_from_type($type)
295
+	{
296
+		return 'EE_PMT_' . $type;
297
+	}
298
+
299
+
300
+
301
+	/**
302
+	 * Activates a payment method of the given type.
303
+	 *
304
+	 * @param string $payment_method_type the PMT_type; for EE_PMT_Invoice this would be 'Invoice'
305
+	 * @return EE_Payment_Method
306
+	 * @throws InvalidDataTypeException
307
+	 * @throws EE_Error
308
+	 */
309
+	public function activate_a_payment_method_of_type($payment_method_type)
310
+	{
311
+		$this->maybe_register_payment_methods();
312
+		$payment_method = EEM_Payment_Method::instance()->get_one_of_type($payment_method_type);
313
+		if (! $payment_method instanceof EE_Payment_Method) {
314
+			$pm_type_class = $this->payment_method_class_from_type($payment_method_type);
315
+			if (class_exists($pm_type_class)) {
316
+				/** @var $pm_type_obj EE_PMT_Base */
317
+				$pm_type_obj = new $pm_type_class;
318
+				$payment_method = EEM_Payment_Method::instance()->get_one_by_slug($pm_type_obj->system_name());
319
+				if (! $payment_method) {
320
+					$payment_method = $this->create_payment_method_of_type($pm_type_obj);
321
+				}
322
+				$payment_method->set_type($payment_method_type);
323
+				$this->initialize_payment_method($payment_method);
324
+			} else {
325
+				throw new EE_Error(
326
+					sprintf(
327
+						esc_html__(
328
+							'There is no payment method of type %1$s, so it could not be activated',
329
+							'event_espresso'
330
+						),
331
+						$pm_type_class
332
+					)
333
+				);
334
+			}
335
+		}
336
+		$payment_method->set_active();
337
+		$payment_method->save();
338
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
339
+		//if this was the invoice message type, make sure users can view their invoices
340
+		if ($payment_method->type() === 'Invoice'
341
+			&& (
342
+				! EEH_MSG_Template::is_mt_active('invoice')
343
+			)
344
+		) {
345
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
346
+			/** @type EE_Message_Resource_Manager $message_resource_manager */
347
+			$message_resource_manager->ensure_message_type_is_active('invoice', 'html');
348
+			new PersistentAdminNotice(
349
+				'invoice_pm_requirements_notice',
350
+				sprintf(
351
+					esc_html__(
352
+						'The Invoice payment method has been activated. It requires the %1$sinvoice message%2$s type to be active, so it was automatically activated for you.',
353
+						'event_espresso'
354
+					),
355
+					'<a href="' . admin_url('admin.php?page=espresso_messages&action=settings') . '">',
356
+					'</a>'
357
+				),
358
+				true
359
+			);
360
+		}
361
+		return $payment_method;
362
+	}
363
+
364
+
365
+
366
+	/**
367
+	 * Creates a payment method of the specified type. Does not save it.
368
+	 *
369
+	 * @global WP_User    $current_user
370
+	 * @param EE_PMT_Base $pm_type_obj
371
+	 * @return EE_Payment_Method
372
+	 * @throws EE_Error
373
+	 */
374
+	public function create_payment_method_of_type($pm_type_obj)
375
+	{
376
+		global $current_user;
377
+		$payment_method = EE_Payment_Method::new_instance(
378
+			array(
379
+				'PMD_type'       => $pm_type_obj->system_name(),
380
+				'PMD_name'       => $pm_type_obj->pretty_name(),
381
+				'PMD_admin_name' => $pm_type_obj->pretty_name(),
382
+				'PMD_slug'       => $pm_type_obj->system_name(),//automatically converted to slug
383
+				'PMD_wp_user'    => $current_user->ID,
384
+				'PMD_order'      => EEM_Payment_Method::instance()->count(
385
+						array(array('PMD_type' => array('!=', 'Admin_Only')))
386
+					) * 10,
387
+			)
388
+		);
389
+		return $payment_method;
390
+	}
391
+
392
+
393
+
394
+	/**
395
+	 * Sets the initial payment method properties (including extra meta)
396
+	 *
397
+	 * @param EE_Payment_Method $payment_method
398
+	 * @return EE_Payment_Method
399
+	 * @throws EE_Error
400
+	 */
401
+	public function initialize_payment_method($payment_method)
402
+	{
403
+		$pm_type_obj = $payment_method->type_obj();
404
+		$payment_method->set_description($pm_type_obj->default_description());
405
+		if (! $payment_method->button_url()) {
406
+			$payment_method->set_button_url($pm_type_obj->default_button_url());
407
+		}
408
+		//now add setup its default extra meta properties
409
+		$extra_metas = $pm_type_obj->settings_form()->extra_meta_inputs();
410
+		if (! empty($extra_metas)) {
411
+			//verify the payment method has an ID before adding extra meta
412
+			if (! $payment_method->ID()) {
413
+				$payment_method->save();
414
+			}
415
+			foreach ($extra_metas as $meta_name => $input) {
416
+				$payment_method->update_extra_meta($meta_name, $input->raw_value());
417
+			}
418
+		}
419
+		return $payment_method;
420
+	}
421
+
422
+
423
+
424
+	/**
425
+	 * Makes sure the payment method is related to the specified payment method
426
+	 *
427
+	 * @deprecated in 4.9.40 because the currency payment method table is being deprecated
428
+	 * @param EE_Payment_Method $payment_method
429
+	 * @return EE_Payment_Method
430
+	 * @throws EE_Error
431
+	 */
432
+	public function set_usable_currencies_on_payment_method($payment_method)
433
+	{
434
+		EE_Error::doing_it_wrong(
435
+			'EE_Payment_Method_Manager::set_usable_currencies_on_payment_method',
436
+			esc_html__(
437
+				'We no longer define what currencies are usable by payment methods. Its not used nor efficient.',
438
+				'event_espresso'
439
+			),
440
+			'4.9.40'
441
+		);
442
+		return $payment_method;
443
+	}
444
+
445
+
446
+
447
+	/**
448
+	 * Deactivates a payment method of the given payment method slug.
449
+	 *
450
+	 * @param string $payment_method_slug The slug for the payment method to deactivate.
451
+	 * @return int count of rows updated.
452
+	 * @throws EE_Error
453
+	 */
454
+	public function deactivate_payment_method($payment_method_slug)
455
+	{
456
+		EE_Log::instance()->log(
457
+			__FILE__,
458
+			__FUNCTION__,
459
+			sprintf(
460
+				esc_html__(
461
+					'Payment method with slug %1$s is being deactivated by site admin',
462
+					'event_espresso'
463
+				),
464
+				$payment_method_slug
465
+			),
466
+			'payment_method_change'
467
+		);
468
+		$count_updated = EEM_Payment_Method::instance()->update(
469
+			array('PMD_scope' => array()),
470
+			array(array('PMD_slug' => $payment_method_slug))
471
+		);
472
+		return $count_updated;
473
+	}
474
+
475
+
476
+
477
+	/**
478
+	 * initializes payment method access caps via EE_Capabilities::init_role_caps()
479
+	 * upon EE_Payment_Method_Manager construction
480
+	 *
481
+	 * @throws EE_Error
482
+	 * @throws DomainException
483
+	 */
484
+	protected function initializePaymentMethodCaps()
485
+	{
486
+		// don't do this twice
487
+		if ($this->payment_method_caps_initialized) {
488
+			return;
489
+		}
490
+		EE_Capabilities::instance()->addCaps(
491
+			$this->getPaymentMethodCaps()
492
+		);
493
+		$this->payment_method_caps_initialized = true;
494
+	}
495
+
496
+
497
+
498
+	/**
499
+	 * array  of dynamic payment method access caps.
500
+	 * at the time of writing, october 20 2014, these are the caps added:
501
+	 *  ee_payment_method_admin_only
502
+	 *  ee_payment_method_aim
503
+	 *  ee_payment_method_bank
504
+	 *  ee_payment_method_check
505
+	 *  ee_payment_method_invoice
506
+	 *  ee_payment_method_mijireh
507
+	 *  ee_payment_method_paypal_pro
508
+	 *  ee_payment_method_paypal_standard
509
+	 * Any other payment methods added to core or via addons will also get
510
+	 * their related capability automatically added too, so long as they are
511
+	 * registered properly using EE_Register_Payment_Method::register()
512
+	 *
513
+	 * @return array
514
+	 * @throws DomainException
515
+	 */
516
+	protected function getPaymentMethodCaps()
517
+	{
518
+		$caps = array();
519
+		foreach ($this->payment_method_type_names() as $payment_method_name) {
520
+			$caps = $this->addPaymentMethodCap($payment_method_name,$caps);
521
+		}
522
+		return $caps;
523
+	}
524
+
525
+
526
+
527
+	/**
528
+	 * @param string $payment_method_name
529
+	 * @param array  $payment_method_caps
530
+	 * @param string $role
531
+	 * @return array
532
+	 * @throws DomainException
533
+	 */
534
+	public function addPaymentMethodCap($payment_method_name, array $payment_method_caps, $role = 'administrator')
535
+	{
536
+		if (empty($payment_method_name)) {
537
+			throw new DomainException(
538
+				esc_html__(
539
+					'The name of a payment method must be specified to add capabilities.',
540
+					'event_espresso'
541
+				)
542
+			);
543
+		}
544
+		if (empty($role)) {
545
+			throw new DomainException(
546
+				sprintf(
547
+					esc_html__(
548
+						'No role was supplied while trying to add capabilities for the %1$s payment method.',
549
+						'event_espresso'
550
+					),
551
+					$payment_method_name
552
+				)
553
+			);
554
+		}
555
+		if(! isset($payment_method_caps[$role])) {
556
+			$payment_method_caps[$role] = array();
557
+		}
558
+		$payment_method_caps[$role][] = EE_Payment_Method_Manager::CAPABILITIES_PREFIX
559
+												  . strtolower($payment_method_name);
560
+		return $payment_method_caps;
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 * callback for FHEE__EE_Capabilities__init_role_caps__caps_map filter
567
+	 * to add dynamic payment method access caps when capabilities are reset
568
+	 * (or if that filter is called and PM caps are not already set)
569
+	 *
570
+	 * @param array $caps capabilities being filtered
571
+	 * @param bool  $reset
572
+	 * @return array
573
+	 * @throws DomainException
574
+	 */
575
+	public function addPaymentMethodCapsDuringReset(array $caps, $reset = false)
576
+	{
577
+		if ($reset || ! $this->payment_method_caps_initialized) {
578
+			$this->payment_method_caps_initialized = true;
579
+			$caps = array_merge_recursive($caps, $this->getPaymentMethodCaps());
580
+		}
581
+		return $caps;
582
+	}
583
+
584
+
585
+
586
+	/**
587
+	 * @deprecated 4.9.42
588
+	 * @param $caps
589
+	 * @return mixed
590
+	 */
591
+	public function add_payment_method_caps($caps)
592
+	{
593
+		return $caps;
594
+	}
595 595
 
596 596
 
597 597
 
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
     /**
25 25
      * prefix added to all payment method capabilities names
26 26
      */
27
-    const   CAPABILITIES_PREFIX= 'ee_payment_method_';
27
+    const   CAPABILITIES_PREFIX = 'ee_payment_method_';
28 28
 
29 29
     /**
30 30
      * @var EE_Payment_Method_Manager $_instance
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
     public static function instance()
81 81
     {
82 82
         // check if class object is instantiated, and instantiated properly
83
-        if (! self::$_instance instanceof EE_Payment_Method_Manager) {
83
+        if ( ! self::$_instance instanceof EE_Payment_Method_Manager) {
84 84
             EE_Registry::instance()->load_lib('PMT_Base');
85 85
             self::$_instance = new self();
86 86
         }
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
      */
114 114
     public function maybe_register_payment_methods($force_recheck = false)
115 115
     {
116
-        if (! $this->_payment_method_types || $force_recheck) {
116
+        if ( ! $this->_payment_method_types || $force_recheck) {
117 117
             $this->_register_payment_methods();
118 118
         }
119 119
     }
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
     protected function _register_payment_methods()
129 129
     {
130 130
         // grab list of installed modules
131
-        $pm_to_register = glob(EE_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
131
+        $pm_to_register = glob(EE_PAYMENT_METHODS.'*', GLOB_ONLYDIR);
132 132
         // filter list of modules to register
133 133
         $pm_to_register = apply_filters(
134 134
             'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
@@ -169,31 +169,31 @@  discard block
 block discarded – undo
169 169
         // create class name from module directory name
170 170
         $module = str_replace(array('_', ' '), array(' ', '_'), $module_dir);
171 171
         // add class prefix
172
-        $module_class = 'EE_PMT_' . $module;
172
+        $module_class = 'EE_PMT_'.$module;
173 173
         // does the module exist ?
174
-        if (! is_readable($payment_method_path . DS . $module_class . $module_ext)) {
174
+        if ( ! is_readable($payment_method_path.DS.$module_class.$module_ext)) {
175 175
             $msg = sprintf(
176 176
                 esc_html__(
177 177
                     'The requested %s payment method file could not be found or is not readable due to file permissions.',
178 178
                     'event_espresso'
179 179
                 ), $module
180 180
             );
181
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
181
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
182 182
             return false;
183 183
         }
184 184
         // load the module class file
185
-        require_once($payment_method_path . DS . $module_class . $module_ext);
185
+        require_once($payment_method_path.DS.$module_class.$module_ext);
186 186
         // verify that class exists
187
-        if (! class_exists($module_class)) {
187
+        if ( ! class_exists($module_class)) {
188 188
             $msg = sprintf(
189 189
                 esc_html__('The requested %s module class does not exist.', 'event_espresso'),
190 190
                 $module_class
191 191
             );
192
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
192
+            EE_Error::add_error($msg.'||'.$msg, __FILE__, __FUNCTION__, __LINE__);
193 193
             return false;
194 194
         }
195 195
         // add to array of registered modules
196
-        $this->_payment_method_types[$module] = $payment_method_path . DS . $module_class . $module_ext;
196
+        $this->_payment_method_types[$module] = $payment_method_path.DS.$module_class.$module_ext;
197 197
         ksort($this->_payment_method_types);
198 198
         return true;
199 199
     }
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
         if ($force_recheck || empty($this->payment_method_objects)) {
262 262
             $this->maybe_register_payment_methods($force_recheck);
263 263
             foreach ($this->payment_method_type_names(true) as $classname) {
264
-                if (! isset($this->payment_method_objects[$classname])) {
264
+                if ( ! isset($this->payment_method_objects[$classname])) {
265 265
                     $this->payment_method_objects[$classname] = new $classname;
266 266
                 }
267 267
             }
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
      */
294 294
     public function payment_method_class_from_type($type)
295 295
     {
296
-        return 'EE_PMT_' . $type;
296
+        return 'EE_PMT_'.$type;
297 297
     }
298 298
 
299 299
 
@@ -310,13 +310,13 @@  discard block
 block discarded – undo
310 310
     {
311 311
         $this->maybe_register_payment_methods();
312 312
         $payment_method = EEM_Payment_Method::instance()->get_one_of_type($payment_method_type);
313
-        if (! $payment_method instanceof EE_Payment_Method) {
313
+        if ( ! $payment_method instanceof EE_Payment_Method) {
314 314
             $pm_type_class = $this->payment_method_class_from_type($payment_method_type);
315 315
             if (class_exists($pm_type_class)) {
316 316
                 /** @var $pm_type_obj EE_PMT_Base */
317 317
                 $pm_type_obj = new $pm_type_class;
318 318
                 $payment_method = EEM_Payment_Method::instance()->get_one_by_slug($pm_type_obj->system_name());
319
-                if (! $payment_method) {
319
+                if ( ! $payment_method) {
320 320
                     $payment_method = $this->create_payment_method_of_type($pm_type_obj);
321 321
                 }
322 322
                 $payment_method->set_type($payment_method_type);
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
                         'The Invoice payment method has been activated. It requires the %1$sinvoice message%2$s type to be active, so it was automatically activated for you.',
353 353
                         'event_espresso'
354 354
                     ),
355
-                    '<a href="' . admin_url('admin.php?page=espresso_messages&action=settings') . '">',
355
+                    '<a href="'.admin_url('admin.php?page=espresso_messages&action=settings').'">',
356 356
                     '</a>'
357 357
                 ),
358 358
                 true
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
                 'PMD_type'       => $pm_type_obj->system_name(),
380 380
                 'PMD_name'       => $pm_type_obj->pretty_name(),
381 381
                 'PMD_admin_name' => $pm_type_obj->pretty_name(),
382
-                'PMD_slug'       => $pm_type_obj->system_name(),//automatically converted to slug
382
+                'PMD_slug'       => $pm_type_obj->system_name(), //automatically converted to slug
383 383
                 'PMD_wp_user'    => $current_user->ID,
384 384
                 'PMD_order'      => EEM_Payment_Method::instance()->count(
385 385
                         array(array('PMD_type' => array('!=', 'Admin_Only')))
@@ -402,14 +402,14 @@  discard block
 block discarded – undo
402 402
     {
403 403
         $pm_type_obj = $payment_method->type_obj();
404 404
         $payment_method->set_description($pm_type_obj->default_description());
405
-        if (! $payment_method->button_url()) {
405
+        if ( ! $payment_method->button_url()) {
406 406
             $payment_method->set_button_url($pm_type_obj->default_button_url());
407 407
         }
408 408
         //now add setup its default extra meta properties
409 409
         $extra_metas = $pm_type_obj->settings_form()->extra_meta_inputs();
410
-        if (! empty($extra_metas)) {
410
+        if ( ! empty($extra_metas)) {
411 411
             //verify the payment method has an ID before adding extra meta
412
-            if (! $payment_method->ID()) {
412
+            if ( ! $payment_method->ID()) {
413 413
                 $payment_method->save();
414 414
             }
415 415
             foreach ($extra_metas as $meta_name => $input) {
@@ -517,7 +517,7 @@  discard block
 block discarded – undo
517 517
     {
518 518
         $caps = array();
519 519
         foreach ($this->payment_method_type_names() as $payment_method_name) {
520
-            $caps = $this->addPaymentMethodCap($payment_method_name,$caps);
520
+            $caps = $this->addPaymentMethodCap($payment_method_name, $caps);
521 521
         }
522 522
         return $caps;
523 523
     }
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
                 )
553 553
             );
554 554
         }
555
-        if(! isset($payment_method_caps[$role])) {
555
+        if ( ! isset($payment_method_caps[$role])) {
556 556
             $payment_method_caps[$role] = array();
557 557
         }
558 558
         $payment_method_caps[$role][] = EE_Payment_Method_Manager::CAPABILITIES_PREFIX
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6176 added lines, -6176 removed lines patch added patch discarded remove patch
@@ -34,6184 +34,6184 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Used to set the $_model_query_blog_id static property.
654
-     *
655
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
-     *                      value for get_current_blog_id() will be used.
657
-     */
658
-    public static function set_model_query_blog_id($blog_id = 0)
659
-    {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
-    }
662
-
663
-
664
-
665
-    /**
666
-     * Returns whatever is set as the internal $model_query_blog_id.
667
-     *
668
-     * @return int
669
-     */
670
-    public static function get_model_query_blog_id()
671
-    {
672
-        return EEM_Base::$_model_query_blog_id;
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * This function is a singleton method used to instantiate the Espresso_model object
679
-     *
680
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
-     *                                (and any incoming timezone data that gets saved).
682
-     *                                Note this just sends the timezone info to the date time model field objects.
683
-     *                                Default is NULL
684
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
-     * @return static (as in the concrete child class)
686
-     * @throws EE_Error
687
-     * @throws InvalidArgumentException
688
-     * @throws InvalidDataTypeException
689
-     * @throws InvalidInterfaceException
690
-     */
691
-    public static function instance($timezone = null)
692
-    {
693
-        // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
695
-            // instantiate Espresso_model
696
-            static::$_instance = new static(
697
-                $timezone,
698
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
-            );
700
-        }
701
-        //we might have a timezone set, let set_timezone decide what to do with it
702
-        static::$_instance->set_timezone($timezone);
703
-        // Espresso_model object
704
-        return static::$_instance;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * resets the model and returns it
711
-     *
712
-     * @param null | string $timezone
713
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
-     * all its properties reset; if it wasn't instantiated, returns null)
715
-     * @throws EE_Error
716
-     * @throws ReflectionException
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidDataTypeException
719
-     * @throws InvalidInterfaceException
720
-     */
721
-    public static function reset($timezone = null)
722
-    {
723
-        if (static::$_instance instanceof EEM_Base) {
724
-            //let's try to NOT swap out the current instance for a new one
725
-            //because if someone has a reference to it, we can't remove their reference
726
-            //so it's best to keep using the same reference, but change the original object
727
-            //reset all its properties to their original values as defined in the class
728
-            $r = new ReflectionClass(get_class(static::$_instance));
729
-            $static_properties = $r->getStaticProperties();
730
-            foreach ($r->getDefaultProperties() as $property => $value) {
731
-                //don't set instance to null like it was originally,
732
-                //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
734
-                    static::$_instance->{$property} = $value;
735
-                }
736
-            }
737
-            //and then directly call its constructor again, like we would if we were creating a new one
738
-            static::$_instance->__construct(
739
-                $timezone,
740
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
-            );
742
-            return self::instance();
743
-        }
744
-        return null;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * @return LoaderInterface
751
-     * @throws InvalidArgumentException
752
-     * @throws InvalidDataTypeException
753
-     * @throws InvalidInterfaceException
754
-     */
755
-    private static function getLoader()
756
-    {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
758
-            EEM_Base::$loader = LoaderFactory::getLoader();
759
-        }
760
-        return EEM_Base::$loader;
761
-    }
762
-
763
-
764
-
765
-    /**
766
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
-     *
768
-     * @param  boolean $translated return localized strings or JUST the array.
769
-     * @return array
770
-     * @throws EE_Error
771
-     * @throws InvalidArgumentException
772
-     * @throws InvalidDataTypeException
773
-     * @throws InvalidInterfaceException
774
-     */
775
-    public function status_array($translated = false)
776
-    {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
778
-            return array();
779
-        }
780
-        $model_name = $this->get_this_model_name();
781
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
-        $status_array = array();
784
-        foreach ($stati as $status) {
785
-            $status_array[$status->ID()] = $status->get('STS_code');
786
-        }
787
-        return $translated
788
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
-            : $status_array;
790
-    }
791
-
792
-
793
-
794
-    /**
795
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
-     *
797
-     * @param array $query_params             {
798
-     * @var array $0 (where) array {
799
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
-     *                                        conditions based on related models (and even
803
-     *                                        models-related-to-related-models) prepend the model's name onto the field
804
-     *                                        name. Eg,
805
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
-     *                                        to Venues (even when each of those models actually consisted of two
813
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
814
-     *                                        just having
815
-     *                                        "Venue.VNU_ID", you could have
816
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
-     *                                        events are related to Registrations, which are related to Attendees). You
818
-     *                                        can take it even further with
819
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
-     *                                        (from the default of '='), change the value to an numerically-indexed
821
-     *                                        array, where the first item in the list is the operator. eg: array(
822
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
830
-     *                                        the value is a field, simply provide a third array item (true) to the
831
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
-     *                                        Note: you can also use related model field names like you would any other
834
-     *                                        field name. eg:
835
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
837
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
844
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
-     *                                        "stick" until you specify an AND. eg
846
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
851
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
-     *                                        too, eg:
854
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
859
-     *                                        the OFFSET, the 2nd is the LIMIT
860
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
-     *                                        following format array('on_join_limit'
863
-     *                                        => array( 'table_alias', array(1,2) ) ).
864
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
-     *                                        values are either 'ASC' or 'DESC'.
866
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
-     *                                        DESC..." respectively. Like the
869
-     *                                        'where' conditions, these fields can be on related models. Eg
870
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
872
-     *                                        Attendee, Price, Datetime, etc.)
873
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
875
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
-     *                                        order by the primary key. Eg,
878
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
-     *                                        //(will join with the Datetime model's table(s) and order by its field
880
-     *                                        DTT_EVT_start) or
881
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
-     *                                        'group_by'=>'VNU_ID', or
885
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
-     *                                        if no
887
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
888
-     *                                        model's primary key (or combined primary keys). This avoids some
889
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
890
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
-     *                                        results)
894
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
-     *                                        array where values are models to be joined in the query.Eg
896
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
898
-     *                                        probably only want to do this in hopes of increasing efficiency, as
899
-     *                                        related models which belongs to the current model
900
-     *                                        (ie, the current model has a foreign key to them, like how Registration
901
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
902
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
905
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
-     *                                        default where conditions set it to 'other_models_only'. If you only want
907
-     *                                        this model's default where conditions added to the query, use
908
-     *                                        'this_model_only'. If you want to use all default where conditions
909
-     *                                        (default), set to 'all'.
910
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
-     *                                        everything? Or should we only show the current user items they should be
913
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
-     *                                        }
916
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
-     *                                        array( array(
922
-     *                                        'OR'=>array(
923
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
-     *                                        )
926
-     *                                        ),
927
-     *                                        'limit'=>10,
928
-     *                                        'group_by'=>'TXN_ID'
929
-     *                                        ));
930
-     *                                        get all the answers to the question titled "shirt size" for event with id
931
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
-     *                                        'Question.QST_display_text'=>'shirt size',
933
-     *                                        'Registration.Event.EVT_ID'=>12
934
-     *                                        ),
935
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
936
-     *                                        ));
937
-     * @throws EE_Error
938
-     */
939
-    public function get_all($query_params = array())
940
-    {
941
-        if (isset($query_params['limit'])
942
-            && ! isset($query_params['group_by'])
943
-        ) {
944
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
-        }
946
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * Modifies the query parameters so we only get back model objects
953
-     * that "belong" to the current user
954
-     *
955
-     * @param array $query_params @see EEM_Base::get_all()
956
-     * @return array like EEM_Base::get_all
957
-     */
958
-    public function alter_query_params_to_only_include_mine($query_params = array())
959
-    {
960
-        $wp_user_field_name = $this->wp_user_field_name();
961
-        if ($wp_user_field_name) {
962
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
963
-        }
964
-        return $query_params;
965
-    }
966
-
967
-
968
-
969
-    /**
970
-     * Returns the name of the field's name that points to the WP_User table
971
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
-     * foreign key to the WP_User table)
973
-     *
974
-     * @return string|boolean string on success, boolean false when there is no
975
-     * foreign key to the WP_User table
976
-     */
977
-    public function wp_user_field_name()
978
-    {
979
-        try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
981
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
-                $last_model_name = end($models_to_follow_to_wp_users);
983
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
-            } else {
986
-                $model_with_fk_to_wp_users = $this;
987
-                $model_chain_to_wp_user = '';
988
-            }
989
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
991
-        } catch (EE_Error $e) {
992
-            return false;
993
-        }
994
-    }
995
-
996
-
997
-
998
-    /**
999
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
-     * (or transiently-related model) has a foreign key to the wp_users table;
1001
-     * useful for finding if model objects of this type are 'owned' by the current user.
1002
-     * This is an empty string when the foreign key is on this model and when it isn't,
1003
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
-     * (or transiently-related model)
1005
-     *
1006
-     * @return string
1007
-     */
1008
-    public function model_chain_to_wp_user()
1009
-    {
1010
-        return $this->_model_chain_to_wp_user;
1011
-    }
1012
-
1013
-
1014
-
1015
-    /**
1016
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
-     * like how registrations don't have a foreign key to wp_users, but the
1018
-     * events they are for are), or is unrelated to wp users.
1019
-     * generally available
1020
-     *
1021
-     * @return boolean
1022
-     */
1023
-    public function is_owned()
1024
-    {
1025
-        if ($this->model_chain_to_wp_user()) {
1026
-            return true;
1027
-        }
1028
-        try {
1029
-            $this->get_foreign_key_to('WP_User');
1030
-            return true;
1031
-        } catch (EE_Error $e) {
1032
-            return false;
1033
-        }
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
-     * the model)
1041
-     *
1042
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1046
-     *                                  override this and set the select to "*", or a specific column name, like
1047
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
-     *                                  the aliases used to refer to this selection, and values are to be
1050
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
-     * @throws EE_Error
1054
-     * @throws InvalidArgumentException
1055
-     */
1056
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
-    {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
-        $select_expressions = $columns_to_select === null
1061
-            ? $this->_construct_default_select_sql($model_query_info)
1062
-            : '';
1063
-        if ($this->_custom_selections instanceof CustomSelects) {
1064
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
-            $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1067
-                : $custom_expressions;
1068
-        }
1069
-
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
-     * method of including extra select information.
1079
-     *
1080
-     * @param array             $query_params
1081
-     * @param null|array|string $columns_to_select
1082
-     * @return null|CustomSelects
1083
-     * @throws InvalidArgumentException
1084
-     */
1085
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
-    {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
-            return null;
1089
-        }
1090
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
-        return new CustomSelects($selects);
1093
-    }
1094
-
1095
-
1096
-
1097
-    /**
1098
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1099
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
-     * take care of joins, field preparation etc.
1101
-     *
1102
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1106
-     *                                  override this and set the select to "*", or a specific column name, like
1107
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
-     *                                  the aliases used to refer to this selection, and values are to be
1110
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
-    {
1117
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
-    }
1119
-
1120
-
1121
-
1122
-    /**
1123
-     * For creating a custom select statement
1124
-     *
1125
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
-     *                                 SQL, and 1=>is the datatype
1128
-     * @throws EE_Error
1129
-     * @return string
1130
-     */
1131
-    private function _construct_select_from_input($columns_to_select)
1132
-    {
1133
-        if (is_array($columns_to_select)) {
1134
-            $select_sql_array = array();
1135
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
-                    throw new EE_Error(
1138
-                        sprintf(
1139
-                            __(
1140
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
-                                'event_espresso'
1142
-                            ),
1143
-                            $selection_and_datatype,
1144
-                            $alias
1145
-                        )
1146
-                    );
1147
-                }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
-                    throw new EE_Error(
1150
-                        sprintf(
1151
-                            esc_html__(
1152
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
-                                'event_espresso'
1154
-                            ),
1155
-                            $selection_and_datatype[1],
1156
-                            $selection_and_datatype[0],
1157
-                            $alias,
1158
-                            implode(', ', $this->_valid_wpdb_data_types)
1159
-                        )
1160
-                    );
1161
-                }
1162
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
-            }
1164
-            $columns_to_select_string = implode(', ', $select_sql_array);
1165
-        } else {
1166
-            $columns_to_select_string = $columns_to_select;
1167
-        }
1168
-        return $columns_to_select_string;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
-     *
1176
-     * @return string
1177
-     * @throws EE_Error
1178
-     */
1179
-    public function primary_key_name()
1180
-    {
1181
-        return $this->get_primary_key_field()->get_name();
1182
-    }
1183
-
1184
-
1185
-
1186
-    /**
1187
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
-     * If there is no primary key on this model, $id is treated as primary key string
1189
-     *
1190
-     * @param mixed $id int or string, depending on the type of the model's primary key
1191
-     * @return EE_Base_Class
1192
-     */
1193
-    public function get_one_by_ID($id)
1194
-    {
1195
-        if ($this->get_from_entity_map($id)) {
1196
-            return $this->get_from_entity_map($id);
1197
-        }
1198
-        return $this->get_one(
1199
-            $this->alter_query_params_to_restrict_by_ID(
1200
-                $id,
1201
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
-            )
1203
-        );
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * Alters query parameters to only get items with this ID are returned.
1210
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
-     * or could just be a simple primary key ID
1212
-     *
1213
-     * @param int   $id
1214
-     * @param array $query_params
1215
-     * @return array of normal query params, @see EEM_Base::get_all
1216
-     * @throws EE_Error
1217
-     */
1218
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
-    {
1220
-        if (! isset($query_params[0])) {
1221
-            $query_params[0] = array();
1222
-        }
1223
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1224
-        if ($conditions_from_id === null) {
1225
-            $query_params[0][$this->primary_key_name()] = $id;
1226
-        } else {
1227
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1228
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
-        }
1230
-        return $query_params;
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
-     * array. If no item is found, null is returned.
1238
-     *
1239
-     * @param array $query_params like EEM_Base's $query_params variable.
1240
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
-     * @throws EE_Error
1242
-     */
1243
-    public function get_one($query_params = array())
1244
-    {
1245
-        if (! is_array($query_params)) {
1246
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
-                    gettype($query_params)), '4.6.0');
1249
-            $query_params = array();
1250
-        }
1251
-        $query_params['limit'] = 1;
1252
-        $items = $this->get_all($query_params);
1253
-        if (empty($items)) {
1254
-            return null;
1255
-        }
1256
-        return array_shift($items);
1257
-    }
1258
-
1259
-
1260
-
1261
-    /**
1262
-     * Returns the next x number of items in sequence from the given value as
1263
-     * found in the database matching the given query conditions.
1264
-     *
1265
-     * @param mixed $current_field_value    Value used for the reference point.
1266
-     * @param null  $field_to_order_by      What field is used for the
1267
-     *                                      reference point.
1268
-     * @param int   $limit                  How many to return.
1269
-     * @param array $query_params           Extra conditions on the query.
1270
-     * @param null  $columns_to_select      If left null, then an array of
1271
-     *                                      EE_Base_Class objects is returned,
1272
-     *                                      otherwise you can indicate just the
1273
-     *                                      columns you want returned.
1274
-     * @return EE_Base_Class[]|array
1275
-     * @throws EE_Error
1276
-     */
1277
-    public function next_x(
1278
-        $current_field_value,
1279
-        $field_to_order_by = null,
1280
-        $limit = 1,
1281
-        $query_params = array(),
1282
-        $columns_to_select = null
1283
-    ) {
1284
-        return $this->_get_consecutive(
1285
-            $current_field_value,
1286
-            '>',
1287
-            $field_to_order_by,
1288
-            $limit,
1289
-            $query_params,
1290
-            $columns_to_select
1291
-        );
1292
-    }
1293
-
1294
-
1295
-
1296
-    /**
1297
-     * Returns the previous x number of items in sequence from the given value
1298
-     * as found in the database matching the given query conditions.
1299
-     *
1300
-     * @param mixed $current_field_value    Value used for the reference point.
1301
-     * @param null  $field_to_order_by      What field is used for the
1302
-     *                                      reference point.
1303
-     * @param int   $limit                  How many to return.
1304
-     * @param array $query_params           Extra conditions on the query.
1305
-     * @param null  $columns_to_select      If left null, then an array of
1306
-     *                                      EE_Base_Class objects is returned,
1307
-     *                                      otherwise you can indicate just the
1308
-     *                                      columns you want returned.
1309
-     * @return EE_Base_Class[]|array
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function previous_x(
1313
-        $current_field_value,
1314
-        $field_to_order_by = null,
1315
-        $limit = 1,
1316
-        $query_params = array(),
1317
-        $columns_to_select = null
1318
-    ) {
1319
-        return $this->_get_consecutive(
1320
-            $current_field_value,
1321
-            '<',
1322
-            $field_to_order_by,
1323
-            $limit,
1324
-            $query_params,
1325
-            $columns_to_select
1326
-        );
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * Returns the next item in sequence from the given value as found in the
1333
-     * database matching the given query conditions.
1334
-     *
1335
-     * @param mixed $current_field_value    Value used for the reference point.
1336
-     * @param null  $field_to_order_by      What field is used for the
1337
-     *                                      reference point.
1338
-     * @param array $query_params           Extra conditions on the query.
1339
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
-     *                                      object is returned, otherwise you
1341
-     *                                      can indicate just the columns you
1342
-     *                                      want and a single array indexed by
1343
-     *                                      the columns will be returned.
1344
-     * @return EE_Base_Class|null|array()
1345
-     * @throws EE_Error
1346
-     */
1347
-    public function next(
1348
-        $current_field_value,
1349
-        $field_to_order_by = null,
1350
-        $query_params = array(),
1351
-        $columns_to_select = null
1352
-    ) {
1353
-        $results = $this->_get_consecutive(
1354
-            $current_field_value,
1355
-            '>',
1356
-            $field_to_order_by,
1357
-            1,
1358
-            $query_params,
1359
-            $columns_to_select
1360
-        );
1361
-        return empty($results) ? null : reset($results);
1362
-    }
1363
-
1364
-
1365
-
1366
-    /**
1367
-     * Returns the previous item in sequence from the given value as found in
1368
-     * the database matching the given query conditions.
1369
-     *
1370
-     * @param mixed $current_field_value    Value used for the reference point.
1371
-     * @param null  $field_to_order_by      What field is used for the
1372
-     *                                      reference point.
1373
-     * @param array $query_params           Extra conditions on the query.
1374
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
-     *                                      object is returned, otherwise you
1376
-     *                                      can indicate just the columns you
1377
-     *                                      want and a single array indexed by
1378
-     *                                      the columns will be returned.
1379
-     * @return EE_Base_Class|null|array()
1380
-     * @throws EE_Error
1381
-     */
1382
-    public function previous(
1383
-        $current_field_value,
1384
-        $field_to_order_by = null,
1385
-        $query_params = array(),
1386
-        $columns_to_select = null
1387
-    ) {
1388
-        $results = $this->_get_consecutive(
1389
-            $current_field_value,
1390
-            '<',
1391
-            $field_to_order_by,
1392
-            1,
1393
-            $query_params,
1394
-            $columns_to_select
1395
-        );
1396
-        return empty($results) ? null : reset($results);
1397
-    }
1398
-
1399
-
1400
-
1401
-    /**
1402
-     * Returns the a consecutive number of items in sequence from the given
1403
-     * value as found in the database matching the given query conditions.
1404
-     *
1405
-     * @param mixed  $current_field_value   Value used for the reference point.
1406
-     * @param string $operand               What operand is used for the sequence.
1407
-     * @param string $field_to_order_by     What field is used for the reference point.
1408
-     * @param int    $limit                 How many to return.
1409
-     * @param array  $query_params          Extra conditions on the query.
1410
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
-     *                                      otherwise you can indicate just the columns you want returned.
1412
-     * @return EE_Base_Class[]|array
1413
-     * @throws EE_Error
1414
-     */
1415
-    protected function _get_consecutive(
1416
-        $current_field_value,
1417
-        $operand = '>',
1418
-        $field_to_order_by = null,
1419
-        $limit = 1,
1420
-        $query_params = array(),
1421
-        $columns_to_select = null
1422
-    ) {
1423
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
-        if (empty($field_to_order_by)) {
1425
-            if ($this->has_primary_key_field()) {
1426
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1427
-            } else {
1428
-                if (WP_DEBUG) {
1429
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1430
-                        'event_espresso'));
1431
-                }
1432
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
-                return array();
1434
-            }
1435
-        }
1436
-        if (! is_array($query_params)) {
1437
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
-                    gettype($query_params)), '4.6.0');
1440
-            $query_params = array();
1441
-        }
1442
-        //let's add the where query param for consecutive look up.
1443
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
-        $query_params['limit'] = $limit;
1445
-        //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
-        $query_params['order_by'] = $operand === '>'
1448
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
-        if (empty($columns_to_select)) {
1452
-            return $this->get_all($query_params);
1453
-        }
1454
-        //getting just the fields
1455
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This sets the _timezone property after model object has been instantiated.
1462
-     *
1463
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
-     */
1465
-    public function set_timezone($timezone)
1466
-    {
1467
-        if ($timezone !== null) {
1468
-            $this->_timezone = $timezone;
1469
-        }
1470
-        //note we need to loop through relations and set the timezone on those objects as well.
1471
-        foreach ($this->_model_relations as $relation) {
1472
-            $relation->set_timezone($timezone);
1473
-        }
1474
-        //and finally we do the same for any datetime fields
1475
-        foreach ($this->_fields as $field) {
1476
-            if ($field instanceof EE_Datetime_Field) {
1477
-                $field->set_timezone($timezone);
1478
-            }
1479
-        }
1480
-    }
1481
-
1482
-
1483
-
1484
-    /**
1485
-     * This just returns whatever is set for the current timezone.
1486
-     *
1487
-     * @access public
1488
-     * @return string
1489
-     */
1490
-    public function get_timezone()
1491
-    {
1492
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
-        if (empty($this->_timezone)) {
1494
-            foreach ($this->_fields as $field) {
1495
-                if ($field instanceof EE_Datetime_Field) {
1496
-                    $this->set_timezone($field->get_timezone());
1497
-                    break;
1498
-                }
1499
-            }
1500
-        }
1501
-        //if timezone STILL empty then return the default timezone for the site.
1502
-        if (empty($this->_timezone)) {
1503
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
-        }
1505
-        return $this->_timezone;
1506
-    }
1507
-
1508
-
1509
-
1510
-    /**
1511
-     * This returns the date formats set for the given field name and also ensures that
1512
-     * $this->_timezone property is set correctly.
1513
-     *
1514
-     * @since 4.6.x
1515
-     * @param string $field_name The name of the field the formats are being retrieved for.
1516
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
-     * @return array formats in an array with the date format first, and the time format last.
1519
-     */
1520
-    public function get_formats_for($field_name, $pretty = false)
1521
-    {
1522
-        $field_settings = $this->field_settings_for($field_name);
1523
-        //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1525
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1526
-                'event_espresso'), $field_name));
1527
-        }
1528
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
-        //the field.
1530
-        $this->_timezone = $field_settings->get_timezone();
1531
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
-    }
1533
-
1534
-
1535
-
1536
-    /**
1537
-     * This returns the current time in a format setup for a query on this model.
1538
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
-     * it will return:
1540
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
-     *  NOW
1542
-     *  - or a unix timestamp (equivalent to time())
1543
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
-     * @since 4.6.x
1547
-     * @param string $field_name       The field the current time is needed for.
1548
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
-     *                                 formatted string matching the set format for the field in the set timezone will
1550
-     *                                 be returned.
1551
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
-     *                                 exception is triggered.
1555
-     */
1556
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
-    {
1558
-        $formats = $this->get_formats_for($field_name);
1559
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
-        if ($timestamp) {
1561
-            return $DateTime->format('U');
1562
-        }
1563
-        //not returning timestamp, so return formatted string in timezone.
1564
-        switch ($what) {
1565
-            case 'time' :
1566
-                return $DateTime->format($formats[1]);
1567
-                break;
1568
-            case 'date' :
1569
-                return $DateTime->format($formats[0]);
1570
-                break;
1571
-            default :
1572
-                return $DateTime->format(implode(' ', $formats));
1573
-                break;
1574
-        }
1575
-    }
1576
-
1577
-
1578
-
1579
-    /**
1580
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
-     * for the model are.  Returns a DateTime object.
1582
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
-     * ignored.
1585
-     *
1586
-     * @param string $field_name      The field being setup.
1587
-     * @param string $timestring      The date time string being used.
1588
-     * @param string $incoming_format The format for the time string.
1589
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
-     *                                format is
1592
-     *                                'U', this is ignored.
1593
-     * @return DateTime
1594
-     * @throws EE_Error
1595
-     */
1596
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
-    {
1598
-        //just using this to ensure the timezone is set correctly internally
1599
-        $this->get_formats_for($field_name);
1600
-        //load EEH_DTT_Helper
1601
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1604
-    }
1605
-
1606
-
1607
-
1608
-    /**
1609
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1610
-     *
1611
-     * @return EE_Table_Base[]
1612
-     */
1613
-    public function get_tables()
1614
-    {
1615
-        return $this->_tables;
1616
-    }
1617
-
1618
-
1619
-
1620
-    /**
1621
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1622
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1623
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1624
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1625
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1626
-     * model object with EVT_ID = 1
1627
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1628
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1629
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1630
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1631
-     * are not specified)
1632
-     *
1633
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1634
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1635
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1636
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1637
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1638
-     *                                         ID=34, we'd use this method as follows:
1639
-     *                                         EEM_Transaction::instance()->update(
1640
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1641
-     *                                         array(array('TXN_ID'=>34)));
1642
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1643
-     *                                         in client code into what's expected to be stored on each field. Eg,
1644
-     *                                         consider updating Question's QST_admin_label field is of type
1645
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1646
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1647
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1648
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1649
-     *                                         TRUE, it is assumed that you've already called
1650
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1651
-     *                                         malicious javascript. However, if
1652
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1653
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1654
-     *                                         and every other field, before insertion. We provide this parameter
1655
-     *                                         because model objects perform their prepare_for_set function on all
1656
-     *                                         their values, and so don't need to be called again (and in many cases,
1657
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1658
-     *                                         prepare_for_set method...)
1659
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1660
-     *                                         in this model's entity map according to $fields_n_values that match
1661
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1662
-     *                                         by setting this to FALSE, but be aware that model objects being used
1663
-     *                                         could get out-of-sync with the database
1664
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1665
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1666
-     *                                         bad)
1667
-     * @throws EE_Error
1668
-     */
1669
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1670
-    {
1671
-        if (! is_array($query_params)) {
1672
-            EE_Error::doing_it_wrong('EEM_Base::update',
1673
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1674
-                    gettype($query_params)), '4.6.0');
1675
-            $query_params = array();
1676
-        }
1677
-        /**
1678
-         * Action called before a model update call has been made.
1679
-         *
1680
-         * @param EEM_Base $model
1681
-         * @param array    $fields_n_values the updated fields and their new values
1682
-         * @param array    $query_params    @see EEM_Base::get_all()
1683
-         */
1684
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1685
-        /**
1686
-         * Filters the fields about to be updated given the query parameters. You can provide the
1687
-         * $query_params to $this->get_all() to find exactly which records will be updated
1688
-         *
1689
-         * @param array    $fields_n_values fields and their new values
1690
-         * @param EEM_Base $model           the model being queried
1691
-         * @param array    $query_params    see EEM_Base::get_all()
1692
-         */
1693
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1694
-            $query_params);
1695
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1696
-        //to do that, for each table, verify that it's PK isn't null.
1697
-        $tables = $this->get_tables();
1698
-        //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
1699
-        //NOTE: we should make this code more efficient by NOT querying twice
1700
-        //before the real update, but that needs to first go through ALPHA testing
1701
-        //as it's dangerous. says Mike August 8 2014
1702
-        //we want to make sure the default_where strategy is ignored
1703
-        $this->_ignore_where_strategy = true;
1704
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1705
-        foreach ($wpdb_select_results as $wpdb_result) {
1706
-            // type cast stdClass as array
1707
-            $wpdb_result = (array)$wpdb_result;
1708
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1709
-            if ($this->has_primary_key_field()) {
1710
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1711
-            } else {
1712
-                //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)
1713
-                $main_table_pk_value = null;
1714
-            }
1715
-            //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
1716
-            //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
1717
-            if (count($tables) > 1) {
1718
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1719
-                //in that table, and so we'll want to insert one
1720
-                foreach ($tables as $table_obj) {
1721
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1722
-                    //if there is no private key for this table on the results, it means there's no entry
1723
-                    //in this table, right? so insert a row in the current table, using any fields available
1724
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1725
-                           && $wpdb_result[$this_table_pk_column])
1726
-                    ) {
1727
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1728
-                            $main_table_pk_value);
1729
-                        //if we died here, report the error
1730
-                        if (! $success) {
1731
-                            return false;
1732
-                        }
1733
-                    }
1734
-                }
1735
-            }
1736
-            //				//and now check that if we have cached any models by that ID on the model, that
1737
-            //				//they also get updated properly
1738
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1739
-            //				if( $model_object ){
1740
-            //					foreach( $fields_n_values as $field => $value ){
1741
-            //						$model_object->set($field, $value);
1742
-            //let's make sure default_where strategy is followed now
1743
-            $this->_ignore_where_strategy = false;
1744
-        }
1745
-        //if we want to keep model objects in sync, AND
1746
-        //if this wasn't called from a model object (to update itself)
1747
-        //then we want to make sure we keep all the existing
1748
-        //model objects in sync with the db
1749
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1750
-            if ($this->has_primary_key_field()) {
1751
-                $model_objs_affected_ids = $this->get_col($query_params);
1752
-            } else {
1753
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1754
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1755
-                $model_objs_affected_ids = array();
1756
-                foreach ($models_affected_key_columns as $row) {
1757
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1758
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1759
-                }
1760
-            }
1761
-            if (! $model_objs_affected_ids) {
1762
-                //wait wait wait- if nothing was affected let's stop here
1763
-                return 0;
1764
-            }
1765
-            foreach ($model_objs_affected_ids as $id) {
1766
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1767
-                if ($model_obj_in_entity_map) {
1768
-                    foreach ($fields_n_values as $field => $new_value) {
1769
-                        $model_obj_in_entity_map->set($field, $new_value);
1770
-                    }
1771
-                }
1772
-            }
1773
-            //if there is a primary key on this model, we can now do a slight optimization
1774
-            if ($this->has_primary_key_field()) {
1775
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1776
-                $query_params = array(
1777
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1778
-                    'limit'                    => count($model_objs_affected_ids),
1779
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1780
-                );
1781
-            }
1782
-        }
1783
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1784
-        $SQL = "UPDATE "
1785
-               . $model_query_info->get_full_join_sql()
1786
-               . " SET "
1787
-               . $this->_construct_update_sql($fields_n_values)
1788
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1789
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1790
-        /**
1791
-         * Action called after a model update call has been made.
1792
-         *
1793
-         * @param EEM_Base $model
1794
-         * @param array    $fields_n_values the updated fields and their new values
1795
-         * @param array    $query_params    @see EEM_Base::get_all()
1796
-         * @param int      $rows_affected
1797
-         */
1798
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1799
-        return $rows_affected;//how many supposedly got updated
1800
-    }
1801
-
1802
-
1803
-
1804
-    /**
1805
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1806
-     * are teh values of the field specified (or by default the primary key field)
1807
-     * that matched the query params. Note that you should pass the name of the
1808
-     * model FIELD, not the database table's column name.
1809
-     *
1810
-     * @param array  $query_params @see EEM_Base::get_all()
1811
-     * @param string $field_to_select
1812
-     * @return array just like $wpdb->get_col()
1813
-     * @throws EE_Error
1814
-     */
1815
-    public function get_col($query_params = array(), $field_to_select = null)
1816
-    {
1817
-        if ($field_to_select) {
1818
-            $field = $this->field_settings_for($field_to_select);
1819
-        } elseif ($this->has_primary_key_field()) {
1820
-            $field = $this->get_primary_key_field();
1821
-        } else {
1822
-            //no primary key, just grab the first column
1823
-            $field = reset($this->field_settings());
1824
-        }
1825
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1826
-        $select_expressions = $field->get_qualified_column();
1827
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1828
-        return $this->_do_wpdb_query('get_col', array($SQL));
1829
-    }
1830
-
1831
-
1832
-
1833
-    /**
1834
-     * Returns a single column value for a single row from the database
1835
-     *
1836
-     * @param array  $query_params    @see EEM_Base::get_all()
1837
-     * @param string $field_to_select @see EEM_Base::get_col()
1838
-     * @return string
1839
-     * @throws EE_Error
1840
-     */
1841
-    public function get_var($query_params = array(), $field_to_select = null)
1842
-    {
1843
-        $query_params['limit'] = 1;
1844
-        $col = $this->get_col($query_params, $field_to_select);
1845
-        if (! empty($col)) {
1846
-            return reset($col);
1847
-        }
1848
-        return null;
1849
-    }
1850
-
1851
-
1852
-
1853
-    /**
1854
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1855
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1856
-     * injection, but currently no further filtering is done
1857
-     *
1858
-     * @global      $wpdb
1859
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1860
-     *                               be updated to in the DB
1861
-     * @return string of SQL
1862
-     * @throws EE_Error
1863
-     */
1864
-    public function _construct_update_sql($fields_n_values)
1865
-    {
1866
-        /** @type WPDB $wpdb */
1867
-        global $wpdb;
1868
-        $cols_n_values = array();
1869
-        foreach ($fields_n_values as $field_name => $value) {
1870
-            $field_obj = $this->field_settings_for($field_name);
1871
-            //if the value is NULL, we want to assign the value to that.
1872
-            //wpdb->prepare doesn't really handle that properly
1873
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1874
-            $value_sql = $prepared_value === null ? 'NULL'
1875
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1876
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1877
-        }
1878
-        return implode(",", $cols_n_values);
1879
-    }
1880
-
1881
-
1882
-
1883
-    /**
1884
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1885
-     * Performs a HARD delete, meaning the database row should always be removed,
1886
-     * not just have a flag field on it switched
1887
-     * Wrapper for EEM_Base::delete_permanently()
1888
-     *
1889
-     * @param mixed $id
1890
-     * @param boolean $allow_blocking
1891
-     * @return int the number of rows deleted
1892
-     * @throws EE_Error
1893
-     */
1894
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1895
-    {
1896
-        return $this->delete_permanently(
1897
-            array(
1898
-                array($this->get_primary_key_field()->get_name() => $id),
1899
-                'limit' => 1,
1900
-            ),
1901
-            $allow_blocking
1902
-        );
1903
-    }
1904
-
1905
-
1906
-
1907
-    /**
1908
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1909
-     * Wrapper for EEM_Base::delete()
1910
-     *
1911
-     * @param mixed $id
1912
-     * @param boolean $allow_blocking
1913
-     * @return int the number of rows deleted
1914
-     * @throws EE_Error
1915
-     */
1916
-    public function delete_by_ID($id, $allow_blocking = true)
1917
-    {
1918
-        return $this->delete(
1919
-            array(
1920
-                array($this->get_primary_key_field()->get_name() => $id),
1921
-                'limit' => 1,
1922
-            ),
1923
-            $allow_blocking
1924
-        );
1925
-    }
1926
-
1927
-
1928
-
1929
-    /**
1930
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1931
-     * meaning if the model has a field that indicates its been "trashed" or
1932
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1933
-     *
1934
-     * @see EEM_Base::delete_permanently
1935
-     * @param array   $query_params
1936
-     * @param boolean $allow_blocking
1937
-     * @return int how many rows got deleted
1938
-     * @throws EE_Error
1939
-     */
1940
-    public function delete($query_params, $allow_blocking = true)
1941
-    {
1942
-        return $this->delete_permanently($query_params, $allow_blocking);
1943
-    }
1944
-
1945
-
1946
-
1947
-    /**
1948
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1949
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1950
-     * as archived, not actually deleted
1951
-     *
1952
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1953
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1954
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1955
-     *                                deletes regardless of other objects which may depend on it. Its generally
1956
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1957
-     *                                DB
1958
-     * @return int how many rows got deleted
1959
-     * @throws EE_Error
1960
-     */
1961
-    public function delete_permanently($query_params, $allow_blocking = true)
1962
-    {
1963
-        /**
1964
-         * Action called just before performing a real deletion query. You can use the
1965
-         * model and its $query_params to find exactly which items will be deleted
1966
-         *
1967
-         * @param EEM_Base $model
1968
-         * @param array    $query_params   @see EEM_Base::get_all()
1969
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1970
-         *                                 to block (prevent) this deletion
1971
-         */
1972
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1973
-        //some MySQL databases may be running safe mode, which may restrict
1974
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1975
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1976
-        //to delete them
1977
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1978
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1979
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1980
-            $columns_and_ids_for_deleting
1981
-        );
1982
-        /**
1983
-         * Allows client code to act on the items being deleted before the query is actually executed.
1984
-         *
1985
-         * @param EEM_Base $this  The model instance being acted on.
1986
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1987
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1988
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1989
-         *                                                  derived from the incoming query parameters.
1990
-         *                                                  @see details on the structure of this array in the phpdocs
1991
-         *                                                  for the `_get_ids_for_delete_method`
1992
-         *
1993
-         */
1994
-        do_action('AHEE__EEM_Base__delete__before_query',
1995
-            $this,
1996
-            $query_params,
1997
-            $allow_blocking,
1998
-            $columns_and_ids_for_deleting
1999
-        );
2000
-        if ($deletion_where_query_part) {
2001
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2002
-            $table_aliases = array_keys($this->_tables);
2003
-            $SQL = "DELETE "
2004
-                   . implode(", ", $table_aliases)
2005
-                   . " FROM "
2006
-                   . $model_query_info->get_full_join_sql()
2007
-                   . " WHERE "
2008
-                   . $deletion_where_query_part;
2009
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2010
-        } else {
2011
-            $rows_deleted = 0;
2012
-        }
2013
-
2014
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2015
-        //there was no error with the delete query.
2016
-        if ($this->has_primary_key_field()
2017
-            && $rows_deleted !== false
2018
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2019
-        ) {
2020
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2021
-            foreach ($ids_for_removal as $id) {
2022
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2023
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2024
-                }
2025
-            }
2026
-
2027
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2028
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2029
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2030
-            // (although it is possible).
2031
-            //Note this can be skipped by using the provided filter and returning false.
2032
-            if (apply_filters(
2033
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2034
-                ! $this instanceof EEM_Extra_Meta,
2035
-                $this
2036
-            )) {
2037
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2038
-                    0 => array(
2039
-                        'EXM_type' => $this->get_this_model_name(),
2040
-                        'OBJ_ID'   => array(
2041
-                            'IN',
2042
-                            $ids_for_removal
2043
-                        )
2044
-                    )
2045
-                ));
2046
-            }
2047
-        }
2048
-
2049
-        /**
2050
-         * Action called just after performing a real deletion query. Although at this point the
2051
-         * items should have been deleted
2052
-         *
2053
-         * @param EEM_Base $model
2054
-         * @param array    $query_params @see EEM_Base::get_all()
2055
-         * @param int      $rows_deleted
2056
-         */
2057
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
-        return $rows_deleted;//how many supposedly got deleted
2059
-    }
2060
-
2061
-
2062
-
2063
-    /**
2064
-     * Checks all the relations that throw error messages when there are blocking related objects
2065
-     * for related model objects. If there are any related model objects on those relations,
2066
-     * adds an EE_Error, and return true
2067
-     *
2068
-     * @param EE_Base_Class|int $this_model_obj_or_id
2069
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2070
-     *                                                 should be ignored when determining whether there are related
2071
-     *                                                 model objects which block this model object's deletion. Useful
2072
-     *                                                 if you know A is related to B and are considering deleting A,
2073
-     *                                                 but want to see if A has any other objects blocking its deletion
2074
-     *                                                 before removing the relation between A and B
2075
-     * @return boolean
2076
-     * @throws EE_Error
2077
-     */
2078
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
-    {
2080
-        //first, if $ignore_this_model_obj was supplied, get its model
2081
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
-            $ignored_model = $ignore_this_model_obj->get_model();
2083
-        } else {
2084
-            $ignored_model = null;
2085
-        }
2086
-        //now check all the relations of $this_model_obj_or_id and see if there
2087
-        //are any related model objects blocking it?
2088
-        $is_blocked = false;
2089
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2091
-                //if $ignore_this_model_obj was supplied, then for the query
2092
-                //on that model needs to be told to ignore $ignore_this_model_obj
2093
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2095
-                        array(
2096
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2097
-                                '!=',
2098
-                                $ignore_this_model_obj->ID(),
2099
-                            ),
2100
-                        ),
2101
-                    ));
2102
-                } else {
2103
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2104
-                }
2105
-                if ($related_model_objects) {
2106
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2107
-                    $is_blocked = true;
2108
-                }
2109
-            }
2110
-        }
2111
-        return $is_blocked;
2112
-    }
2113
-
2114
-
2115
-    /**
2116
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2117
-     * @param array $row_results_for_deleting
2118
-     * @param bool  $allow_blocking
2119
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2120
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2121
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2122
-     *                 deleted. Example:
2123
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2124
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2125
-     *                 where each element is a group of columns and values that get deleted. Example:
2126
-     *                      array(
2127
-     *                          0 => array(
2128
-     *                              'Term_Relationship.object_id' => 1
2129
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2130
-     *                          ),
2131
-     *                          1 => array(
2132
-     *                              'Term_Relationship.object_id' => 1
2133
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2134
-     *                          )
2135
-     *                      )
2136
-     * @throws EE_Error
2137
-     */
2138
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2139
-    {
2140
-        $ids_to_delete_indexed_by_column = array();
2141
-        if ($this->has_primary_key_field()) {
2142
-            $primary_table = $this->_get_main_table();
2143
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2144
-            $other_tables = $this->_get_other_tables();
2145
-            $ids_to_delete_indexed_by_column = $query = array();
2146
-            foreach ($row_results_for_deleting as $item_to_delete) {
2147
-                //before we mark this item for deletion,
2148
-                //make sure there's no related entities blocking its deletion (if we're checking)
2149
-                if (
2150
-                    $allow_blocking
2151
-                    && $this->delete_is_blocked_by_related_models(
2152
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2153
-                    )
2154
-                ) {
2155
-                    continue;
2156
-                }
2157
-                //primary table deletes
2158
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2159
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2160
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2161
-                }
2162
-            }
2163
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2164
-            $fields = $this->get_combined_primary_key_fields();
2165
-            foreach ($row_results_for_deleting as $item_to_delete) {
2166
-                $ids_to_delete_indexed_by_column_for_row = array();
2167
-                foreach ($fields as $cpk_field) {
2168
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2169
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2170
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2171
-                    }
2172
-                }
2173
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2174
-            }
2175
-        } else {
2176
-            //so there's no primary key and no combined key...
2177
-            //sorry, can't help you
2178
-            throw new EE_Error(
2179
-                sprintf(
2180
-                    __(
2181
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2182
-                        "event_espresso"
2183
-                    ), get_class($this)
2184
-                )
2185
-            );
2186
-        }
2187
-        return $ids_to_delete_indexed_by_column;
2188
-    }
2189
-
2190
-
2191
-    /**
2192
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2193
-     * the corresponding query_part for the query performing the delete.
2194
-     *
2195
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2196
-     * @return string
2197
-     * @throws EE_Error
2198
-     */
2199
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2200
-        $query_part = '';
2201
-        if (empty($ids_to_delete_indexed_by_column)) {
2202
-            return $query_part;
2203
-        } elseif ($this->has_primary_key_field()) {
2204
-            $query = array();
2205
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2206
-                //make sure we have unique $ids
2207
-                $ids = array_unique($ids);
2208
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2209
-            }
2210
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2211
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2212
-            $ways_to_identify_a_row = array();
2213
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2214
-                $values_for_each_combined_primary_key_for_a_row = array();
2215
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2216
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2217
-                }
2218
-                $ways_to_identify_a_row[] = '('
2219
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2220
-                                            . ')';
2221
-            }
2222
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2223
-        }
2224
-        return $query_part;
2225
-    }
2226
-
2227
-
2228
-
2229
-    /**
2230
-     * Gets the model field by the fully qualified name
2231
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2232
-     * @return EE_Model_Field_Base
2233
-     */
2234
-    public function get_field_by_column($qualified_column_name)
2235
-    {
2236
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2237
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2238
-               return $field_obj;
2239
-           }
2240
-       }
2241
-        throw new EE_Error(
2242
-            sprintf(
2243
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2244
-                $this->get_this_model_name(),
2245
-                $qualified_column_name
2246
-            )
2247
-        );
2248
-    }
2249
-
2250
-
2251
-
2252
-    /**
2253
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2254
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2255
-     * column
2256
-     *
2257
-     * @param array  $query_params   like EEM_Base::get_all's
2258
-     * @param string $field_to_count field on model to count by (not column name)
2259
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2260
-     *                               that by the setting $distinct to TRUE;
2261
-     * @return int
2262
-     * @throws EE_Error
2263
-     */
2264
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2265
-    {
2266
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2267
-        if ($field_to_count) {
2268
-            $field_obj = $this->field_settings_for($field_to_count);
2269
-            $column_to_count = $field_obj->get_qualified_column();
2270
-        } elseif ($this->has_primary_key_field()) {
2271
-            $pk_field_obj = $this->get_primary_key_field();
2272
-            $column_to_count = $pk_field_obj->get_qualified_column();
2273
-        } else {
2274
-            //there's no primary key
2275
-            //if we're counting distinct items, and there's no primary key,
2276
-            //we need to list out the columns for distinction;
2277
-            //otherwise we can just use star
2278
-            if ($distinct) {
2279
-                $columns_to_use = array();
2280
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2281
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2282
-                }
2283
-                $column_to_count = implode(',', $columns_to_use);
2284
-            } else {
2285
-                $column_to_count = '*';
2286
-            }
2287
-        }
2288
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2289
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2297
-     *
2298
-     * @param array  $query_params like EEM_Base::get_all
2299
-     * @param string $field_to_sum name of field (array key in $_fields array)
2300
-     * @return float
2301
-     * @throws EE_Error
2302
-     */
2303
-    public function sum($query_params, $field_to_sum = null)
2304
-    {
2305
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
-        if ($field_to_sum) {
2307
-            $field_obj = $this->field_settings_for($field_to_sum);
2308
-        } else {
2309
-            $field_obj = $this->get_primary_key_field();
2310
-        }
2311
-        $column_to_count = $field_obj->get_qualified_column();
2312
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2314
-        $data_type = $field_obj->get_wpdb_data_type();
2315
-        if ($data_type === '%d' || $data_type === '%s') {
2316
-            return (float)$return_value;
2317
-        }
2318
-        //must be %f
2319
-        return (float)$return_value;
2320
-    }
2321
-
2322
-
2323
-
2324
-    /**
2325
-     * Just calls the specified method on $wpdb with the given arguments
2326
-     * Consolidates a little extra error handling code
2327
-     *
2328
-     * @param string $wpdb_method
2329
-     * @param array  $arguments_to_provide
2330
-     * @throws EE_Error
2331
-     * @global wpdb  $wpdb
2332
-     * @return mixed
2333
-     */
2334
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
-    {
2336
-        //if we're in maintenance mode level 2, DON'T run any queries
2337
-        //because level 2 indicates the database needs updating and
2338
-        //is probably out of sync with the code
2339
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
-            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.",
2341
-                "event_espresso")));
2342
-        }
2343
-        /** @type WPDB $wpdb */
2344
-        global $wpdb;
2345
-        if (! method_exists($wpdb, $wpdb_method)) {
2346
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2347
-                'event_espresso'), $wpdb_method));
2348
-        }
2349
-        if (WP_DEBUG) {
2350
-            $old_show_errors_value = $wpdb->show_errors;
2351
-            $wpdb->show_errors(false);
2352
-        }
2353
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2354
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2355
-        if (WP_DEBUG) {
2356
-            $wpdb->show_errors($old_show_errors_value);
2357
-            if (! empty($wpdb->last_error)) {
2358
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2359
-            }
2360
-            if ($result === false) {
2361
-                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"',
2362
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2363
-            }
2364
-        } elseif ($result === false) {
2365
-            EE_Error::add_error(
2366
-                sprintf(
2367
-                    __('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"',
2368
-                        'event_espresso'),
2369
-                    $wpdb_method,
2370
-                    var_export($arguments_to_provide, true),
2371
-                    $wpdb->last_error
2372
-                ),
2373
-                __FILE__,
2374
-                __FUNCTION__,
2375
-                __LINE__
2376
-            );
2377
-        }
2378
-        return $result;
2379
-    }
2380
-
2381
-
2382
-
2383
-    /**
2384
-     * Attempts to run the indicated WPDB method with the provided arguments,
2385
-     * and if there's an error tries to verify the DB is correct. Uses
2386
-     * the static property EEM_Base::$_db_verification_level to determine whether
2387
-     * we should try to fix the EE core db, the addons, or just give up
2388
-     *
2389
-     * @param string $wpdb_method
2390
-     * @param array  $arguments_to_provide
2391
-     * @return mixed
2392
-     */
2393
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2394
-    {
2395
-        /** @type WPDB $wpdb */
2396
-        global $wpdb;
2397
-        $wpdb->last_error = null;
2398
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2399
-        // was there an error running the query? but we don't care on new activations
2400
-        // (we're going to setup the DB anyway on new activations)
2401
-        if (($result === false || ! empty($wpdb->last_error))
2402
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2403
-        ) {
2404
-            switch (EEM_Base::$_db_verification_level) {
2405
-                case EEM_Base::db_verified_none :
2406
-                    // let's double-check core's DB
2407
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2408
-                    break;
2409
-                case EEM_Base::db_verified_core :
2410
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2411
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2412
-                    break;
2413
-                case EEM_Base::db_verified_addons :
2414
-                    // ummmm... you in trouble
2415
-                    return $result;
2416
-                    break;
2417
-            }
2418
-            if (! empty($error_message)) {
2419
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2420
-                trigger_error($error_message);
2421
-            }
2422
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2423
-        }
2424
-        return $result;
2425
-    }
2426
-
2427
-
2428
-
2429
-    /**
2430
-     * Verifies the EE core database is up-to-date and records that we've done it on
2431
-     * EEM_Base::$_db_verification_level
2432
-     *
2433
-     * @param string $wpdb_method
2434
-     * @param array  $arguments_to_provide
2435
-     * @return string
2436
-     */
2437
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2438
-    {
2439
-        /** @type WPDB $wpdb */
2440
-        global $wpdb;
2441
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2442
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2443
-        $error_message = sprintf(
2444
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2445
-                'event_espresso'),
2446
-            $wpdb->last_error,
2447
-            $wpdb_method,
2448
-            wp_json_encode($arguments_to_provide)
2449
-        );
2450
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2451
-        return $error_message;
2452
-    }
2453
-
2454
-
2455
-
2456
-    /**
2457
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2458
-     * EEM_Base::$_db_verification_level
2459
-     *
2460
-     * @param $wpdb_method
2461
-     * @param $arguments_to_provide
2462
-     * @return string
2463
-     */
2464
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2465
-    {
2466
-        /** @type WPDB $wpdb */
2467
-        global $wpdb;
2468
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2469
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2470
-        $error_message = sprintf(
2471
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2472
-                'event_espresso'),
2473
-            $wpdb->last_error,
2474
-            $wpdb_method,
2475
-            wp_json_encode($arguments_to_provide)
2476
-        );
2477
-        EE_System::instance()->initialize_addons();
2478
-        return $error_message;
2479
-    }
2480
-
2481
-
2482
-
2483
-    /**
2484
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2485
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2486
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2487
-     * ..."
2488
-     *
2489
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2490
-     * @return string
2491
-     */
2492
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2493
-    {
2494
-        return " FROM " . $model_query_info->get_full_join_sql() .
2495
-               $model_query_info->get_where_sql() .
2496
-               $model_query_info->get_group_by_sql() .
2497
-               $model_query_info->get_having_sql() .
2498
-               $model_query_info->get_order_by_sql() .
2499
-               $model_query_info->get_limit_sql();
2500
-    }
2501
-
2502
-
2503
-
2504
-    /**
2505
-     * Set to easily debug the next X queries ran from this model.
2506
-     *
2507
-     * @param int $count
2508
-     */
2509
-    public function show_next_x_db_queries($count = 1)
2510
-    {
2511
-        $this->_show_next_x_db_queries = $count;
2512
-    }
2513
-
2514
-
2515
-
2516
-    /**
2517
-     * @param $sql_query
2518
-     */
2519
-    public function show_db_query_if_previously_requested($sql_query)
2520
-    {
2521
-        if ($this->_show_next_x_db_queries > 0) {
2522
-            echo $sql_query;
2523
-            $this->_show_next_x_db_queries--;
2524
-        }
2525
-    }
2526
-
2527
-
2528
-
2529
-    /**
2530
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2531
-     * There are the 3 cases:
2532
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2533
-     * $otherModelObject has no ID, it is first saved.
2534
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2535
-     * has no ID, it is first saved.
2536
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2537
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2538
-     * join table
2539
-     *
2540
-     * @param        EE_Base_Class                     /int $thisModelObject
2541
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2542
-     * @param string $relationName                     , key in EEM_Base::_relations
2543
-     *                                                 an attendee to a group, you also want to specify which role they
2544
-     *                                                 will have in that group. So you would use this parameter to
2545
-     *                                                 specify array('role-column-name'=>'role-id')
2546
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2547
-     *                                                 to for relation to methods that allow you to further specify
2548
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2549
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2550
-     *                                                 because these will be inserted in any new rows created as well.
2551
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2552
-     * @throws EE_Error
2553
-     */
2554
-    public function add_relationship_to(
2555
-        $id_or_obj,
2556
-        $other_model_id_or_obj,
2557
-        $relationName,
2558
-        $extra_join_model_fields_n_values = array()
2559
-    ) {
2560
-        $relation_obj = $this->related_settings_for($relationName);
2561
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2562
-    }
2563
-
2564
-
2565
-
2566
-    /**
2567
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2568
-     * There are the 3 cases:
2569
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2570
-     * error
2571
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2572
-     * an error
2573
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2574
-     *
2575
-     * @param        EE_Base_Class /int $id_or_obj
2576
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2577
-     * @param string $relationName key in EEM_Base::_relations
2578
-     * @return boolean of success
2579
-     * @throws EE_Error
2580
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2581
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2582
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2583
-     *                             because these will be inserted in any new rows created as well.
2584
-     */
2585
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2586
-    {
2587
-        $relation_obj = $this->related_settings_for($relationName);
2588
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2589
-    }
2590
-
2591
-
2592
-
2593
-    /**
2594
-     * @param mixed           $id_or_obj
2595
-     * @param string          $relationName
2596
-     * @param array           $where_query_params
2597
-     * @param EE_Base_Class[] objects to which relations were removed
2598
-     * @return \EE_Base_Class[]
2599
-     * @throws EE_Error
2600
-     */
2601
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2602
-    {
2603
-        $relation_obj = $this->related_settings_for($relationName);
2604
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2605
-    }
2606
-
2607
-
2608
-
2609
-    /**
2610
-     * Gets all the related items of the specified $model_name, using $query_params.
2611
-     * Note: by default, we remove the "default query params"
2612
-     * because we want to get even deleted items etc.
2613
-     *
2614
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2615
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2616
-     * @param array  $query_params like EEM_Base::get_all
2617
-     * @return EE_Base_Class[]
2618
-     * @throws EE_Error
2619
-     */
2620
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2621
-    {
2622
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2623
-        $relation_settings = $this->related_settings_for($model_name);
2624
-        return $relation_settings->get_all_related($model_obj, $query_params);
2625
-    }
2626
-
2627
-
2628
-
2629
-    /**
2630
-     * Deletes all the model objects across the relation indicated by $model_name
2631
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2632
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2633
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2634
-     *
2635
-     * @param EE_Base_Class|int|string $id_or_obj
2636
-     * @param string                   $model_name
2637
-     * @param array                    $query_params
2638
-     * @return int how many deleted
2639
-     * @throws EE_Error
2640
-     */
2641
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2642
-    {
2643
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2644
-        $relation_settings = $this->related_settings_for($model_name);
2645
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2646
-    }
2647
-
2648
-
2649
-
2650
-    /**
2651
-     * Hard deletes all the model objects across the relation indicated by $model_name
2652
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2653
-     * the model objects can't be hard deleted because of blocking related model objects,
2654
-     * just does a soft-delete on them instead.
2655
-     *
2656
-     * @param EE_Base_Class|int|string $id_or_obj
2657
-     * @param string                   $model_name
2658
-     * @param array                    $query_params
2659
-     * @return int how many deleted
2660
-     * @throws EE_Error
2661
-     */
2662
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2663
-    {
2664
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2665
-        $relation_settings = $this->related_settings_for($model_name);
2666
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2667
-    }
2668
-
2669
-
2670
-
2671
-    /**
2672
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2673
-     * unless otherwise specified in the $query_params
2674
-     *
2675
-     * @param        int             /EE_Base_Class $id_or_obj
2676
-     * @param string $model_name     like 'Event', or 'Registration'
2677
-     * @param array  $query_params   like EEM_Base::get_all's
2678
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2679
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2680
-     *                               that by the setting $distinct to TRUE;
2681
-     * @return int
2682
-     * @throws EE_Error
2683
-     */
2684
-    public function count_related(
2685
-        $id_or_obj,
2686
-        $model_name,
2687
-        $query_params = array(),
2688
-        $field_to_count = null,
2689
-        $distinct = false
2690
-    ) {
2691
-        $related_model = $this->get_related_model_obj($model_name);
2692
-        //we're just going to use the query params on the related model's normal get_all query,
2693
-        //except add a condition to say to match the current mod
2694
-        if (! isset($query_params['default_where_conditions'])) {
2695
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696
-        }
2697
-        $this_model_name = $this->get_this_model_name();
2698
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2700
-        return $related_model->count($query_params, $field_to_count, $distinct);
2701
-    }
2702
-
2703
-
2704
-
2705
-    /**
2706
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2707
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2708
-     *
2709
-     * @param        int           /EE_Base_Class $id_or_obj
2710
-     * @param string $model_name   like 'Event', or 'Registration'
2711
-     * @param array  $query_params like EEM_Base::get_all's
2712
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2713
-     * @return float
2714
-     * @throws EE_Error
2715
-     */
2716
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2717
-    {
2718
-        $related_model = $this->get_related_model_obj($model_name);
2719
-        if (! is_array($query_params)) {
2720
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2721
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2722
-                    gettype($query_params)), '4.6.0');
2723
-            $query_params = array();
2724
-        }
2725
-        //we're just going to use the query params on the related model's normal get_all query,
2726
-        //except add a condition to say to match the current mod
2727
-        if (! isset($query_params['default_where_conditions'])) {
2728
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729
-        }
2730
-        $this_model_name = $this->get_this_model_name();
2731
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2733
-        return $related_model->sum($query_params, $field_to_sum);
2734
-    }
2735
-
2736
-
2737
-
2738
-    /**
2739
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2740
-     * $modelObject
2741
-     *
2742
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2743
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2744
-     * @param array               $query_params     like EEM_Base::get_all's
2745
-     * @return EE_Base_Class
2746
-     * @throws EE_Error
2747
-     */
2748
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2749
-    {
2750
-        $query_params['limit'] = 1;
2751
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2752
-        if ($results) {
2753
-            return array_shift($results);
2754
-        }
2755
-        return null;
2756
-    }
2757
-
2758
-
2759
-
2760
-    /**
2761
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2762
-     *
2763
-     * @return string
2764
-     */
2765
-    public function get_this_model_name()
2766
-    {
2767
-        return str_replace("EEM_", "", get_class($this));
2768
-    }
2769
-
2770
-
2771
-
2772
-    /**
2773
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2774
-     *
2775
-     * @return EE_Any_Foreign_Model_Name_Field
2776
-     * @throws EE_Error
2777
-     */
2778
-    public function get_field_containing_related_model_name()
2779
-    {
2780
-        foreach ($this->field_settings(true) as $field) {
2781
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2782
-                $field_with_model_name = $field;
2783
-            }
2784
-        }
2785
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2786
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2787
-                $this->get_this_model_name()));
2788
-        }
2789
-        return $field_with_model_name;
2790
-    }
2791
-
2792
-
2793
-
2794
-    /**
2795
-     * Inserts a new entry into the database, for each table.
2796
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2797
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2798
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2799
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2800
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2801
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2802
-     *
2803
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2804
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2805
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2806
-     *                              of EEM_Base)
2807
-     * @return int new primary key on main table that got inserted
2808
-     * @throws EE_Error
2809
-     */
2810
-    public function insert($field_n_values)
2811
-    {
2812
-        /**
2813
-         * Filters the fields and their values before inserting an item using the models
2814
-         *
2815
-         * @param array    $fields_n_values keys are the fields and values are their new values
2816
-         * @param EEM_Base $model           the model used
2817
-         */
2818
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2819
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2820
-            $main_table = $this->_get_main_table();
2821
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2822
-            if ($new_id !== false) {
2823
-                foreach ($this->_get_other_tables() as $other_table) {
2824
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2825
-                }
2826
-            }
2827
-            /**
2828
-             * Done just after attempting to insert a new model object
2829
-             *
2830
-             * @param EEM_Base   $model           used
2831
-             * @param array      $fields_n_values fields and their values
2832
-             * @param int|string the              ID of the newly-inserted model object
2833
-             */
2834
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2835
-            return $new_id;
2836
-        }
2837
-        return false;
2838
-    }
2839
-
2840
-
2841
-
2842
-    /**
2843
-     * Checks that the result would satisfy the unique indexes on this model
2844
-     *
2845
-     * @param array  $field_n_values
2846
-     * @param string $action
2847
-     * @return boolean
2848
-     * @throws EE_Error
2849
-     */
2850
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2851
-    {
2852
-        foreach ($this->unique_indexes() as $index_name => $index) {
2853
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2854
-            if ($this->exists(array($uniqueness_where_params))) {
2855
-                EE_Error::add_error(
2856
-                    sprintf(
2857
-                        __(
2858
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2859
-                            "event_espresso"
2860
-                        ),
2861
-                        $action,
2862
-                        $this->_get_class_name(),
2863
-                        $index_name,
2864
-                        implode(",", $index->field_names()),
2865
-                        http_build_query($uniqueness_where_params)
2866
-                    ),
2867
-                    __FILE__,
2868
-                    __FUNCTION__,
2869
-                    __LINE__
2870
-                );
2871
-                return false;
2872
-            }
2873
-        }
2874
-        return true;
2875
-    }
2876
-
2877
-
2878
-
2879
-    /**
2880
-     * Checks the database for an item that conflicts (ie, if this item were
2881
-     * saved to the DB would break some uniqueness requirement, like a primary key
2882
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2883
-     * can be either an EE_Base_Class or an array of fields n values
2884
-     *
2885
-     * @param EE_Base_Class|array $obj_or_fields_array
2886
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2887
-     *                                                 when looking for conflicts
2888
-     *                                                 (ie, if false, we ignore the model object's primary key
2889
-     *                                                 when finding "conflicts". If true, it's also considered).
2890
-     *                                                 Only works for INT primary key,
2891
-     *                                                 STRING primary keys cannot be ignored
2892
-     * @throws EE_Error
2893
-     * @return EE_Base_Class|array
2894
-     */
2895
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2896
-    {
2897
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2898
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2899
-        } elseif (is_array($obj_or_fields_array)) {
2900
-            $fields_n_values = $obj_or_fields_array;
2901
-        } else {
2902
-            throw new EE_Error(
2903
-                sprintf(
2904
-                    __(
2905
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2906
-                        "event_espresso"
2907
-                    ),
2908
-                    get_class($this),
2909
-                    $obj_or_fields_array
2910
-                )
2911
-            );
2912
-        }
2913
-        $query_params = array();
2914
-        if ($this->has_primary_key_field()
2915
-            && ($include_primary_key
2916
-                || $this->get_primary_key_field()
2917
-                   instanceof
2918
-                   EE_Primary_Key_String_Field)
2919
-            && isset($fields_n_values[$this->primary_key_name()])
2920
-        ) {
2921
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2922
-        }
2923
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2924
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2925
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2926
-        }
2927
-        //if there is nothing to base this search on, then we shouldn't find anything
2928
-        if (empty($query_params)) {
2929
-            return array();
2930
-        }
2931
-        return $this->get_one($query_params);
2932
-    }
2933
-
2934
-
2935
-
2936
-    /**
2937
-     * Like count, but is optimized and returns a boolean instead of an int
2938
-     *
2939
-     * @param array $query_params
2940
-     * @return boolean
2941
-     * @throws EE_Error
2942
-     */
2943
-    public function exists($query_params)
2944
-    {
2945
-        $query_params['limit'] = 1;
2946
-        return $this->count($query_params) > 0;
2947
-    }
2948
-
2949
-
2950
-
2951
-    /**
2952
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2953
-     *
2954
-     * @param int|string $id
2955
-     * @return boolean
2956
-     * @throws EE_Error
2957
-     */
2958
-    public function exists_by_ID($id)
2959
-    {
2960
-        return $this->exists(
2961
-            array(
2962
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2963
-                array(
2964
-                    $this->primary_key_name() => $id,
2965
-                ),
2966
-            )
2967
-        );
2968
-    }
2969
-
2970
-
2971
-
2972
-    /**
2973
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2974
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2975
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2976
-     * on the main table)
2977
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2978
-     * cases where we want to call it directly rather than via insert().
2979
-     *
2980
-     * @access   protected
2981
-     * @param EE_Table_Base $table
2982
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2983
-     *                                       float
2984
-     * @param int           $new_id          for now we assume only int keys
2985
-     * @throws EE_Error
2986
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2987
-     * @return int ID of new row inserted, or FALSE on failure
2988
-     */
2989
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2990
-    {
2991
-        global $wpdb;
2992
-        $insertion_col_n_values = array();
2993
-        $format_for_insertion = array();
2994
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2995
-        foreach ($fields_on_table as $field_name => $field_obj) {
2996
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2997
-            if ($field_obj->is_auto_increment()) {
2998
-                continue;
2999
-            }
3000
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3001
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
3002
-            if ($prepared_value !== null) {
3003
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3004
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3005
-            }
3006
-        }
3007
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3008
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
3009
-            //so add the fk to the main table as a column
3010
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3011
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3012
-        }
3013
-        //insert the new entry
3014
-        $result = $this->_do_wpdb_query('insert',
3015
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3016
-        if ($result === false) {
3017
-            return false;
3018
-        }
3019
-        //ok, now what do we return for the ID of the newly-inserted thing?
3020
-        if ($this->has_primary_key_field()) {
3021
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3022
-                return $wpdb->insert_id;
3023
-            }
3024
-            //it's not an auto-increment primary key, so
3025
-            //it must have been supplied
3026
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3027
-        }
3028
-        //we can't return a  primary key because there is none. instead return
3029
-        //a unique string indicating this model
3030
-        return $this->get_index_primary_key_string($fields_n_values);
3031
-    }
3032
-
3033
-
3034
-
3035
-    /**
3036
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3037
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3038
-     * and there is no default, we pass it along. WPDB will take care of it)
3039
-     *
3040
-     * @param EE_Model_Field_Base $field_obj
3041
-     * @param array               $fields_n_values
3042
-     * @return mixed string|int|float depending on what the table column will be expecting
3043
-     * @throws EE_Error
3044
-     */
3045
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3046
-    {
3047
-        //if this field doesn't allow nullable, don't allow it
3048
-        if (
3049
-            ! $field_obj->is_nullable()
3050
-            && (
3051
-                ! isset($fields_n_values[$field_obj->get_name()])
3052
-                || $fields_n_values[$field_obj->get_name()] === null
3053
-            )
3054
-        ) {
3055
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3056
-        }
3057
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3058
-            ? $fields_n_values[$field_obj->get_name()]
3059
-            : null;
3060
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3061
-    }
3062
-
3063
-
3064
-
3065
-    /**
3066
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3067
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3068
-     * the field's prepare_for_set() method.
3069
-     *
3070
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3071
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3072
-     *                                   top of file)
3073
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3074
-     *                                   $value is a custom selection
3075
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3076
-     */
3077
-    private function _prepare_value_for_use_in_db($value, $field)
3078
-    {
3079
-        if ($field && $field instanceof EE_Model_Field_Base) {
3080
-            switch ($this->_values_already_prepared_by_model_object) {
3081
-                /** @noinspection PhpMissingBreakStatementInspection */
3082
-                case self::not_prepared_by_model_object:
3083
-                    $value = $field->prepare_for_set($value);
3084
-                //purposefully left out "return"
3085
-                case self::prepared_by_model_object:
3086
-                    /** @noinspection SuspiciousAssignmentsInspection */
3087
-                    $value = $field->prepare_for_use_in_db($value);
3088
-                case self::prepared_for_use_in_db:
3089
-                    //leave the value alone
3090
-            }
3091
-            return $value;
3092
-        }
3093
-        return $value;
3094
-    }
3095
-
3096
-
3097
-
3098
-    /**
3099
-     * Returns the main table on this model
3100
-     *
3101
-     * @return EE_Primary_Table
3102
-     * @throws EE_Error
3103
-     */
3104
-    protected function _get_main_table()
3105
-    {
3106
-        foreach ($this->_tables as $table) {
3107
-            if ($table instanceof EE_Primary_Table) {
3108
-                return $table;
3109
-            }
3110
-        }
3111
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3112
-            'event_espresso'), get_class($this)));
3113
-    }
3114
-
3115
-
3116
-
3117
-    /**
3118
-     * table
3119
-     * returns EE_Primary_Table table name
3120
-     *
3121
-     * @return string
3122
-     * @throws EE_Error
3123
-     */
3124
-    public function table()
3125
-    {
3126
-        return $this->_get_main_table()->get_table_name();
3127
-    }
3128
-
3129
-
3130
-
3131
-    /**
3132
-     * table
3133
-     * returns first EE_Secondary_Table table name
3134
-     *
3135
-     * @return string
3136
-     */
3137
-    public function second_table()
3138
-    {
3139
-        // grab second table from tables array
3140
-        $second_table = end($this->_tables);
3141
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
-    }
3143
-
3144
-
3145
-
3146
-    /**
3147
-     * get_table_obj_by_alias
3148
-     * returns table name given it's alias
3149
-     *
3150
-     * @param string $table_alias
3151
-     * @return EE_Primary_Table | EE_Secondary_Table
3152
-     */
3153
-    public function get_table_obj_by_alias($table_alias = '')
3154
-    {
3155
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3156
-    }
3157
-
3158
-
3159
-
3160
-    /**
3161
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
-     *
3163
-     * @return EE_Secondary_Table[]
3164
-     */
3165
-    protected function _get_other_tables()
3166
-    {
3167
-        $other_tables = array();
3168
-        foreach ($this->_tables as $table_alias => $table) {
3169
-            if ($table instanceof EE_Secondary_Table) {
3170
-                $other_tables[$table_alias] = $table;
3171
-            }
3172
-        }
3173
-        return $other_tables;
3174
-    }
3175
-
3176
-
3177
-
3178
-    /**
3179
-     * Finds all the fields that correspond to the given table
3180
-     *
3181
-     * @param string $table_alias , array key in EEM_Base::_tables
3182
-     * @return EE_Model_Field_Base[]
3183
-     */
3184
-    public function _get_fields_for_table($table_alias)
3185
-    {
3186
-        return $this->_fields[$table_alias];
3187
-    }
3188
-
3189
-
3190
-
3191
-    /**
3192
-     * Recurses through all the where parameters, and finds all the related models we'll need
3193
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
-     * related Registration, Transaction, and Payment models.
3197
-     *
3198
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3199
-     * @return EE_Model_Query_Info_Carrier
3200
-     * @throws EE_Error
3201
-     */
3202
-    public function _extract_related_models_from_query($query_params)
3203
-    {
3204
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
-        if (array_key_exists(0, $query_params)) {
3206
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
-        }
3208
-        if (array_key_exists('group_by', $query_params)) {
3209
-            if (is_array($query_params['group_by'])) {
3210
-                $this->_extract_related_models_from_sub_params_array_values(
3211
-                    $query_params['group_by'],
3212
-                    $query_info_carrier,
3213
-                    'group_by'
3214
-                );
3215
-            } elseif (! empty ($query_params['group_by'])) {
3216
-                $this->_extract_related_model_info_from_query_param(
3217
-                    $query_params['group_by'],
3218
-                    $query_info_carrier,
3219
-                    'group_by'
3220
-                );
3221
-            }
3222
-        }
3223
-        if (array_key_exists('having', $query_params)) {
3224
-            $this->_extract_related_models_from_sub_params_array_keys(
3225
-                $query_params[0],
3226
-                $query_info_carrier,
3227
-                'having'
3228
-            );
3229
-        }
3230
-        if (array_key_exists('order_by', $query_params)) {
3231
-            if (is_array($query_params['order_by'])) {
3232
-                $this->_extract_related_models_from_sub_params_array_keys(
3233
-                    $query_params['order_by'],
3234
-                    $query_info_carrier,
3235
-                    'order_by'
3236
-                );
3237
-            } elseif (! empty($query_params['order_by'])) {
3238
-                $this->_extract_related_model_info_from_query_param(
3239
-                    $query_params['order_by'],
3240
-                    $query_info_carrier,
3241
-                    'order_by'
3242
-                );
3243
-            }
3244
-        }
3245
-        if (array_key_exists('force_join', $query_params)) {
3246
-            $this->_extract_related_models_from_sub_params_array_values(
3247
-                $query_params['force_join'],
3248
-                $query_info_carrier,
3249
-                'force_join'
3250
-            );
3251
-        }
3252
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
-        return $query_info_carrier;
3254
-    }
3255
-
3256
-
3257
-
3258
-    /**
3259
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
-     *
3261
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3262
-     *                                                      $query_params['having']
3263
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3264
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3265
-     * @throws EE_Error
3266
-     * @return \EE_Model_Query_Info_Carrier
3267
-     */
3268
-    private function _extract_related_models_from_sub_params_array_keys(
3269
-        $sub_query_params,
3270
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3271
-        $query_param_type
3272
-    ) {
3273
-        if (! empty($sub_query_params)) {
3274
-            $sub_query_params = (array)$sub_query_params;
3275
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3276
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3277
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3278
-                    $query_param_type);
3279
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
-                //of array('Registration.TXN_ID'=>23)
3283
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3286
-                        throw new EE_Error(sprintf(__("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'))",
3287
-                            "event_espresso"),
3288
-                            $param, $possibly_array_of_params));
3289
-                    }
3290
-                    $this->_extract_related_models_from_sub_params_array_keys(
3291
-                        $possibly_array_of_params,
3292
-                        $model_query_info_carrier, $query_param_type
3293
-                    );
3294
-                } elseif ($query_param_type === 0 //ie WHERE
3295
-                          && is_array($possibly_array_of_params)
3296
-                          && isset($possibly_array_of_params[2])
3297
-                          && $possibly_array_of_params[2] == true
3298
-                ) {
3299
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3300
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3301
-                    //from which we should extract query parameters!
3302
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3303
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3304
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3305
-                    }
3306
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3307
-                        $model_query_info_carrier, $query_param_type);
3308
-                }
3309
-            }
3310
-        }
3311
-        return $model_query_info_carrier;
3312
-    }
3313
-
3314
-
3315
-
3316
-    /**
3317
-     * For extracting related models from forced_joins, where the array values contain the info about what
3318
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3319
-     *
3320
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3321
-     *                                                      $query_params['having']
3322
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3323
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3324
-     * @throws EE_Error
3325
-     * @return \EE_Model_Query_Info_Carrier
3326
-     */
3327
-    private function _extract_related_models_from_sub_params_array_values(
3328
-        $sub_query_params,
3329
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330
-        $query_param_type
3331
-    ) {
3332
-        if (! empty($sub_query_params)) {
3333
-            if (! is_array($sub_query_params)) {
3334
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3335
-                    $sub_query_params));
3336
-            }
3337
-            foreach ($sub_query_params as $param) {
3338
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3339
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3340
-                    $query_param_type);
3341
-            }
3342
-        }
3343
-        return $model_query_info_carrier;
3344
-    }
3345
-
3346
-
3347
-
3348
-    /**
3349
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3350
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3351
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3352
-     * but use them in a different order. Eg, we need to know what models we are querying
3353
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3354
-     * other models before we can finalize the where clause SQL.
3355
-     *
3356
-     * @param array $query_params
3357
-     * @throws EE_Error
3358
-     * @return EE_Model_Query_Info_Carrier
3359
-     */
3360
-    public function _create_model_query_info_carrier($query_params)
3361
-    {
3362
-        if (! is_array($query_params)) {
3363
-            EE_Error::doing_it_wrong(
3364
-                'EEM_Base::_create_model_query_info_carrier',
3365
-                sprintf(
3366
-                    __(
3367
-                        '$query_params should be an array, you passed a variable of type %s',
3368
-                        'event_espresso'
3369
-                    ),
3370
-                    gettype($query_params)
3371
-                ),
3372
-                '4.6.0'
3373
-            );
3374
-            $query_params = array();
3375
-        }
3376
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3377
-        //first check if we should alter the query to account for caps or not
3378
-        //because the caps might require us to do extra joins
3379
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3380
-            $query_params[0] = $where_query_params = array_replace_recursive(
3381
-                $where_query_params,
3382
-                $this->caps_where_conditions(
3383
-                    $query_params['caps']
3384
-                )
3385
-            );
3386
-        }
3387
-        $query_object = $this->_extract_related_models_from_query($query_params);
3388
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3389
-        foreach ($where_query_params as $key => $value) {
3390
-            if (is_int($key)) {
3391
-                throw new EE_Error(
3392
-                    sprintf(
3393
-                        __(
3394
-                            "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.",
3395
-                            "event_espresso"
3396
-                        ),
3397
-                        $key,
3398
-                        var_export($value, true),
3399
-                        var_export($query_params, true),
3400
-                        get_class($this)
3401
-                    )
3402
-                );
3403
-            }
3404
-        }
3405
-        if (
3406
-            array_key_exists('default_where_conditions', $query_params)
3407
-            && ! empty($query_params['default_where_conditions'])
3408
-        ) {
3409
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3410
-        } else {
3411
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3412
-        }
3413
-        $where_query_params = array_merge(
3414
-            $this->_get_default_where_conditions_for_models_in_query(
3415
-                $query_object,
3416
-                $use_default_where_conditions,
3417
-                $where_query_params
3418
-            ),
3419
-            $where_query_params
3420
-        );
3421
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3422
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3423
-        // So we need to setup a subquery and use that for the main join.
3424
-        // Note for now this only works on the primary table for the model.
3425
-        // So for instance, you could set the limit array like this:
3426
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3427
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3428
-            $query_object->set_main_model_join_sql(
3429
-                $this->_construct_limit_join_select(
3430
-                    $query_params['on_join_limit'][0],
3431
-                    $query_params['on_join_limit'][1]
3432
-                )
3433
-            );
3434
-        }
3435
-        //set limit
3436
-        if (array_key_exists('limit', $query_params)) {
3437
-            if (is_array($query_params['limit'])) {
3438
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3439
-                    $e = sprintf(
3440
-                        __(
3441
-                            "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)",
3442
-                            "event_espresso"
3443
-                        ),
3444
-                        http_build_query($query_params['limit'])
3445
-                    );
3446
-                    throw new EE_Error($e . "|" . $e);
3447
-                }
3448
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3449
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3450
-            } elseif (! empty ($query_params['limit'])) {
3451
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3452
-            }
3453
-        }
3454
-        //set order by
3455
-        if (array_key_exists('order_by', $query_params)) {
3456
-            if (is_array($query_params['order_by'])) {
3457
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3458
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3459
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3460
-                if (array_key_exists('order', $query_params)) {
3461
-                    throw new EE_Error(
3462
-                        sprintf(
3463
-                            __(
3464
-                                "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 ",
3465
-                                "event_espresso"
3466
-                            ),
3467
-                            get_class($this),
3468
-                            implode(", ", array_keys($query_params['order_by'])),
3469
-                            implode(", ", $query_params['order_by']),
3470
-                            $query_params['order']
3471
-                        )
3472
-                    );
3473
-                }
3474
-                $this->_extract_related_models_from_sub_params_array_keys(
3475
-                    $query_params['order_by'],
3476
-                    $query_object,
3477
-                    'order_by'
3478
-                );
3479
-                //assume it's an array of fields to order by
3480
-                $order_array = array();
3481
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3482
-                    $order = $this->_extract_order($order);
3483
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3484
-                }
3485
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3486
-            } elseif (! empty ($query_params['order_by'])) {
3487
-                $this->_extract_related_model_info_from_query_param(
3488
-                    $query_params['order_by'],
3489
-                    $query_object,
3490
-                    'order',
3491
-                    $query_params['order_by']
3492
-                );
3493
-                $order = isset($query_params['order'])
3494
-                    ? $this->_extract_order($query_params['order'])
3495
-                    : 'DESC';
3496
-                $query_object->set_order_by_sql(
3497
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3498
-                );
3499
-            }
3500
-        }
3501
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3502
-        if (! array_key_exists('order_by', $query_params)
3503
-            && array_key_exists('order', $query_params)
3504
-            && ! empty($query_params['order'])
3505
-        ) {
3506
-            $pk_field = $this->get_primary_key_field();
3507
-            $order = $this->_extract_order($query_params['order']);
3508
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3509
-        }
3510
-        //set group by
3511
-        if (array_key_exists('group_by', $query_params)) {
3512
-            if (is_array($query_params['group_by'])) {
3513
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3514
-                $group_by_array = array();
3515
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3516
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3517
-                }
3518
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3519
-            } elseif (! empty ($query_params['group_by'])) {
3520
-                $query_object->set_group_by_sql(
3521
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3522
-                );
3523
-            }
3524
-        }
3525
-        //set having
3526
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3527
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3528
-        }
3529
-        //now, just verify they didn't pass anything wack
3530
-        foreach ($query_params as $query_key => $query_value) {
3531
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3532
-                throw new EE_Error(
3533
-                    sprintf(
3534
-                        __(
3535
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3536
-                            'event_espresso'
3537
-                        ),
3538
-                        $query_key,
3539
-                        get_class($this),
3540
-                        //						print_r( $this->_allowed_query_params, TRUE )
3541
-                        implode(',', $this->_allowed_query_params)
3542
-                    )
3543
-                );
3544
-            }
3545
-        }
3546
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3547
-        if (empty($main_model_join_sql)) {
3548
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3549
-        }
3550
-        return $query_object;
3551
-    }
3552
-
3553
-
3554
-
3555
-    /**
3556
-     * Gets the where conditions that should be imposed on the query based on the
3557
-     * context (eg reading frontend, backend, edit or delete).
3558
-     *
3559
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3560
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3561
-     * @throws EE_Error
3562
-     */
3563
-    public function caps_where_conditions($context = self::caps_read)
3564
-    {
3565
-        EEM_Base::verify_is_valid_cap_context($context);
3566
-        $cap_where_conditions = array();
3567
-        $cap_restrictions = $this->caps_missing($context);
3568
-        /**
3569
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3570
-         */
3571
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3572
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3573
-                $restriction_if_no_cap->get_default_where_conditions());
3574
-        }
3575
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3576
-            $cap_restrictions);
3577
-    }
3578
-
3579
-
3580
-
3581
-    /**
3582
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3583
-     * otherwise throws an exception
3584
-     *
3585
-     * @param string $should_be_order_string
3586
-     * @return string either ASC, asc, DESC or desc
3587
-     * @throws EE_Error
3588
-     */
3589
-    private function _extract_order($should_be_order_string)
3590
-    {
3591
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3592
-            return $should_be_order_string;
3593
-        }
3594
-        throw new EE_Error(
3595
-            sprintf(
3596
-                __(
3597
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3598
-                    "event_espresso"
3599
-                ), get_class($this), $should_be_order_string
3600
-            )
3601
-        );
3602
-    }
3603
-
3604
-
3605
-
3606
-    /**
3607
-     * Looks at all the models which are included in this query, and asks each
3608
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3609
-     * so they can be merged
3610
-     *
3611
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3612
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3613
-     *                                                                  'none' means NO default where conditions will
3614
-     *                                                                  be used AT ALL during this query.
3615
-     *                                                                  'other_models_only' means default where
3616
-     *                                                                  conditions from other models will be used, but
3617
-     *                                                                  not for this primary model. 'all', the default,
3618
-     *                                                                  means default where conditions will apply as
3619
-     *                                                                  normal
3620
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3621
-     * @throws EE_Error
3622
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3623
-     */
3624
-    private function _get_default_where_conditions_for_models_in_query(
3625
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3626
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3627
-        $where_query_params = array()
3628
-    ) {
3629
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3630
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3631
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3632
-                "event_espresso"), $use_default_where_conditions,
3633
-                implode(", ", $allowed_used_default_where_conditions_values)));
3634
-        }
3635
-        $universal_query_params = array();
3636
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3637
-            $universal_query_params = $this->_get_default_where_conditions();
3638
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3639
-            $universal_query_params = $this->_get_minimum_where_conditions();
3640
-        }
3641
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3642
-            $related_model = $this->get_related_model_obj($model_name);
3643
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3644
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3645
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3646
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3647
-            } else {
3648
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3649
-                continue;
3650
-            }
3651
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3652
-                $related_model_universal_where_params,
3653
-                $where_query_params,
3654
-                $related_model,
3655
-                $model_relation_path
3656
-            );
3657
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3658
-                $universal_query_params,
3659
-                $overrides
3660
-            );
3661
-        }
3662
-        return $universal_query_params;
3663
-    }
3664
-
3665
-
3666
-
3667
-    /**
3668
-     * Determines whether or not we should use default where conditions for the model in question
3669
-     * (this model, or other related models).
3670
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3671
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3672
-     * We should use default where conditions on related models when they requested to use default where conditions
3673
-     * on all models, or specifically just on other related models
3674
-     * @param      $default_where_conditions_value
3675
-     * @param bool $for_this_model false means this is for OTHER related models
3676
-     * @return bool
3677
-     */
3678
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3679
-    {
3680
-        return (
3681
-                   $for_this_model
3682
-                   && in_array(
3683
-                       $default_where_conditions_value,
3684
-                       array(
3685
-                           EEM_Base::default_where_conditions_all,
3686
-                           EEM_Base::default_where_conditions_this_only,
3687
-                           EEM_Base::default_where_conditions_minimum_others,
3688
-                       ),
3689
-                       true
3690
-                   )
3691
-               )
3692
-               || (
3693
-                   ! $for_this_model
3694
-                   && in_array(
3695
-                       $default_where_conditions_value,
3696
-                       array(
3697
-                           EEM_Base::default_where_conditions_all,
3698
-                           EEM_Base::default_where_conditions_others_only,
3699
-                       ),
3700
-                       true
3701
-                   )
3702
-               );
3703
-    }
3704
-
3705
-    /**
3706
-     * Determines whether or not we should use default minimum conditions for the model in question
3707
-     * (this model, or other related models).
3708
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3709
-     * where conditions.
3710
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3711
-     * on this model or others
3712
-     * @param      $default_where_conditions_value
3713
-     * @param bool $for_this_model false means this is for OTHER related models
3714
-     * @return bool
3715
-     */
3716
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3717
-    {
3718
-        return (
3719
-                   $for_this_model
3720
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3721
-               )
3722
-               || (
3723
-                   ! $for_this_model
3724
-                   && in_array(
3725
-                       $default_where_conditions_value,
3726
-                       array(
3727
-                           EEM_Base::default_where_conditions_minimum_others,
3728
-                           EEM_Base::default_where_conditions_minimum_all,
3729
-                       ),
3730
-                       true
3731
-                   )
3732
-               );
3733
-    }
3734
-
3735
-
3736
-    /**
3737
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3738
-     * then we also add a special where condition which allows for that model's primary key
3739
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3740
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3741
-     *
3742
-     * @param array    $default_where_conditions
3743
-     * @param array    $provided_where_conditions
3744
-     * @param EEM_Base $model
3745
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3746
-     * @return array like EEM_Base::get_all's $query_params[0]
3747
-     * @throws EE_Error
3748
-     */
3749
-    private function _override_defaults_or_make_null_friendly(
3750
-        $default_where_conditions,
3751
-        $provided_where_conditions,
3752
-        $model,
3753
-        $model_relation_path
3754
-    ) {
3755
-        $null_friendly_where_conditions = array();
3756
-        $none_overridden = true;
3757
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3758
-        foreach ($default_where_conditions as $key => $val) {
3759
-            if (isset($provided_where_conditions[$key])) {
3760
-                $none_overridden = false;
3761
-            } else {
3762
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3763
-            }
3764
-        }
3765
-        if ($none_overridden && $default_where_conditions) {
3766
-            if ($model->has_primary_key_field()) {
3767
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3768
-                                                                                . "."
3769
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3770
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Used to set the $_model_query_blog_id static property.
654
+	 *
655
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
+	 *                      value for get_current_blog_id() will be used.
657
+	 */
658
+	public static function set_model_query_blog_id($blog_id = 0)
659
+	{
660
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
+	}
662
+
663
+
664
+
665
+	/**
666
+	 * Returns whatever is set as the internal $model_query_blog_id.
667
+	 *
668
+	 * @return int
669
+	 */
670
+	public static function get_model_query_blog_id()
671
+	{
672
+		return EEM_Base::$_model_query_blog_id;
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * This function is a singleton method used to instantiate the Espresso_model object
679
+	 *
680
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
+	 *                                (and any incoming timezone data that gets saved).
682
+	 *                                Note this just sends the timezone info to the date time model field objects.
683
+	 *                                Default is NULL
684
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
+	 * @return static (as in the concrete child class)
686
+	 * @throws EE_Error
687
+	 * @throws InvalidArgumentException
688
+	 * @throws InvalidDataTypeException
689
+	 * @throws InvalidInterfaceException
690
+	 */
691
+	public static function instance($timezone = null)
692
+	{
693
+		// check if instance of Espresso_model already exists
694
+		if (! static::$_instance instanceof static) {
695
+			// instantiate Espresso_model
696
+			static::$_instance = new static(
697
+				$timezone,
698
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
+			);
700
+		}
701
+		//we might have a timezone set, let set_timezone decide what to do with it
702
+		static::$_instance->set_timezone($timezone);
703
+		// Espresso_model object
704
+		return static::$_instance;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * resets the model and returns it
711
+	 *
712
+	 * @param null | string $timezone
713
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
+	 * all its properties reset; if it wasn't instantiated, returns null)
715
+	 * @throws EE_Error
716
+	 * @throws ReflectionException
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws InvalidInterfaceException
720
+	 */
721
+	public static function reset($timezone = null)
722
+	{
723
+		if (static::$_instance instanceof EEM_Base) {
724
+			//let's try to NOT swap out the current instance for a new one
725
+			//because if someone has a reference to it, we can't remove their reference
726
+			//so it's best to keep using the same reference, but change the original object
727
+			//reset all its properties to their original values as defined in the class
728
+			$r = new ReflectionClass(get_class(static::$_instance));
729
+			$static_properties = $r->getStaticProperties();
730
+			foreach ($r->getDefaultProperties() as $property => $value) {
731
+				//don't set instance to null like it was originally,
732
+				//but it's static anyways, and we're ignoring static properties (for now at least)
733
+				if (! isset($static_properties[$property])) {
734
+					static::$_instance->{$property} = $value;
735
+				}
736
+			}
737
+			//and then directly call its constructor again, like we would if we were creating a new one
738
+			static::$_instance->__construct(
739
+				$timezone,
740
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
+			);
742
+			return self::instance();
743
+		}
744
+		return null;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * @return LoaderInterface
751
+	 * @throws InvalidArgumentException
752
+	 * @throws InvalidDataTypeException
753
+	 * @throws InvalidInterfaceException
754
+	 */
755
+	private static function getLoader()
756
+	{
757
+		if(! EEM_Base::$loader instanceof LoaderInterface) {
758
+			EEM_Base::$loader = LoaderFactory::getLoader();
759
+		}
760
+		return EEM_Base::$loader;
761
+	}
762
+
763
+
764
+
765
+	/**
766
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
+	 *
768
+	 * @param  boolean $translated return localized strings or JUST the array.
769
+	 * @return array
770
+	 * @throws EE_Error
771
+	 * @throws InvalidArgumentException
772
+	 * @throws InvalidDataTypeException
773
+	 * @throws InvalidInterfaceException
774
+	 */
775
+	public function status_array($translated = false)
776
+	{
777
+		if (! array_key_exists('Status', $this->_model_relations)) {
778
+			return array();
779
+		}
780
+		$model_name = $this->get_this_model_name();
781
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
+		$status_array = array();
784
+		foreach ($stati as $status) {
785
+			$status_array[$status->ID()] = $status->get('STS_code');
786
+		}
787
+		return $translated
788
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
+			: $status_array;
790
+	}
791
+
792
+
793
+
794
+	/**
795
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
+	 *
797
+	 * @param array $query_params             {
798
+	 * @var array $0 (where) array {
799
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
+	 *                                        conditions based on related models (and even
803
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
804
+	 *                                        name. Eg,
805
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
+	 *                                        to Venues (even when each of those models actually consisted of two
813
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
814
+	 *                                        just having
815
+	 *                                        "Venue.VNU_ID", you could have
816
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
+	 *                                        events are related to Registrations, which are related to Attendees). You
818
+	 *                                        can take it even further with
819
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
+	 *                                        (from the default of '='), change the value to an numerically-indexed
821
+	 *                                        array, where the first item in the list is the operator. eg: array(
822
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
830
+	 *                                        the value is a field, simply provide a third array item (true) to the
831
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
+	 *                                        Note: you can also use related model field names like you would any other
834
+	 *                                        field name. eg:
835
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
837
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
844
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
+	 *                                        "stick" until you specify an AND. eg
846
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
851
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
+	 *                                        too, eg:
854
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
859
+	 *                                        the OFFSET, the 2nd is the LIMIT
860
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
+	 *                                        following format array('on_join_limit'
863
+	 *                                        => array( 'table_alias', array(1,2) ) ).
864
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
+	 *                                        values are either 'ASC' or 'DESC'.
866
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
+	 *                                        DESC..." respectively. Like the
869
+	 *                                        'where' conditions, these fields can be on related models. Eg
870
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
872
+	 *                                        Attendee, Price, Datetime, etc.)
873
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
875
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
+	 *                                        order by the primary key. Eg,
878
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
880
+	 *                                        DTT_EVT_start) or
881
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
+	 *                                        'group_by'=>'VNU_ID', or
885
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
+	 *                                        if no
887
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
888
+	 *                                        model's primary key (or combined primary keys). This avoids some
889
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
890
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
+	 *                                        results)
894
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
+	 *                                        array where values are models to be joined in the query.Eg
896
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
898
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
899
+	 *                                        related models which belongs to the current model
900
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
901
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
902
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
905
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
907
+	 *                                        this model's default where conditions added to the query, use
908
+	 *                                        'this_model_only'. If you want to use all default where conditions
909
+	 *                                        (default), set to 'all'.
910
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
+	 *                                        everything? Or should we only show the current user items they should be
913
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
+	 *                                        }
916
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
+	 *                                        array( array(
922
+	 *                                        'OR'=>array(
923
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
+	 *                                        )
926
+	 *                                        ),
927
+	 *                                        'limit'=>10,
928
+	 *                                        'group_by'=>'TXN_ID'
929
+	 *                                        ));
930
+	 *                                        get all the answers to the question titled "shirt size" for event with id
931
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
+	 *                                        'Question.QST_display_text'=>'shirt size',
933
+	 *                                        'Registration.Event.EVT_ID'=>12
934
+	 *                                        ),
935
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
936
+	 *                                        ));
937
+	 * @throws EE_Error
938
+	 */
939
+	public function get_all($query_params = array())
940
+	{
941
+		if (isset($query_params['limit'])
942
+			&& ! isset($query_params['group_by'])
943
+		) {
944
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
+		}
946
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * Modifies the query parameters so we only get back model objects
953
+	 * that "belong" to the current user
954
+	 *
955
+	 * @param array $query_params @see EEM_Base::get_all()
956
+	 * @return array like EEM_Base::get_all
957
+	 */
958
+	public function alter_query_params_to_only_include_mine($query_params = array())
959
+	{
960
+		$wp_user_field_name = $this->wp_user_field_name();
961
+		if ($wp_user_field_name) {
962
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
963
+		}
964
+		return $query_params;
965
+	}
966
+
967
+
968
+
969
+	/**
970
+	 * Returns the name of the field's name that points to the WP_User table
971
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
+	 * foreign key to the WP_User table)
973
+	 *
974
+	 * @return string|boolean string on success, boolean false when there is no
975
+	 * foreign key to the WP_User table
976
+	 */
977
+	public function wp_user_field_name()
978
+	{
979
+		try {
980
+			if (! empty($this->_model_chain_to_wp_user)) {
981
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
+				$last_model_name = end($models_to_follow_to_wp_users);
983
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
+			} else {
986
+				$model_with_fk_to_wp_users = $this;
987
+				$model_chain_to_wp_user = '';
988
+			}
989
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
991
+		} catch (EE_Error $e) {
992
+			return false;
993
+		}
994
+	}
995
+
996
+
997
+
998
+	/**
999
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1001
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1002
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1003
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
+	 * (or transiently-related model)
1005
+	 *
1006
+	 * @return string
1007
+	 */
1008
+	public function model_chain_to_wp_user()
1009
+	{
1010
+		return $this->_model_chain_to_wp_user;
1011
+	}
1012
+
1013
+
1014
+
1015
+	/**
1016
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
+	 * like how registrations don't have a foreign key to wp_users, but the
1018
+	 * events they are for are), or is unrelated to wp users.
1019
+	 * generally available
1020
+	 *
1021
+	 * @return boolean
1022
+	 */
1023
+	public function is_owned()
1024
+	{
1025
+		if ($this->model_chain_to_wp_user()) {
1026
+			return true;
1027
+		}
1028
+		try {
1029
+			$this->get_foreign_key_to('WP_User');
1030
+			return true;
1031
+		} catch (EE_Error $e) {
1032
+			return false;
1033
+		}
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
+	 * the model)
1041
+	 *
1042
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1046
+	 *                                  override this and set the select to "*", or a specific column name, like
1047
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
+	 *                                  the aliases used to refer to this selection, and values are to be
1050
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
+	 * @throws EE_Error
1054
+	 * @throws InvalidArgumentException
1055
+	 */
1056
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
+	{
1058
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
+		$select_expressions = $columns_to_select === null
1061
+			? $this->_construct_default_select_sql($model_query_info)
1062
+			: '';
1063
+		if ($this->_custom_selections instanceof CustomSelects) {
1064
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
+			$select_expressions .= $select_expressions
1066
+				? ', ' . $custom_expressions
1067
+				: $custom_expressions;
1068
+		}
1069
+
1070
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
+	 * method of including extra select information.
1079
+	 *
1080
+	 * @param array             $query_params
1081
+	 * @param null|array|string $columns_to_select
1082
+	 * @return null|CustomSelects
1083
+	 * @throws InvalidArgumentException
1084
+	 */
1085
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
+	{
1087
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
+			return null;
1089
+		}
1090
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
+		return new CustomSelects($selects);
1093
+	}
1094
+
1095
+
1096
+
1097
+	/**
1098
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1099
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
+	 * take care of joins, field preparation etc.
1101
+	 *
1102
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1106
+	 *                                  override this and set the select to "*", or a specific column name, like
1107
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
+	 *                                  the aliases used to refer to this selection, and values are to be
1110
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
+	{
1117
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
+	}
1119
+
1120
+
1121
+
1122
+	/**
1123
+	 * For creating a custom select statement
1124
+	 *
1125
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
+	 *                                 SQL, and 1=>is the datatype
1128
+	 * @throws EE_Error
1129
+	 * @return string
1130
+	 */
1131
+	private function _construct_select_from_input($columns_to_select)
1132
+	{
1133
+		if (is_array($columns_to_select)) {
1134
+			$select_sql_array = array();
1135
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
+					throw new EE_Error(
1138
+						sprintf(
1139
+							__(
1140
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
+								'event_espresso'
1142
+							),
1143
+							$selection_and_datatype,
1144
+							$alias
1145
+						)
1146
+					);
1147
+				}
1148
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
+					throw new EE_Error(
1150
+						sprintf(
1151
+							esc_html__(
1152
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
+								'event_espresso'
1154
+							),
1155
+							$selection_and_datatype[1],
1156
+							$selection_and_datatype[0],
1157
+							$alias,
1158
+							implode(', ', $this->_valid_wpdb_data_types)
1159
+						)
1160
+					);
1161
+				}
1162
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
+			}
1164
+			$columns_to_select_string = implode(', ', $select_sql_array);
1165
+		} else {
1166
+			$columns_to_select_string = $columns_to_select;
1167
+		}
1168
+		return $columns_to_select_string;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
+	 *
1176
+	 * @return string
1177
+	 * @throws EE_Error
1178
+	 */
1179
+	public function primary_key_name()
1180
+	{
1181
+		return $this->get_primary_key_field()->get_name();
1182
+	}
1183
+
1184
+
1185
+
1186
+	/**
1187
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
+	 * If there is no primary key on this model, $id is treated as primary key string
1189
+	 *
1190
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1191
+	 * @return EE_Base_Class
1192
+	 */
1193
+	public function get_one_by_ID($id)
1194
+	{
1195
+		if ($this->get_from_entity_map($id)) {
1196
+			return $this->get_from_entity_map($id);
1197
+		}
1198
+		return $this->get_one(
1199
+			$this->alter_query_params_to_restrict_by_ID(
1200
+				$id,
1201
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
+			)
1203
+		);
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * Alters query parameters to only get items with this ID are returned.
1210
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
+	 * or could just be a simple primary key ID
1212
+	 *
1213
+	 * @param int   $id
1214
+	 * @param array $query_params
1215
+	 * @return array of normal query params, @see EEM_Base::get_all
1216
+	 * @throws EE_Error
1217
+	 */
1218
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
+	{
1220
+		if (! isset($query_params[0])) {
1221
+			$query_params[0] = array();
1222
+		}
1223
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1224
+		if ($conditions_from_id === null) {
1225
+			$query_params[0][$this->primary_key_name()] = $id;
1226
+		} else {
1227
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1228
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
+		}
1230
+		return $query_params;
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
+	 * array. If no item is found, null is returned.
1238
+	 *
1239
+	 * @param array $query_params like EEM_Base's $query_params variable.
1240
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
+	 * @throws EE_Error
1242
+	 */
1243
+	public function get_one($query_params = array())
1244
+	{
1245
+		if (! is_array($query_params)) {
1246
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
+					gettype($query_params)), '4.6.0');
1249
+			$query_params = array();
1250
+		}
1251
+		$query_params['limit'] = 1;
1252
+		$items = $this->get_all($query_params);
1253
+		if (empty($items)) {
1254
+			return null;
1255
+		}
1256
+		return array_shift($items);
1257
+	}
1258
+
1259
+
1260
+
1261
+	/**
1262
+	 * Returns the next x number of items in sequence from the given value as
1263
+	 * found in the database matching the given query conditions.
1264
+	 *
1265
+	 * @param mixed $current_field_value    Value used for the reference point.
1266
+	 * @param null  $field_to_order_by      What field is used for the
1267
+	 *                                      reference point.
1268
+	 * @param int   $limit                  How many to return.
1269
+	 * @param array $query_params           Extra conditions on the query.
1270
+	 * @param null  $columns_to_select      If left null, then an array of
1271
+	 *                                      EE_Base_Class objects is returned,
1272
+	 *                                      otherwise you can indicate just the
1273
+	 *                                      columns you want returned.
1274
+	 * @return EE_Base_Class[]|array
1275
+	 * @throws EE_Error
1276
+	 */
1277
+	public function next_x(
1278
+		$current_field_value,
1279
+		$field_to_order_by = null,
1280
+		$limit = 1,
1281
+		$query_params = array(),
1282
+		$columns_to_select = null
1283
+	) {
1284
+		return $this->_get_consecutive(
1285
+			$current_field_value,
1286
+			'>',
1287
+			$field_to_order_by,
1288
+			$limit,
1289
+			$query_params,
1290
+			$columns_to_select
1291
+		);
1292
+	}
1293
+
1294
+
1295
+
1296
+	/**
1297
+	 * Returns the previous x number of items in sequence from the given value
1298
+	 * as found in the database matching the given query conditions.
1299
+	 *
1300
+	 * @param mixed $current_field_value    Value used for the reference point.
1301
+	 * @param null  $field_to_order_by      What field is used for the
1302
+	 *                                      reference point.
1303
+	 * @param int   $limit                  How many to return.
1304
+	 * @param array $query_params           Extra conditions on the query.
1305
+	 * @param null  $columns_to_select      If left null, then an array of
1306
+	 *                                      EE_Base_Class objects is returned,
1307
+	 *                                      otherwise you can indicate just the
1308
+	 *                                      columns you want returned.
1309
+	 * @return EE_Base_Class[]|array
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function previous_x(
1313
+		$current_field_value,
1314
+		$field_to_order_by = null,
1315
+		$limit = 1,
1316
+		$query_params = array(),
1317
+		$columns_to_select = null
1318
+	) {
1319
+		return $this->_get_consecutive(
1320
+			$current_field_value,
1321
+			'<',
1322
+			$field_to_order_by,
1323
+			$limit,
1324
+			$query_params,
1325
+			$columns_to_select
1326
+		);
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * Returns the next item in sequence from the given value as found in the
1333
+	 * database matching the given query conditions.
1334
+	 *
1335
+	 * @param mixed $current_field_value    Value used for the reference point.
1336
+	 * @param null  $field_to_order_by      What field is used for the
1337
+	 *                                      reference point.
1338
+	 * @param array $query_params           Extra conditions on the query.
1339
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
+	 *                                      object is returned, otherwise you
1341
+	 *                                      can indicate just the columns you
1342
+	 *                                      want and a single array indexed by
1343
+	 *                                      the columns will be returned.
1344
+	 * @return EE_Base_Class|null|array()
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	public function next(
1348
+		$current_field_value,
1349
+		$field_to_order_by = null,
1350
+		$query_params = array(),
1351
+		$columns_to_select = null
1352
+	) {
1353
+		$results = $this->_get_consecutive(
1354
+			$current_field_value,
1355
+			'>',
1356
+			$field_to_order_by,
1357
+			1,
1358
+			$query_params,
1359
+			$columns_to_select
1360
+		);
1361
+		return empty($results) ? null : reset($results);
1362
+	}
1363
+
1364
+
1365
+
1366
+	/**
1367
+	 * Returns the previous item in sequence from the given value as found in
1368
+	 * the database matching the given query conditions.
1369
+	 *
1370
+	 * @param mixed $current_field_value    Value used for the reference point.
1371
+	 * @param null  $field_to_order_by      What field is used for the
1372
+	 *                                      reference point.
1373
+	 * @param array $query_params           Extra conditions on the query.
1374
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
+	 *                                      object is returned, otherwise you
1376
+	 *                                      can indicate just the columns you
1377
+	 *                                      want and a single array indexed by
1378
+	 *                                      the columns will be returned.
1379
+	 * @return EE_Base_Class|null|array()
1380
+	 * @throws EE_Error
1381
+	 */
1382
+	public function previous(
1383
+		$current_field_value,
1384
+		$field_to_order_by = null,
1385
+		$query_params = array(),
1386
+		$columns_to_select = null
1387
+	) {
1388
+		$results = $this->_get_consecutive(
1389
+			$current_field_value,
1390
+			'<',
1391
+			$field_to_order_by,
1392
+			1,
1393
+			$query_params,
1394
+			$columns_to_select
1395
+		);
1396
+		return empty($results) ? null : reset($results);
1397
+	}
1398
+
1399
+
1400
+
1401
+	/**
1402
+	 * Returns the a consecutive number of items in sequence from the given
1403
+	 * value as found in the database matching the given query conditions.
1404
+	 *
1405
+	 * @param mixed  $current_field_value   Value used for the reference point.
1406
+	 * @param string $operand               What operand is used for the sequence.
1407
+	 * @param string $field_to_order_by     What field is used for the reference point.
1408
+	 * @param int    $limit                 How many to return.
1409
+	 * @param array  $query_params          Extra conditions on the query.
1410
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
+	 *                                      otherwise you can indicate just the columns you want returned.
1412
+	 * @return EE_Base_Class[]|array
1413
+	 * @throws EE_Error
1414
+	 */
1415
+	protected function _get_consecutive(
1416
+		$current_field_value,
1417
+		$operand = '>',
1418
+		$field_to_order_by = null,
1419
+		$limit = 1,
1420
+		$query_params = array(),
1421
+		$columns_to_select = null
1422
+	) {
1423
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
+		if (empty($field_to_order_by)) {
1425
+			if ($this->has_primary_key_field()) {
1426
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1427
+			} else {
1428
+				if (WP_DEBUG) {
1429
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1430
+						'event_espresso'));
1431
+				}
1432
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
+				return array();
1434
+			}
1435
+		}
1436
+		if (! is_array($query_params)) {
1437
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
+					gettype($query_params)), '4.6.0');
1440
+			$query_params = array();
1441
+		}
1442
+		//let's add the where query param for consecutive look up.
1443
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
+		$query_params['limit'] = $limit;
1445
+		//set direction
1446
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
+		$query_params['order_by'] = $operand === '>'
1448
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
+		if (empty($columns_to_select)) {
1452
+			return $this->get_all($query_params);
1453
+		}
1454
+		//getting just the fields
1455
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This sets the _timezone property after model object has been instantiated.
1462
+	 *
1463
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
+	 */
1465
+	public function set_timezone($timezone)
1466
+	{
1467
+		if ($timezone !== null) {
1468
+			$this->_timezone = $timezone;
1469
+		}
1470
+		//note we need to loop through relations and set the timezone on those objects as well.
1471
+		foreach ($this->_model_relations as $relation) {
1472
+			$relation->set_timezone($timezone);
1473
+		}
1474
+		//and finally we do the same for any datetime fields
1475
+		foreach ($this->_fields as $field) {
1476
+			if ($field instanceof EE_Datetime_Field) {
1477
+				$field->set_timezone($timezone);
1478
+			}
1479
+		}
1480
+	}
1481
+
1482
+
1483
+
1484
+	/**
1485
+	 * This just returns whatever is set for the current timezone.
1486
+	 *
1487
+	 * @access public
1488
+	 * @return string
1489
+	 */
1490
+	public function get_timezone()
1491
+	{
1492
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
+		if (empty($this->_timezone)) {
1494
+			foreach ($this->_fields as $field) {
1495
+				if ($field instanceof EE_Datetime_Field) {
1496
+					$this->set_timezone($field->get_timezone());
1497
+					break;
1498
+				}
1499
+			}
1500
+		}
1501
+		//if timezone STILL empty then return the default timezone for the site.
1502
+		if (empty($this->_timezone)) {
1503
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
+		}
1505
+		return $this->_timezone;
1506
+	}
1507
+
1508
+
1509
+
1510
+	/**
1511
+	 * This returns the date formats set for the given field name and also ensures that
1512
+	 * $this->_timezone property is set correctly.
1513
+	 *
1514
+	 * @since 4.6.x
1515
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1516
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
+	 * @return array formats in an array with the date format first, and the time format last.
1519
+	 */
1520
+	public function get_formats_for($field_name, $pretty = false)
1521
+	{
1522
+		$field_settings = $this->field_settings_for($field_name);
1523
+		//if not a valid EE_Datetime_Field then throw error
1524
+		if (! $field_settings instanceof EE_Datetime_Field) {
1525
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1526
+				'event_espresso'), $field_name));
1527
+		}
1528
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
+		//the field.
1530
+		$this->_timezone = $field_settings->get_timezone();
1531
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
+	}
1533
+
1534
+
1535
+
1536
+	/**
1537
+	 * This returns the current time in a format setup for a query on this model.
1538
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
+	 * it will return:
1540
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
+	 *  NOW
1542
+	 *  - or a unix timestamp (equivalent to time())
1543
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
+	 * @since 4.6.x
1547
+	 * @param string $field_name       The field the current time is needed for.
1548
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
+	 *                                 formatted string matching the set format for the field in the set timezone will
1550
+	 *                                 be returned.
1551
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
+	 *                                 exception is triggered.
1555
+	 */
1556
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
+	{
1558
+		$formats = $this->get_formats_for($field_name);
1559
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
+		if ($timestamp) {
1561
+			return $DateTime->format('U');
1562
+		}
1563
+		//not returning timestamp, so return formatted string in timezone.
1564
+		switch ($what) {
1565
+			case 'time' :
1566
+				return $DateTime->format($formats[1]);
1567
+				break;
1568
+			case 'date' :
1569
+				return $DateTime->format($formats[0]);
1570
+				break;
1571
+			default :
1572
+				return $DateTime->format(implode(' ', $formats));
1573
+				break;
1574
+		}
1575
+	}
1576
+
1577
+
1578
+
1579
+	/**
1580
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
+	 * for the model are.  Returns a DateTime object.
1582
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
+	 * ignored.
1585
+	 *
1586
+	 * @param string $field_name      The field being setup.
1587
+	 * @param string $timestring      The date time string being used.
1588
+	 * @param string $incoming_format The format for the time string.
1589
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
+	 *                                format is
1592
+	 *                                'U', this is ignored.
1593
+	 * @return DateTime
1594
+	 * @throws EE_Error
1595
+	 */
1596
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
+	{
1598
+		//just using this to ensure the timezone is set correctly internally
1599
+		$this->get_formats_for($field_name);
1600
+		//load EEH_DTT_Helper
1601
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1604
+	}
1605
+
1606
+
1607
+
1608
+	/**
1609
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1610
+	 *
1611
+	 * @return EE_Table_Base[]
1612
+	 */
1613
+	public function get_tables()
1614
+	{
1615
+		return $this->_tables;
1616
+	}
1617
+
1618
+
1619
+
1620
+	/**
1621
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1622
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1623
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1624
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1625
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1626
+	 * model object with EVT_ID = 1
1627
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1628
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1629
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1630
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1631
+	 * are not specified)
1632
+	 *
1633
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1634
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1635
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1636
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1637
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1638
+	 *                                         ID=34, we'd use this method as follows:
1639
+	 *                                         EEM_Transaction::instance()->update(
1640
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1641
+	 *                                         array(array('TXN_ID'=>34)));
1642
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1643
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1644
+	 *                                         consider updating Question's QST_admin_label field is of type
1645
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1646
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1647
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1648
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1649
+	 *                                         TRUE, it is assumed that you've already called
1650
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1651
+	 *                                         malicious javascript. However, if
1652
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1653
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1654
+	 *                                         and every other field, before insertion. We provide this parameter
1655
+	 *                                         because model objects perform their prepare_for_set function on all
1656
+	 *                                         their values, and so don't need to be called again (and in many cases,
1657
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1658
+	 *                                         prepare_for_set method...)
1659
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1660
+	 *                                         in this model's entity map according to $fields_n_values that match
1661
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1662
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1663
+	 *                                         could get out-of-sync with the database
1664
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1665
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1666
+	 *                                         bad)
1667
+	 * @throws EE_Error
1668
+	 */
1669
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1670
+	{
1671
+		if (! is_array($query_params)) {
1672
+			EE_Error::doing_it_wrong('EEM_Base::update',
1673
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1674
+					gettype($query_params)), '4.6.0');
1675
+			$query_params = array();
1676
+		}
1677
+		/**
1678
+		 * Action called before a model update call has been made.
1679
+		 *
1680
+		 * @param EEM_Base $model
1681
+		 * @param array    $fields_n_values the updated fields and their new values
1682
+		 * @param array    $query_params    @see EEM_Base::get_all()
1683
+		 */
1684
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1685
+		/**
1686
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1687
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1688
+		 *
1689
+		 * @param array    $fields_n_values fields and their new values
1690
+		 * @param EEM_Base $model           the model being queried
1691
+		 * @param array    $query_params    see EEM_Base::get_all()
1692
+		 */
1693
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1694
+			$query_params);
1695
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1696
+		//to do that, for each table, verify that it's PK isn't null.
1697
+		$tables = $this->get_tables();
1698
+		//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
1699
+		//NOTE: we should make this code more efficient by NOT querying twice
1700
+		//before the real update, but that needs to first go through ALPHA testing
1701
+		//as it's dangerous. says Mike August 8 2014
1702
+		//we want to make sure the default_where strategy is ignored
1703
+		$this->_ignore_where_strategy = true;
1704
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1705
+		foreach ($wpdb_select_results as $wpdb_result) {
1706
+			// type cast stdClass as array
1707
+			$wpdb_result = (array)$wpdb_result;
1708
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1709
+			if ($this->has_primary_key_field()) {
1710
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1711
+			} else {
1712
+				//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)
1713
+				$main_table_pk_value = null;
1714
+			}
1715
+			//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
1716
+			//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
1717
+			if (count($tables) > 1) {
1718
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1719
+				//in that table, and so we'll want to insert one
1720
+				foreach ($tables as $table_obj) {
1721
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1722
+					//if there is no private key for this table on the results, it means there's no entry
1723
+					//in this table, right? so insert a row in the current table, using any fields available
1724
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1725
+						   && $wpdb_result[$this_table_pk_column])
1726
+					) {
1727
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1728
+							$main_table_pk_value);
1729
+						//if we died here, report the error
1730
+						if (! $success) {
1731
+							return false;
1732
+						}
1733
+					}
1734
+				}
1735
+			}
1736
+			//				//and now check that if we have cached any models by that ID on the model, that
1737
+			//				//they also get updated properly
1738
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1739
+			//				if( $model_object ){
1740
+			//					foreach( $fields_n_values as $field => $value ){
1741
+			//						$model_object->set($field, $value);
1742
+			//let's make sure default_where strategy is followed now
1743
+			$this->_ignore_where_strategy = false;
1744
+		}
1745
+		//if we want to keep model objects in sync, AND
1746
+		//if this wasn't called from a model object (to update itself)
1747
+		//then we want to make sure we keep all the existing
1748
+		//model objects in sync with the db
1749
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1750
+			if ($this->has_primary_key_field()) {
1751
+				$model_objs_affected_ids = $this->get_col($query_params);
1752
+			} else {
1753
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1754
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1755
+				$model_objs_affected_ids = array();
1756
+				foreach ($models_affected_key_columns as $row) {
1757
+					$combined_index_key = $this->get_index_primary_key_string($row);
1758
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1759
+				}
1760
+			}
1761
+			if (! $model_objs_affected_ids) {
1762
+				//wait wait wait- if nothing was affected let's stop here
1763
+				return 0;
1764
+			}
1765
+			foreach ($model_objs_affected_ids as $id) {
1766
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1767
+				if ($model_obj_in_entity_map) {
1768
+					foreach ($fields_n_values as $field => $new_value) {
1769
+						$model_obj_in_entity_map->set($field, $new_value);
1770
+					}
1771
+				}
1772
+			}
1773
+			//if there is a primary key on this model, we can now do a slight optimization
1774
+			if ($this->has_primary_key_field()) {
1775
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1776
+				$query_params = array(
1777
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1778
+					'limit'                    => count($model_objs_affected_ids),
1779
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1780
+				);
1781
+			}
1782
+		}
1783
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1784
+		$SQL = "UPDATE "
1785
+			   . $model_query_info->get_full_join_sql()
1786
+			   . " SET "
1787
+			   . $this->_construct_update_sql($fields_n_values)
1788
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1789
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1790
+		/**
1791
+		 * Action called after a model update call has been made.
1792
+		 *
1793
+		 * @param EEM_Base $model
1794
+		 * @param array    $fields_n_values the updated fields and their new values
1795
+		 * @param array    $query_params    @see EEM_Base::get_all()
1796
+		 * @param int      $rows_affected
1797
+		 */
1798
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1799
+		return $rows_affected;//how many supposedly got updated
1800
+	}
1801
+
1802
+
1803
+
1804
+	/**
1805
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1806
+	 * are teh values of the field specified (or by default the primary key field)
1807
+	 * that matched the query params. Note that you should pass the name of the
1808
+	 * model FIELD, not the database table's column name.
1809
+	 *
1810
+	 * @param array  $query_params @see EEM_Base::get_all()
1811
+	 * @param string $field_to_select
1812
+	 * @return array just like $wpdb->get_col()
1813
+	 * @throws EE_Error
1814
+	 */
1815
+	public function get_col($query_params = array(), $field_to_select = null)
1816
+	{
1817
+		if ($field_to_select) {
1818
+			$field = $this->field_settings_for($field_to_select);
1819
+		} elseif ($this->has_primary_key_field()) {
1820
+			$field = $this->get_primary_key_field();
1821
+		} else {
1822
+			//no primary key, just grab the first column
1823
+			$field = reset($this->field_settings());
1824
+		}
1825
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1826
+		$select_expressions = $field->get_qualified_column();
1827
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1828
+		return $this->_do_wpdb_query('get_col', array($SQL));
1829
+	}
1830
+
1831
+
1832
+
1833
+	/**
1834
+	 * Returns a single column value for a single row from the database
1835
+	 *
1836
+	 * @param array  $query_params    @see EEM_Base::get_all()
1837
+	 * @param string $field_to_select @see EEM_Base::get_col()
1838
+	 * @return string
1839
+	 * @throws EE_Error
1840
+	 */
1841
+	public function get_var($query_params = array(), $field_to_select = null)
1842
+	{
1843
+		$query_params['limit'] = 1;
1844
+		$col = $this->get_col($query_params, $field_to_select);
1845
+		if (! empty($col)) {
1846
+			return reset($col);
1847
+		}
1848
+		return null;
1849
+	}
1850
+
1851
+
1852
+
1853
+	/**
1854
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1855
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1856
+	 * injection, but currently no further filtering is done
1857
+	 *
1858
+	 * @global      $wpdb
1859
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1860
+	 *                               be updated to in the DB
1861
+	 * @return string of SQL
1862
+	 * @throws EE_Error
1863
+	 */
1864
+	public function _construct_update_sql($fields_n_values)
1865
+	{
1866
+		/** @type WPDB $wpdb */
1867
+		global $wpdb;
1868
+		$cols_n_values = array();
1869
+		foreach ($fields_n_values as $field_name => $value) {
1870
+			$field_obj = $this->field_settings_for($field_name);
1871
+			//if the value is NULL, we want to assign the value to that.
1872
+			//wpdb->prepare doesn't really handle that properly
1873
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1874
+			$value_sql = $prepared_value === null ? 'NULL'
1875
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1876
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1877
+		}
1878
+		return implode(",", $cols_n_values);
1879
+	}
1880
+
1881
+
1882
+
1883
+	/**
1884
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1885
+	 * Performs a HARD delete, meaning the database row should always be removed,
1886
+	 * not just have a flag field on it switched
1887
+	 * Wrapper for EEM_Base::delete_permanently()
1888
+	 *
1889
+	 * @param mixed $id
1890
+	 * @param boolean $allow_blocking
1891
+	 * @return int the number of rows deleted
1892
+	 * @throws EE_Error
1893
+	 */
1894
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1895
+	{
1896
+		return $this->delete_permanently(
1897
+			array(
1898
+				array($this->get_primary_key_field()->get_name() => $id),
1899
+				'limit' => 1,
1900
+			),
1901
+			$allow_blocking
1902
+		);
1903
+	}
1904
+
1905
+
1906
+
1907
+	/**
1908
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1909
+	 * Wrapper for EEM_Base::delete()
1910
+	 *
1911
+	 * @param mixed $id
1912
+	 * @param boolean $allow_blocking
1913
+	 * @return int the number of rows deleted
1914
+	 * @throws EE_Error
1915
+	 */
1916
+	public function delete_by_ID($id, $allow_blocking = true)
1917
+	{
1918
+		return $this->delete(
1919
+			array(
1920
+				array($this->get_primary_key_field()->get_name() => $id),
1921
+				'limit' => 1,
1922
+			),
1923
+			$allow_blocking
1924
+		);
1925
+	}
1926
+
1927
+
1928
+
1929
+	/**
1930
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1931
+	 * meaning if the model has a field that indicates its been "trashed" or
1932
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1933
+	 *
1934
+	 * @see EEM_Base::delete_permanently
1935
+	 * @param array   $query_params
1936
+	 * @param boolean $allow_blocking
1937
+	 * @return int how many rows got deleted
1938
+	 * @throws EE_Error
1939
+	 */
1940
+	public function delete($query_params, $allow_blocking = true)
1941
+	{
1942
+		return $this->delete_permanently($query_params, $allow_blocking);
1943
+	}
1944
+
1945
+
1946
+
1947
+	/**
1948
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1949
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1950
+	 * as archived, not actually deleted
1951
+	 *
1952
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1953
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1954
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1955
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1956
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1957
+	 *                                DB
1958
+	 * @return int how many rows got deleted
1959
+	 * @throws EE_Error
1960
+	 */
1961
+	public function delete_permanently($query_params, $allow_blocking = true)
1962
+	{
1963
+		/**
1964
+		 * Action called just before performing a real deletion query. You can use the
1965
+		 * model and its $query_params to find exactly which items will be deleted
1966
+		 *
1967
+		 * @param EEM_Base $model
1968
+		 * @param array    $query_params   @see EEM_Base::get_all()
1969
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1970
+		 *                                 to block (prevent) this deletion
1971
+		 */
1972
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1973
+		//some MySQL databases may be running safe mode, which may restrict
1974
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1975
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1976
+		//to delete them
1977
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1978
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1979
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1980
+			$columns_and_ids_for_deleting
1981
+		);
1982
+		/**
1983
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1984
+		 *
1985
+		 * @param EEM_Base $this  The model instance being acted on.
1986
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1987
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1988
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1989
+		 *                                                  derived from the incoming query parameters.
1990
+		 *                                                  @see details on the structure of this array in the phpdocs
1991
+		 *                                                  for the `_get_ids_for_delete_method`
1992
+		 *
1993
+		 */
1994
+		do_action('AHEE__EEM_Base__delete__before_query',
1995
+			$this,
1996
+			$query_params,
1997
+			$allow_blocking,
1998
+			$columns_and_ids_for_deleting
1999
+		);
2000
+		if ($deletion_where_query_part) {
2001
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2002
+			$table_aliases = array_keys($this->_tables);
2003
+			$SQL = "DELETE "
2004
+				   . implode(", ", $table_aliases)
2005
+				   . " FROM "
2006
+				   . $model_query_info->get_full_join_sql()
2007
+				   . " WHERE "
2008
+				   . $deletion_where_query_part;
2009
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2010
+		} else {
2011
+			$rows_deleted = 0;
2012
+		}
2013
+
2014
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2015
+		//there was no error with the delete query.
2016
+		if ($this->has_primary_key_field()
2017
+			&& $rows_deleted !== false
2018
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2019
+		) {
2020
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2021
+			foreach ($ids_for_removal as $id) {
2022
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2023
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2024
+				}
2025
+			}
2026
+
2027
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2028
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2029
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2030
+			// (although it is possible).
2031
+			//Note this can be skipped by using the provided filter and returning false.
2032
+			if (apply_filters(
2033
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2034
+				! $this instanceof EEM_Extra_Meta,
2035
+				$this
2036
+			)) {
2037
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2038
+					0 => array(
2039
+						'EXM_type' => $this->get_this_model_name(),
2040
+						'OBJ_ID'   => array(
2041
+							'IN',
2042
+							$ids_for_removal
2043
+						)
2044
+					)
2045
+				));
2046
+			}
2047
+		}
2048
+
2049
+		/**
2050
+		 * Action called just after performing a real deletion query. Although at this point the
2051
+		 * items should have been deleted
2052
+		 *
2053
+		 * @param EEM_Base $model
2054
+		 * @param array    $query_params @see EEM_Base::get_all()
2055
+		 * @param int      $rows_deleted
2056
+		 */
2057
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
+		return $rows_deleted;//how many supposedly got deleted
2059
+	}
2060
+
2061
+
2062
+
2063
+	/**
2064
+	 * Checks all the relations that throw error messages when there are blocking related objects
2065
+	 * for related model objects. If there are any related model objects on those relations,
2066
+	 * adds an EE_Error, and return true
2067
+	 *
2068
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2069
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2070
+	 *                                                 should be ignored when determining whether there are related
2071
+	 *                                                 model objects which block this model object's deletion. Useful
2072
+	 *                                                 if you know A is related to B and are considering deleting A,
2073
+	 *                                                 but want to see if A has any other objects blocking its deletion
2074
+	 *                                                 before removing the relation between A and B
2075
+	 * @return boolean
2076
+	 * @throws EE_Error
2077
+	 */
2078
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
+	{
2080
+		//first, if $ignore_this_model_obj was supplied, get its model
2081
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
+			$ignored_model = $ignore_this_model_obj->get_model();
2083
+		} else {
2084
+			$ignored_model = null;
2085
+		}
2086
+		//now check all the relations of $this_model_obj_or_id and see if there
2087
+		//are any related model objects blocking it?
2088
+		$is_blocked = false;
2089
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2091
+				//if $ignore_this_model_obj was supplied, then for the query
2092
+				//on that model needs to be told to ignore $ignore_this_model_obj
2093
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2095
+						array(
2096
+							$ignored_model->get_primary_key_field()->get_name() => array(
2097
+								'!=',
2098
+								$ignore_this_model_obj->ID(),
2099
+							),
2100
+						),
2101
+					));
2102
+				} else {
2103
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2104
+				}
2105
+				if ($related_model_objects) {
2106
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2107
+					$is_blocked = true;
2108
+				}
2109
+			}
2110
+		}
2111
+		return $is_blocked;
2112
+	}
2113
+
2114
+
2115
+	/**
2116
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2117
+	 * @param array $row_results_for_deleting
2118
+	 * @param bool  $allow_blocking
2119
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2120
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2121
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2122
+	 *                 deleted. Example:
2123
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2124
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2125
+	 *                 where each element is a group of columns and values that get deleted. Example:
2126
+	 *                      array(
2127
+	 *                          0 => array(
2128
+	 *                              'Term_Relationship.object_id' => 1
2129
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2130
+	 *                          ),
2131
+	 *                          1 => array(
2132
+	 *                              'Term_Relationship.object_id' => 1
2133
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2134
+	 *                          )
2135
+	 *                      )
2136
+	 * @throws EE_Error
2137
+	 */
2138
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2139
+	{
2140
+		$ids_to_delete_indexed_by_column = array();
2141
+		if ($this->has_primary_key_field()) {
2142
+			$primary_table = $this->_get_main_table();
2143
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2144
+			$other_tables = $this->_get_other_tables();
2145
+			$ids_to_delete_indexed_by_column = $query = array();
2146
+			foreach ($row_results_for_deleting as $item_to_delete) {
2147
+				//before we mark this item for deletion,
2148
+				//make sure there's no related entities blocking its deletion (if we're checking)
2149
+				if (
2150
+					$allow_blocking
2151
+					&& $this->delete_is_blocked_by_related_models(
2152
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2153
+					)
2154
+				) {
2155
+					continue;
2156
+				}
2157
+				//primary table deletes
2158
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2159
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2160
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2161
+				}
2162
+			}
2163
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2164
+			$fields = $this->get_combined_primary_key_fields();
2165
+			foreach ($row_results_for_deleting as $item_to_delete) {
2166
+				$ids_to_delete_indexed_by_column_for_row = array();
2167
+				foreach ($fields as $cpk_field) {
2168
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2169
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2170
+							$item_to_delete[$cpk_field->get_qualified_column()];
2171
+					}
2172
+				}
2173
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2174
+			}
2175
+		} else {
2176
+			//so there's no primary key and no combined key...
2177
+			//sorry, can't help you
2178
+			throw new EE_Error(
2179
+				sprintf(
2180
+					__(
2181
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2182
+						"event_espresso"
2183
+					), get_class($this)
2184
+				)
2185
+			);
2186
+		}
2187
+		return $ids_to_delete_indexed_by_column;
2188
+	}
2189
+
2190
+
2191
+	/**
2192
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2193
+	 * the corresponding query_part for the query performing the delete.
2194
+	 *
2195
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2196
+	 * @return string
2197
+	 * @throws EE_Error
2198
+	 */
2199
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2200
+		$query_part = '';
2201
+		if (empty($ids_to_delete_indexed_by_column)) {
2202
+			return $query_part;
2203
+		} elseif ($this->has_primary_key_field()) {
2204
+			$query = array();
2205
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2206
+				//make sure we have unique $ids
2207
+				$ids = array_unique($ids);
2208
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2209
+			}
2210
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2211
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2212
+			$ways_to_identify_a_row = array();
2213
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2214
+				$values_for_each_combined_primary_key_for_a_row = array();
2215
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2216
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2217
+				}
2218
+				$ways_to_identify_a_row[] = '('
2219
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2220
+											. ')';
2221
+			}
2222
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2223
+		}
2224
+		return $query_part;
2225
+	}
2226
+
2227
+
2228
+
2229
+	/**
2230
+	 * Gets the model field by the fully qualified name
2231
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2232
+	 * @return EE_Model_Field_Base
2233
+	 */
2234
+	public function get_field_by_column($qualified_column_name)
2235
+	{
2236
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2237
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2238
+			   return $field_obj;
2239
+		   }
2240
+	   }
2241
+		throw new EE_Error(
2242
+			sprintf(
2243
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2244
+				$this->get_this_model_name(),
2245
+				$qualified_column_name
2246
+			)
2247
+		);
2248
+	}
2249
+
2250
+
2251
+
2252
+	/**
2253
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2254
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2255
+	 * column
2256
+	 *
2257
+	 * @param array  $query_params   like EEM_Base::get_all's
2258
+	 * @param string $field_to_count field on model to count by (not column name)
2259
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2260
+	 *                               that by the setting $distinct to TRUE;
2261
+	 * @return int
2262
+	 * @throws EE_Error
2263
+	 */
2264
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2265
+	{
2266
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2267
+		if ($field_to_count) {
2268
+			$field_obj = $this->field_settings_for($field_to_count);
2269
+			$column_to_count = $field_obj->get_qualified_column();
2270
+		} elseif ($this->has_primary_key_field()) {
2271
+			$pk_field_obj = $this->get_primary_key_field();
2272
+			$column_to_count = $pk_field_obj->get_qualified_column();
2273
+		} else {
2274
+			//there's no primary key
2275
+			//if we're counting distinct items, and there's no primary key,
2276
+			//we need to list out the columns for distinction;
2277
+			//otherwise we can just use star
2278
+			if ($distinct) {
2279
+				$columns_to_use = array();
2280
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2281
+					$columns_to_use[] = $field_obj->get_qualified_column();
2282
+				}
2283
+				$column_to_count = implode(',', $columns_to_use);
2284
+			} else {
2285
+				$column_to_count = '*';
2286
+			}
2287
+		}
2288
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2289
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2297
+	 *
2298
+	 * @param array  $query_params like EEM_Base::get_all
2299
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2300
+	 * @return float
2301
+	 * @throws EE_Error
2302
+	 */
2303
+	public function sum($query_params, $field_to_sum = null)
2304
+	{
2305
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
+		if ($field_to_sum) {
2307
+			$field_obj = $this->field_settings_for($field_to_sum);
2308
+		} else {
2309
+			$field_obj = $this->get_primary_key_field();
2310
+		}
2311
+		$column_to_count = $field_obj->get_qualified_column();
2312
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2314
+		$data_type = $field_obj->get_wpdb_data_type();
2315
+		if ($data_type === '%d' || $data_type === '%s') {
2316
+			return (float)$return_value;
2317
+		}
2318
+		//must be %f
2319
+		return (float)$return_value;
2320
+	}
2321
+
2322
+
2323
+
2324
+	/**
2325
+	 * Just calls the specified method on $wpdb with the given arguments
2326
+	 * Consolidates a little extra error handling code
2327
+	 *
2328
+	 * @param string $wpdb_method
2329
+	 * @param array  $arguments_to_provide
2330
+	 * @throws EE_Error
2331
+	 * @global wpdb  $wpdb
2332
+	 * @return mixed
2333
+	 */
2334
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
+	{
2336
+		//if we're in maintenance mode level 2, DON'T run any queries
2337
+		//because level 2 indicates the database needs updating and
2338
+		//is probably out of sync with the code
2339
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
+			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.",
2341
+				"event_espresso")));
2342
+		}
2343
+		/** @type WPDB $wpdb */
2344
+		global $wpdb;
2345
+		if (! method_exists($wpdb, $wpdb_method)) {
2346
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2347
+				'event_espresso'), $wpdb_method));
2348
+		}
2349
+		if (WP_DEBUG) {
2350
+			$old_show_errors_value = $wpdb->show_errors;
2351
+			$wpdb->show_errors(false);
2352
+		}
2353
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2354
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2355
+		if (WP_DEBUG) {
2356
+			$wpdb->show_errors($old_show_errors_value);
2357
+			if (! empty($wpdb->last_error)) {
2358
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2359
+			}
2360
+			if ($result === false) {
2361
+				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"',
2362
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2363
+			}
2364
+		} elseif ($result === false) {
2365
+			EE_Error::add_error(
2366
+				sprintf(
2367
+					__('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"',
2368
+						'event_espresso'),
2369
+					$wpdb_method,
2370
+					var_export($arguments_to_provide, true),
2371
+					$wpdb->last_error
2372
+				),
2373
+				__FILE__,
2374
+				__FUNCTION__,
2375
+				__LINE__
2376
+			);
2377
+		}
2378
+		return $result;
2379
+	}
2380
+
2381
+
2382
+
2383
+	/**
2384
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2385
+	 * and if there's an error tries to verify the DB is correct. Uses
2386
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2387
+	 * we should try to fix the EE core db, the addons, or just give up
2388
+	 *
2389
+	 * @param string $wpdb_method
2390
+	 * @param array  $arguments_to_provide
2391
+	 * @return mixed
2392
+	 */
2393
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2394
+	{
2395
+		/** @type WPDB $wpdb */
2396
+		global $wpdb;
2397
+		$wpdb->last_error = null;
2398
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2399
+		// was there an error running the query? but we don't care on new activations
2400
+		// (we're going to setup the DB anyway on new activations)
2401
+		if (($result === false || ! empty($wpdb->last_error))
2402
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2403
+		) {
2404
+			switch (EEM_Base::$_db_verification_level) {
2405
+				case EEM_Base::db_verified_none :
2406
+					// let's double-check core's DB
2407
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2408
+					break;
2409
+				case EEM_Base::db_verified_core :
2410
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2411
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2412
+					break;
2413
+				case EEM_Base::db_verified_addons :
2414
+					// ummmm... you in trouble
2415
+					return $result;
2416
+					break;
2417
+			}
2418
+			if (! empty($error_message)) {
2419
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2420
+				trigger_error($error_message);
2421
+			}
2422
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2423
+		}
2424
+		return $result;
2425
+	}
2426
+
2427
+
2428
+
2429
+	/**
2430
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2431
+	 * EEM_Base::$_db_verification_level
2432
+	 *
2433
+	 * @param string $wpdb_method
2434
+	 * @param array  $arguments_to_provide
2435
+	 * @return string
2436
+	 */
2437
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2438
+	{
2439
+		/** @type WPDB $wpdb */
2440
+		global $wpdb;
2441
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2442
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2443
+		$error_message = sprintf(
2444
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2445
+				'event_espresso'),
2446
+			$wpdb->last_error,
2447
+			$wpdb_method,
2448
+			wp_json_encode($arguments_to_provide)
2449
+		);
2450
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2451
+		return $error_message;
2452
+	}
2453
+
2454
+
2455
+
2456
+	/**
2457
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2458
+	 * EEM_Base::$_db_verification_level
2459
+	 *
2460
+	 * @param $wpdb_method
2461
+	 * @param $arguments_to_provide
2462
+	 * @return string
2463
+	 */
2464
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2465
+	{
2466
+		/** @type WPDB $wpdb */
2467
+		global $wpdb;
2468
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2469
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2470
+		$error_message = sprintf(
2471
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2472
+				'event_espresso'),
2473
+			$wpdb->last_error,
2474
+			$wpdb_method,
2475
+			wp_json_encode($arguments_to_provide)
2476
+		);
2477
+		EE_System::instance()->initialize_addons();
2478
+		return $error_message;
2479
+	}
2480
+
2481
+
2482
+
2483
+	/**
2484
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2485
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2486
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2487
+	 * ..."
2488
+	 *
2489
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2490
+	 * @return string
2491
+	 */
2492
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2493
+	{
2494
+		return " FROM " . $model_query_info->get_full_join_sql() .
2495
+			   $model_query_info->get_where_sql() .
2496
+			   $model_query_info->get_group_by_sql() .
2497
+			   $model_query_info->get_having_sql() .
2498
+			   $model_query_info->get_order_by_sql() .
2499
+			   $model_query_info->get_limit_sql();
2500
+	}
2501
+
2502
+
2503
+
2504
+	/**
2505
+	 * Set to easily debug the next X queries ran from this model.
2506
+	 *
2507
+	 * @param int $count
2508
+	 */
2509
+	public function show_next_x_db_queries($count = 1)
2510
+	{
2511
+		$this->_show_next_x_db_queries = $count;
2512
+	}
2513
+
2514
+
2515
+
2516
+	/**
2517
+	 * @param $sql_query
2518
+	 */
2519
+	public function show_db_query_if_previously_requested($sql_query)
2520
+	{
2521
+		if ($this->_show_next_x_db_queries > 0) {
2522
+			echo $sql_query;
2523
+			$this->_show_next_x_db_queries--;
2524
+		}
2525
+	}
2526
+
2527
+
2528
+
2529
+	/**
2530
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2531
+	 * There are the 3 cases:
2532
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2533
+	 * $otherModelObject has no ID, it is first saved.
2534
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2535
+	 * has no ID, it is first saved.
2536
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2537
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2538
+	 * join table
2539
+	 *
2540
+	 * @param        EE_Base_Class                     /int $thisModelObject
2541
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2542
+	 * @param string $relationName                     , key in EEM_Base::_relations
2543
+	 *                                                 an attendee to a group, you also want to specify which role they
2544
+	 *                                                 will have in that group. So you would use this parameter to
2545
+	 *                                                 specify array('role-column-name'=>'role-id')
2546
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2547
+	 *                                                 to for relation to methods that allow you to further specify
2548
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2549
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2550
+	 *                                                 because these will be inserted in any new rows created as well.
2551
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2552
+	 * @throws EE_Error
2553
+	 */
2554
+	public function add_relationship_to(
2555
+		$id_or_obj,
2556
+		$other_model_id_or_obj,
2557
+		$relationName,
2558
+		$extra_join_model_fields_n_values = array()
2559
+	) {
2560
+		$relation_obj = $this->related_settings_for($relationName);
2561
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2562
+	}
2563
+
2564
+
2565
+
2566
+	/**
2567
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2568
+	 * There are the 3 cases:
2569
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2570
+	 * error
2571
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2572
+	 * an error
2573
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2574
+	 *
2575
+	 * @param        EE_Base_Class /int $id_or_obj
2576
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2577
+	 * @param string $relationName key in EEM_Base::_relations
2578
+	 * @return boolean of success
2579
+	 * @throws EE_Error
2580
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2581
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2582
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2583
+	 *                             because these will be inserted in any new rows created as well.
2584
+	 */
2585
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2586
+	{
2587
+		$relation_obj = $this->related_settings_for($relationName);
2588
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2589
+	}
2590
+
2591
+
2592
+
2593
+	/**
2594
+	 * @param mixed           $id_or_obj
2595
+	 * @param string          $relationName
2596
+	 * @param array           $where_query_params
2597
+	 * @param EE_Base_Class[] objects to which relations were removed
2598
+	 * @return \EE_Base_Class[]
2599
+	 * @throws EE_Error
2600
+	 */
2601
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2602
+	{
2603
+		$relation_obj = $this->related_settings_for($relationName);
2604
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2605
+	}
2606
+
2607
+
2608
+
2609
+	/**
2610
+	 * Gets all the related items of the specified $model_name, using $query_params.
2611
+	 * Note: by default, we remove the "default query params"
2612
+	 * because we want to get even deleted items etc.
2613
+	 *
2614
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2615
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2616
+	 * @param array  $query_params like EEM_Base::get_all
2617
+	 * @return EE_Base_Class[]
2618
+	 * @throws EE_Error
2619
+	 */
2620
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2621
+	{
2622
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2623
+		$relation_settings = $this->related_settings_for($model_name);
2624
+		return $relation_settings->get_all_related($model_obj, $query_params);
2625
+	}
2626
+
2627
+
2628
+
2629
+	/**
2630
+	 * Deletes all the model objects across the relation indicated by $model_name
2631
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2632
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2633
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2634
+	 *
2635
+	 * @param EE_Base_Class|int|string $id_or_obj
2636
+	 * @param string                   $model_name
2637
+	 * @param array                    $query_params
2638
+	 * @return int how many deleted
2639
+	 * @throws EE_Error
2640
+	 */
2641
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2642
+	{
2643
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2644
+		$relation_settings = $this->related_settings_for($model_name);
2645
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2646
+	}
2647
+
2648
+
2649
+
2650
+	/**
2651
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2652
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2653
+	 * the model objects can't be hard deleted because of blocking related model objects,
2654
+	 * just does a soft-delete on them instead.
2655
+	 *
2656
+	 * @param EE_Base_Class|int|string $id_or_obj
2657
+	 * @param string                   $model_name
2658
+	 * @param array                    $query_params
2659
+	 * @return int how many deleted
2660
+	 * @throws EE_Error
2661
+	 */
2662
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2663
+	{
2664
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2665
+		$relation_settings = $this->related_settings_for($model_name);
2666
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2667
+	}
2668
+
2669
+
2670
+
2671
+	/**
2672
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2673
+	 * unless otherwise specified in the $query_params
2674
+	 *
2675
+	 * @param        int             /EE_Base_Class $id_or_obj
2676
+	 * @param string $model_name     like 'Event', or 'Registration'
2677
+	 * @param array  $query_params   like EEM_Base::get_all's
2678
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2679
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2680
+	 *                               that by the setting $distinct to TRUE;
2681
+	 * @return int
2682
+	 * @throws EE_Error
2683
+	 */
2684
+	public function count_related(
2685
+		$id_or_obj,
2686
+		$model_name,
2687
+		$query_params = array(),
2688
+		$field_to_count = null,
2689
+		$distinct = false
2690
+	) {
2691
+		$related_model = $this->get_related_model_obj($model_name);
2692
+		//we're just going to use the query params on the related model's normal get_all query,
2693
+		//except add a condition to say to match the current mod
2694
+		if (! isset($query_params['default_where_conditions'])) {
2695
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696
+		}
2697
+		$this_model_name = $this->get_this_model_name();
2698
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2700
+		return $related_model->count($query_params, $field_to_count, $distinct);
2701
+	}
2702
+
2703
+
2704
+
2705
+	/**
2706
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2707
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2708
+	 *
2709
+	 * @param        int           /EE_Base_Class $id_or_obj
2710
+	 * @param string $model_name   like 'Event', or 'Registration'
2711
+	 * @param array  $query_params like EEM_Base::get_all's
2712
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2713
+	 * @return float
2714
+	 * @throws EE_Error
2715
+	 */
2716
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2717
+	{
2718
+		$related_model = $this->get_related_model_obj($model_name);
2719
+		if (! is_array($query_params)) {
2720
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2721
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2722
+					gettype($query_params)), '4.6.0');
2723
+			$query_params = array();
2724
+		}
2725
+		//we're just going to use the query params on the related model's normal get_all query,
2726
+		//except add a condition to say to match the current mod
2727
+		if (! isset($query_params['default_where_conditions'])) {
2728
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729
+		}
2730
+		$this_model_name = $this->get_this_model_name();
2731
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2733
+		return $related_model->sum($query_params, $field_to_sum);
2734
+	}
2735
+
2736
+
2737
+
2738
+	/**
2739
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2740
+	 * $modelObject
2741
+	 *
2742
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2743
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2744
+	 * @param array               $query_params     like EEM_Base::get_all's
2745
+	 * @return EE_Base_Class
2746
+	 * @throws EE_Error
2747
+	 */
2748
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2749
+	{
2750
+		$query_params['limit'] = 1;
2751
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2752
+		if ($results) {
2753
+			return array_shift($results);
2754
+		}
2755
+		return null;
2756
+	}
2757
+
2758
+
2759
+
2760
+	/**
2761
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2762
+	 *
2763
+	 * @return string
2764
+	 */
2765
+	public function get_this_model_name()
2766
+	{
2767
+		return str_replace("EEM_", "", get_class($this));
2768
+	}
2769
+
2770
+
2771
+
2772
+	/**
2773
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2774
+	 *
2775
+	 * @return EE_Any_Foreign_Model_Name_Field
2776
+	 * @throws EE_Error
2777
+	 */
2778
+	public function get_field_containing_related_model_name()
2779
+	{
2780
+		foreach ($this->field_settings(true) as $field) {
2781
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2782
+				$field_with_model_name = $field;
2783
+			}
2784
+		}
2785
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2786
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2787
+				$this->get_this_model_name()));
2788
+		}
2789
+		return $field_with_model_name;
2790
+	}
2791
+
2792
+
2793
+
2794
+	/**
2795
+	 * Inserts a new entry into the database, for each table.
2796
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2797
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2798
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2799
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2800
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2801
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2802
+	 *
2803
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2804
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2805
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2806
+	 *                              of EEM_Base)
2807
+	 * @return int new primary key on main table that got inserted
2808
+	 * @throws EE_Error
2809
+	 */
2810
+	public function insert($field_n_values)
2811
+	{
2812
+		/**
2813
+		 * Filters the fields and their values before inserting an item using the models
2814
+		 *
2815
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2816
+		 * @param EEM_Base $model           the model used
2817
+		 */
2818
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2819
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2820
+			$main_table = $this->_get_main_table();
2821
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2822
+			if ($new_id !== false) {
2823
+				foreach ($this->_get_other_tables() as $other_table) {
2824
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2825
+				}
2826
+			}
2827
+			/**
2828
+			 * Done just after attempting to insert a new model object
2829
+			 *
2830
+			 * @param EEM_Base   $model           used
2831
+			 * @param array      $fields_n_values fields and their values
2832
+			 * @param int|string the              ID of the newly-inserted model object
2833
+			 */
2834
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2835
+			return $new_id;
2836
+		}
2837
+		return false;
2838
+	}
2839
+
2840
+
2841
+
2842
+	/**
2843
+	 * Checks that the result would satisfy the unique indexes on this model
2844
+	 *
2845
+	 * @param array  $field_n_values
2846
+	 * @param string $action
2847
+	 * @return boolean
2848
+	 * @throws EE_Error
2849
+	 */
2850
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2851
+	{
2852
+		foreach ($this->unique_indexes() as $index_name => $index) {
2853
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2854
+			if ($this->exists(array($uniqueness_where_params))) {
2855
+				EE_Error::add_error(
2856
+					sprintf(
2857
+						__(
2858
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2859
+							"event_espresso"
2860
+						),
2861
+						$action,
2862
+						$this->_get_class_name(),
2863
+						$index_name,
2864
+						implode(",", $index->field_names()),
2865
+						http_build_query($uniqueness_where_params)
2866
+					),
2867
+					__FILE__,
2868
+					__FUNCTION__,
2869
+					__LINE__
2870
+				);
2871
+				return false;
2872
+			}
2873
+		}
2874
+		return true;
2875
+	}
2876
+
2877
+
2878
+
2879
+	/**
2880
+	 * Checks the database for an item that conflicts (ie, if this item were
2881
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2882
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2883
+	 * can be either an EE_Base_Class or an array of fields n values
2884
+	 *
2885
+	 * @param EE_Base_Class|array $obj_or_fields_array
2886
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2887
+	 *                                                 when looking for conflicts
2888
+	 *                                                 (ie, if false, we ignore the model object's primary key
2889
+	 *                                                 when finding "conflicts". If true, it's also considered).
2890
+	 *                                                 Only works for INT primary key,
2891
+	 *                                                 STRING primary keys cannot be ignored
2892
+	 * @throws EE_Error
2893
+	 * @return EE_Base_Class|array
2894
+	 */
2895
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2896
+	{
2897
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2898
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2899
+		} elseif (is_array($obj_or_fields_array)) {
2900
+			$fields_n_values = $obj_or_fields_array;
2901
+		} else {
2902
+			throw new EE_Error(
2903
+				sprintf(
2904
+					__(
2905
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2906
+						"event_espresso"
2907
+					),
2908
+					get_class($this),
2909
+					$obj_or_fields_array
2910
+				)
2911
+			);
2912
+		}
2913
+		$query_params = array();
2914
+		if ($this->has_primary_key_field()
2915
+			&& ($include_primary_key
2916
+				|| $this->get_primary_key_field()
2917
+				   instanceof
2918
+				   EE_Primary_Key_String_Field)
2919
+			&& isset($fields_n_values[$this->primary_key_name()])
2920
+		) {
2921
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2922
+		}
2923
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2924
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2925
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2926
+		}
2927
+		//if there is nothing to base this search on, then we shouldn't find anything
2928
+		if (empty($query_params)) {
2929
+			return array();
2930
+		}
2931
+		return $this->get_one($query_params);
2932
+	}
2933
+
2934
+
2935
+
2936
+	/**
2937
+	 * Like count, but is optimized and returns a boolean instead of an int
2938
+	 *
2939
+	 * @param array $query_params
2940
+	 * @return boolean
2941
+	 * @throws EE_Error
2942
+	 */
2943
+	public function exists($query_params)
2944
+	{
2945
+		$query_params['limit'] = 1;
2946
+		return $this->count($query_params) > 0;
2947
+	}
2948
+
2949
+
2950
+
2951
+	/**
2952
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2953
+	 *
2954
+	 * @param int|string $id
2955
+	 * @return boolean
2956
+	 * @throws EE_Error
2957
+	 */
2958
+	public function exists_by_ID($id)
2959
+	{
2960
+		return $this->exists(
2961
+			array(
2962
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2963
+				array(
2964
+					$this->primary_key_name() => $id,
2965
+				),
2966
+			)
2967
+		);
2968
+	}
2969
+
2970
+
2971
+
2972
+	/**
2973
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2974
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2975
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2976
+	 * on the main table)
2977
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2978
+	 * cases where we want to call it directly rather than via insert().
2979
+	 *
2980
+	 * @access   protected
2981
+	 * @param EE_Table_Base $table
2982
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2983
+	 *                                       float
2984
+	 * @param int           $new_id          for now we assume only int keys
2985
+	 * @throws EE_Error
2986
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2987
+	 * @return int ID of new row inserted, or FALSE on failure
2988
+	 */
2989
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2990
+	{
2991
+		global $wpdb;
2992
+		$insertion_col_n_values = array();
2993
+		$format_for_insertion = array();
2994
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2995
+		foreach ($fields_on_table as $field_name => $field_obj) {
2996
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2997
+			if ($field_obj->is_auto_increment()) {
2998
+				continue;
2999
+			}
3000
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3001
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
3002
+			if ($prepared_value !== null) {
3003
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3004
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3005
+			}
3006
+		}
3007
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3008
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
3009
+			//so add the fk to the main table as a column
3010
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3011
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3012
+		}
3013
+		//insert the new entry
3014
+		$result = $this->_do_wpdb_query('insert',
3015
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3016
+		if ($result === false) {
3017
+			return false;
3018
+		}
3019
+		//ok, now what do we return for the ID of the newly-inserted thing?
3020
+		if ($this->has_primary_key_field()) {
3021
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3022
+				return $wpdb->insert_id;
3023
+			}
3024
+			//it's not an auto-increment primary key, so
3025
+			//it must have been supplied
3026
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
3027
+		}
3028
+		//we can't return a  primary key because there is none. instead return
3029
+		//a unique string indicating this model
3030
+		return $this->get_index_primary_key_string($fields_n_values);
3031
+	}
3032
+
3033
+
3034
+
3035
+	/**
3036
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3037
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3038
+	 * and there is no default, we pass it along. WPDB will take care of it)
3039
+	 *
3040
+	 * @param EE_Model_Field_Base $field_obj
3041
+	 * @param array               $fields_n_values
3042
+	 * @return mixed string|int|float depending on what the table column will be expecting
3043
+	 * @throws EE_Error
3044
+	 */
3045
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3046
+	{
3047
+		//if this field doesn't allow nullable, don't allow it
3048
+		if (
3049
+			! $field_obj->is_nullable()
3050
+			&& (
3051
+				! isset($fields_n_values[$field_obj->get_name()])
3052
+				|| $fields_n_values[$field_obj->get_name()] === null
3053
+			)
3054
+		) {
3055
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3056
+		}
3057
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3058
+			? $fields_n_values[$field_obj->get_name()]
3059
+			: null;
3060
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3061
+	}
3062
+
3063
+
3064
+
3065
+	/**
3066
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3067
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3068
+	 * the field's prepare_for_set() method.
3069
+	 *
3070
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3071
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3072
+	 *                                   top of file)
3073
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3074
+	 *                                   $value is a custom selection
3075
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3076
+	 */
3077
+	private function _prepare_value_for_use_in_db($value, $field)
3078
+	{
3079
+		if ($field && $field instanceof EE_Model_Field_Base) {
3080
+			switch ($this->_values_already_prepared_by_model_object) {
3081
+				/** @noinspection PhpMissingBreakStatementInspection */
3082
+				case self::not_prepared_by_model_object:
3083
+					$value = $field->prepare_for_set($value);
3084
+				//purposefully left out "return"
3085
+				case self::prepared_by_model_object:
3086
+					/** @noinspection SuspiciousAssignmentsInspection */
3087
+					$value = $field->prepare_for_use_in_db($value);
3088
+				case self::prepared_for_use_in_db:
3089
+					//leave the value alone
3090
+			}
3091
+			return $value;
3092
+		}
3093
+		return $value;
3094
+	}
3095
+
3096
+
3097
+
3098
+	/**
3099
+	 * Returns the main table on this model
3100
+	 *
3101
+	 * @return EE_Primary_Table
3102
+	 * @throws EE_Error
3103
+	 */
3104
+	protected function _get_main_table()
3105
+	{
3106
+		foreach ($this->_tables as $table) {
3107
+			if ($table instanceof EE_Primary_Table) {
3108
+				return $table;
3109
+			}
3110
+		}
3111
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3112
+			'event_espresso'), get_class($this)));
3113
+	}
3114
+
3115
+
3116
+
3117
+	/**
3118
+	 * table
3119
+	 * returns EE_Primary_Table table name
3120
+	 *
3121
+	 * @return string
3122
+	 * @throws EE_Error
3123
+	 */
3124
+	public function table()
3125
+	{
3126
+		return $this->_get_main_table()->get_table_name();
3127
+	}
3128
+
3129
+
3130
+
3131
+	/**
3132
+	 * table
3133
+	 * returns first EE_Secondary_Table table name
3134
+	 *
3135
+	 * @return string
3136
+	 */
3137
+	public function second_table()
3138
+	{
3139
+		// grab second table from tables array
3140
+		$second_table = end($this->_tables);
3141
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
+	}
3143
+
3144
+
3145
+
3146
+	/**
3147
+	 * get_table_obj_by_alias
3148
+	 * returns table name given it's alias
3149
+	 *
3150
+	 * @param string $table_alias
3151
+	 * @return EE_Primary_Table | EE_Secondary_Table
3152
+	 */
3153
+	public function get_table_obj_by_alias($table_alias = '')
3154
+	{
3155
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3156
+	}
3157
+
3158
+
3159
+
3160
+	/**
3161
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
+	 *
3163
+	 * @return EE_Secondary_Table[]
3164
+	 */
3165
+	protected function _get_other_tables()
3166
+	{
3167
+		$other_tables = array();
3168
+		foreach ($this->_tables as $table_alias => $table) {
3169
+			if ($table instanceof EE_Secondary_Table) {
3170
+				$other_tables[$table_alias] = $table;
3171
+			}
3172
+		}
3173
+		return $other_tables;
3174
+	}
3175
+
3176
+
3177
+
3178
+	/**
3179
+	 * Finds all the fields that correspond to the given table
3180
+	 *
3181
+	 * @param string $table_alias , array key in EEM_Base::_tables
3182
+	 * @return EE_Model_Field_Base[]
3183
+	 */
3184
+	public function _get_fields_for_table($table_alias)
3185
+	{
3186
+		return $this->_fields[$table_alias];
3187
+	}
3188
+
3189
+
3190
+
3191
+	/**
3192
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3193
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
+	 * related Registration, Transaction, and Payment models.
3197
+	 *
3198
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3199
+	 * @return EE_Model_Query_Info_Carrier
3200
+	 * @throws EE_Error
3201
+	 */
3202
+	public function _extract_related_models_from_query($query_params)
3203
+	{
3204
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
+		if (array_key_exists(0, $query_params)) {
3206
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
+		}
3208
+		if (array_key_exists('group_by', $query_params)) {
3209
+			if (is_array($query_params['group_by'])) {
3210
+				$this->_extract_related_models_from_sub_params_array_values(
3211
+					$query_params['group_by'],
3212
+					$query_info_carrier,
3213
+					'group_by'
3214
+				);
3215
+			} elseif (! empty ($query_params['group_by'])) {
3216
+				$this->_extract_related_model_info_from_query_param(
3217
+					$query_params['group_by'],
3218
+					$query_info_carrier,
3219
+					'group_by'
3220
+				);
3221
+			}
3222
+		}
3223
+		if (array_key_exists('having', $query_params)) {
3224
+			$this->_extract_related_models_from_sub_params_array_keys(
3225
+				$query_params[0],
3226
+				$query_info_carrier,
3227
+				'having'
3228
+			);
3229
+		}
3230
+		if (array_key_exists('order_by', $query_params)) {
3231
+			if (is_array($query_params['order_by'])) {
3232
+				$this->_extract_related_models_from_sub_params_array_keys(
3233
+					$query_params['order_by'],
3234
+					$query_info_carrier,
3235
+					'order_by'
3236
+				);
3237
+			} elseif (! empty($query_params['order_by'])) {
3238
+				$this->_extract_related_model_info_from_query_param(
3239
+					$query_params['order_by'],
3240
+					$query_info_carrier,
3241
+					'order_by'
3242
+				);
3243
+			}
3244
+		}
3245
+		if (array_key_exists('force_join', $query_params)) {
3246
+			$this->_extract_related_models_from_sub_params_array_values(
3247
+				$query_params['force_join'],
3248
+				$query_info_carrier,
3249
+				'force_join'
3250
+			);
3251
+		}
3252
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
+		return $query_info_carrier;
3254
+	}
3255
+
3256
+
3257
+
3258
+	/**
3259
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
+	 *
3261
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3262
+	 *                                                      $query_params['having']
3263
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3264
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3265
+	 * @throws EE_Error
3266
+	 * @return \EE_Model_Query_Info_Carrier
3267
+	 */
3268
+	private function _extract_related_models_from_sub_params_array_keys(
3269
+		$sub_query_params,
3270
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3271
+		$query_param_type
3272
+	) {
3273
+		if (! empty($sub_query_params)) {
3274
+			$sub_query_params = (array)$sub_query_params;
3275
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3276
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3277
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3278
+					$query_param_type);
3279
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
+				//of array('Registration.TXN_ID'=>23)
3283
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
+					if (! is_array($possibly_array_of_params)) {
3286
+						throw new EE_Error(sprintf(__("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'))",
3287
+							"event_espresso"),
3288
+							$param, $possibly_array_of_params));
3289
+					}
3290
+					$this->_extract_related_models_from_sub_params_array_keys(
3291
+						$possibly_array_of_params,
3292
+						$model_query_info_carrier, $query_param_type
3293
+					);
3294
+				} elseif ($query_param_type === 0 //ie WHERE
3295
+						  && is_array($possibly_array_of_params)
3296
+						  && isset($possibly_array_of_params[2])
3297
+						  && $possibly_array_of_params[2] == true
3298
+				) {
3299
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3300
+					//indicating that $possible_array_of_params[1] is actually a field name,
3301
+					//from which we should extract query parameters!
3302
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3303
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3304
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3305
+					}
3306
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3307
+						$model_query_info_carrier, $query_param_type);
3308
+				}
3309
+			}
3310
+		}
3311
+		return $model_query_info_carrier;
3312
+	}
3313
+
3314
+
3315
+
3316
+	/**
3317
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3318
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3319
+	 *
3320
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3321
+	 *                                                      $query_params['having']
3322
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3323
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3324
+	 * @throws EE_Error
3325
+	 * @return \EE_Model_Query_Info_Carrier
3326
+	 */
3327
+	private function _extract_related_models_from_sub_params_array_values(
3328
+		$sub_query_params,
3329
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330
+		$query_param_type
3331
+	) {
3332
+		if (! empty($sub_query_params)) {
3333
+			if (! is_array($sub_query_params)) {
3334
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3335
+					$sub_query_params));
3336
+			}
3337
+			foreach ($sub_query_params as $param) {
3338
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3339
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3340
+					$query_param_type);
3341
+			}
3342
+		}
3343
+		return $model_query_info_carrier;
3344
+	}
3345
+
3346
+
3347
+
3348
+	/**
3349
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3350
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3351
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3352
+	 * but use them in a different order. Eg, we need to know what models we are querying
3353
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3354
+	 * other models before we can finalize the where clause SQL.
3355
+	 *
3356
+	 * @param array $query_params
3357
+	 * @throws EE_Error
3358
+	 * @return EE_Model_Query_Info_Carrier
3359
+	 */
3360
+	public function _create_model_query_info_carrier($query_params)
3361
+	{
3362
+		if (! is_array($query_params)) {
3363
+			EE_Error::doing_it_wrong(
3364
+				'EEM_Base::_create_model_query_info_carrier',
3365
+				sprintf(
3366
+					__(
3367
+						'$query_params should be an array, you passed a variable of type %s',
3368
+						'event_espresso'
3369
+					),
3370
+					gettype($query_params)
3371
+				),
3372
+				'4.6.0'
3373
+			);
3374
+			$query_params = array();
3375
+		}
3376
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3377
+		//first check if we should alter the query to account for caps or not
3378
+		//because the caps might require us to do extra joins
3379
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3380
+			$query_params[0] = $where_query_params = array_replace_recursive(
3381
+				$where_query_params,
3382
+				$this->caps_where_conditions(
3383
+					$query_params['caps']
3384
+				)
3385
+			);
3386
+		}
3387
+		$query_object = $this->_extract_related_models_from_query($query_params);
3388
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3389
+		foreach ($where_query_params as $key => $value) {
3390
+			if (is_int($key)) {
3391
+				throw new EE_Error(
3392
+					sprintf(
3393
+						__(
3394
+							"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.",
3395
+							"event_espresso"
3396
+						),
3397
+						$key,
3398
+						var_export($value, true),
3399
+						var_export($query_params, true),
3400
+						get_class($this)
3401
+					)
3402
+				);
3403
+			}
3404
+		}
3405
+		if (
3406
+			array_key_exists('default_where_conditions', $query_params)
3407
+			&& ! empty($query_params['default_where_conditions'])
3408
+		) {
3409
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3410
+		} else {
3411
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3412
+		}
3413
+		$where_query_params = array_merge(
3414
+			$this->_get_default_where_conditions_for_models_in_query(
3415
+				$query_object,
3416
+				$use_default_where_conditions,
3417
+				$where_query_params
3418
+			),
3419
+			$where_query_params
3420
+		);
3421
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3422
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3423
+		// So we need to setup a subquery and use that for the main join.
3424
+		// Note for now this only works on the primary table for the model.
3425
+		// So for instance, you could set the limit array like this:
3426
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3427
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3428
+			$query_object->set_main_model_join_sql(
3429
+				$this->_construct_limit_join_select(
3430
+					$query_params['on_join_limit'][0],
3431
+					$query_params['on_join_limit'][1]
3432
+				)
3433
+			);
3434
+		}
3435
+		//set limit
3436
+		if (array_key_exists('limit', $query_params)) {
3437
+			if (is_array($query_params['limit'])) {
3438
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3439
+					$e = sprintf(
3440
+						__(
3441
+							"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)",
3442
+							"event_espresso"
3443
+						),
3444
+						http_build_query($query_params['limit'])
3445
+					);
3446
+					throw new EE_Error($e . "|" . $e);
3447
+				}
3448
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3449
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3450
+			} elseif (! empty ($query_params['limit'])) {
3451
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3452
+			}
3453
+		}
3454
+		//set order by
3455
+		if (array_key_exists('order_by', $query_params)) {
3456
+			if (is_array($query_params['order_by'])) {
3457
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3458
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3459
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3460
+				if (array_key_exists('order', $query_params)) {
3461
+					throw new EE_Error(
3462
+						sprintf(
3463
+							__(
3464
+								"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 ",
3465
+								"event_espresso"
3466
+							),
3467
+							get_class($this),
3468
+							implode(", ", array_keys($query_params['order_by'])),
3469
+							implode(", ", $query_params['order_by']),
3470
+							$query_params['order']
3471
+						)
3472
+					);
3473
+				}
3474
+				$this->_extract_related_models_from_sub_params_array_keys(
3475
+					$query_params['order_by'],
3476
+					$query_object,
3477
+					'order_by'
3478
+				);
3479
+				//assume it's an array of fields to order by
3480
+				$order_array = array();
3481
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3482
+					$order = $this->_extract_order($order);
3483
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3484
+				}
3485
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3486
+			} elseif (! empty ($query_params['order_by'])) {
3487
+				$this->_extract_related_model_info_from_query_param(
3488
+					$query_params['order_by'],
3489
+					$query_object,
3490
+					'order',
3491
+					$query_params['order_by']
3492
+				);
3493
+				$order = isset($query_params['order'])
3494
+					? $this->_extract_order($query_params['order'])
3495
+					: 'DESC';
3496
+				$query_object->set_order_by_sql(
3497
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3498
+				);
3499
+			}
3500
+		}
3501
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3502
+		if (! array_key_exists('order_by', $query_params)
3503
+			&& array_key_exists('order', $query_params)
3504
+			&& ! empty($query_params['order'])
3505
+		) {
3506
+			$pk_field = $this->get_primary_key_field();
3507
+			$order = $this->_extract_order($query_params['order']);
3508
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3509
+		}
3510
+		//set group by
3511
+		if (array_key_exists('group_by', $query_params)) {
3512
+			if (is_array($query_params['group_by'])) {
3513
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3514
+				$group_by_array = array();
3515
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3516
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3517
+				}
3518
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3519
+			} elseif (! empty ($query_params['group_by'])) {
3520
+				$query_object->set_group_by_sql(
3521
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3522
+				);
3523
+			}
3524
+		}
3525
+		//set having
3526
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3527
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3528
+		}
3529
+		//now, just verify they didn't pass anything wack
3530
+		foreach ($query_params as $query_key => $query_value) {
3531
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3532
+				throw new EE_Error(
3533
+					sprintf(
3534
+						__(
3535
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3536
+							'event_espresso'
3537
+						),
3538
+						$query_key,
3539
+						get_class($this),
3540
+						//						print_r( $this->_allowed_query_params, TRUE )
3541
+						implode(',', $this->_allowed_query_params)
3542
+					)
3543
+				);
3544
+			}
3545
+		}
3546
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3547
+		if (empty($main_model_join_sql)) {
3548
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3549
+		}
3550
+		return $query_object;
3551
+	}
3552
+
3553
+
3554
+
3555
+	/**
3556
+	 * Gets the where conditions that should be imposed on the query based on the
3557
+	 * context (eg reading frontend, backend, edit or delete).
3558
+	 *
3559
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3560
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3561
+	 * @throws EE_Error
3562
+	 */
3563
+	public function caps_where_conditions($context = self::caps_read)
3564
+	{
3565
+		EEM_Base::verify_is_valid_cap_context($context);
3566
+		$cap_where_conditions = array();
3567
+		$cap_restrictions = $this->caps_missing($context);
3568
+		/**
3569
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3570
+		 */
3571
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3572
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3573
+				$restriction_if_no_cap->get_default_where_conditions());
3574
+		}
3575
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3576
+			$cap_restrictions);
3577
+	}
3578
+
3579
+
3580
+
3581
+	/**
3582
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3583
+	 * otherwise throws an exception
3584
+	 *
3585
+	 * @param string $should_be_order_string
3586
+	 * @return string either ASC, asc, DESC or desc
3587
+	 * @throws EE_Error
3588
+	 */
3589
+	private function _extract_order($should_be_order_string)
3590
+	{
3591
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3592
+			return $should_be_order_string;
3593
+		}
3594
+		throw new EE_Error(
3595
+			sprintf(
3596
+				__(
3597
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3598
+					"event_espresso"
3599
+				), get_class($this), $should_be_order_string
3600
+			)
3601
+		);
3602
+	}
3603
+
3604
+
3605
+
3606
+	/**
3607
+	 * Looks at all the models which are included in this query, and asks each
3608
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3609
+	 * so they can be merged
3610
+	 *
3611
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3612
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3613
+	 *                                                                  'none' means NO default where conditions will
3614
+	 *                                                                  be used AT ALL during this query.
3615
+	 *                                                                  'other_models_only' means default where
3616
+	 *                                                                  conditions from other models will be used, but
3617
+	 *                                                                  not for this primary model. 'all', the default,
3618
+	 *                                                                  means default where conditions will apply as
3619
+	 *                                                                  normal
3620
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3621
+	 * @throws EE_Error
3622
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3623
+	 */
3624
+	private function _get_default_where_conditions_for_models_in_query(
3625
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3626
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3627
+		$where_query_params = array()
3628
+	) {
3629
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3630
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3631
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3632
+				"event_espresso"), $use_default_where_conditions,
3633
+				implode(", ", $allowed_used_default_where_conditions_values)));
3634
+		}
3635
+		$universal_query_params = array();
3636
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3637
+			$universal_query_params = $this->_get_default_where_conditions();
3638
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3639
+			$universal_query_params = $this->_get_minimum_where_conditions();
3640
+		}
3641
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3642
+			$related_model = $this->get_related_model_obj($model_name);
3643
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3644
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3645
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3646
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3647
+			} else {
3648
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3649
+				continue;
3650
+			}
3651
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3652
+				$related_model_universal_where_params,
3653
+				$where_query_params,
3654
+				$related_model,
3655
+				$model_relation_path
3656
+			);
3657
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3658
+				$universal_query_params,
3659
+				$overrides
3660
+			);
3661
+		}
3662
+		return $universal_query_params;
3663
+	}
3664
+
3665
+
3666
+
3667
+	/**
3668
+	 * Determines whether or not we should use default where conditions for the model in question
3669
+	 * (this model, or other related models).
3670
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3671
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3672
+	 * We should use default where conditions on related models when they requested to use default where conditions
3673
+	 * on all models, or specifically just on other related models
3674
+	 * @param      $default_where_conditions_value
3675
+	 * @param bool $for_this_model false means this is for OTHER related models
3676
+	 * @return bool
3677
+	 */
3678
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3679
+	{
3680
+		return (
3681
+				   $for_this_model
3682
+				   && in_array(
3683
+					   $default_where_conditions_value,
3684
+					   array(
3685
+						   EEM_Base::default_where_conditions_all,
3686
+						   EEM_Base::default_where_conditions_this_only,
3687
+						   EEM_Base::default_where_conditions_minimum_others,
3688
+					   ),
3689
+					   true
3690
+				   )
3691
+			   )
3692
+			   || (
3693
+				   ! $for_this_model
3694
+				   && in_array(
3695
+					   $default_where_conditions_value,
3696
+					   array(
3697
+						   EEM_Base::default_where_conditions_all,
3698
+						   EEM_Base::default_where_conditions_others_only,
3699
+					   ),
3700
+					   true
3701
+				   )
3702
+			   );
3703
+	}
3704
+
3705
+	/**
3706
+	 * Determines whether or not we should use default minimum conditions for the model in question
3707
+	 * (this model, or other related models).
3708
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3709
+	 * where conditions.
3710
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3711
+	 * on this model or others
3712
+	 * @param      $default_where_conditions_value
3713
+	 * @param bool $for_this_model false means this is for OTHER related models
3714
+	 * @return bool
3715
+	 */
3716
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3717
+	{
3718
+		return (
3719
+				   $for_this_model
3720
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3721
+			   )
3722
+			   || (
3723
+				   ! $for_this_model
3724
+				   && in_array(
3725
+					   $default_where_conditions_value,
3726
+					   array(
3727
+						   EEM_Base::default_where_conditions_minimum_others,
3728
+						   EEM_Base::default_where_conditions_minimum_all,
3729
+					   ),
3730
+					   true
3731
+				   )
3732
+			   );
3733
+	}
3734
+
3735
+
3736
+	/**
3737
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3738
+	 * then we also add a special where condition which allows for that model's primary key
3739
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3740
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3741
+	 *
3742
+	 * @param array    $default_where_conditions
3743
+	 * @param array    $provided_where_conditions
3744
+	 * @param EEM_Base $model
3745
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3746
+	 * @return array like EEM_Base::get_all's $query_params[0]
3747
+	 * @throws EE_Error
3748
+	 */
3749
+	private function _override_defaults_or_make_null_friendly(
3750
+		$default_where_conditions,
3751
+		$provided_where_conditions,
3752
+		$model,
3753
+		$model_relation_path
3754
+	) {
3755
+		$null_friendly_where_conditions = array();
3756
+		$none_overridden = true;
3757
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3758
+		foreach ($default_where_conditions as $key => $val) {
3759
+			if (isset($provided_where_conditions[$key])) {
3760
+				$none_overridden = false;
3761
+			} else {
3762
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3763
+			}
3764
+		}
3765
+		if ($none_overridden && $default_where_conditions) {
3766
+			if ($model->has_primary_key_field()) {
3767
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3768
+																				. "."
3769
+																				. $model->primary_key_name()] = array('IS NULL');
3770
+			}/*else{
3771 3771
 				//@todo NO PK, use other defaults
3772 3772
 			}*/
3773
-        }
3774
-        return $null_friendly_where_conditions;
3775
-    }
3776
-
3777
-
3778
-
3779
-    /**
3780
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3781
-     * default where conditions on all get_all, update, and delete queries done by this model.
3782
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3783
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3784
-     *
3785
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3786
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3787
-     */
3788
-    private function _get_default_where_conditions($model_relation_path = null)
3789
-    {
3790
-        if ($this->_ignore_where_strategy) {
3791
-            return array();
3792
-        }
3793
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3794
-    }
3795
-
3796
-
3797
-
3798
-    /**
3799
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3800
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3801
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3802
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3803
-     * Similar to _get_default_where_conditions
3804
-     *
3805
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3806
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3807
-     */
3808
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3809
-    {
3810
-        if ($this->_ignore_where_strategy) {
3811
-            return array();
3812
-        }
3813
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3814
-    }
3815
-
3816
-
3817
-
3818
-    /**
3819
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3820
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3821
-     *
3822
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3823
-     * @return string
3824
-     * @throws EE_Error
3825
-     */
3826
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3827
-    {
3828
-        $selects = $this->_get_columns_to_select_for_this_model();
3829
-        foreach (
3830
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3831
-            $name_of_other_model_included
3832
-        ) {
3833
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3834
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3835
-            foreach ($other_model_selects as $key => $value) {
3836
-                $selects[] = $value;
3837
-            }
3838
-        }
3839
-        return implode(", ", $selects);
3840
-    }
3841
-
3842
-
3843
-
3844
-    /**
3845
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3846
-     * So that's going to be the columns for all the fields on the model
3847
-     *
3848
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3849
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3850
-     */
3851
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3852
-    {
3853
-        $fields = $this->field_settings();
3854
-        $selects = array();
3855
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3856
-            $this->get_this_model_name());
3857
-        foreach ($fields as $field_obj) {
3858
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3859
-                         . $field_obj->get_table_alias()
3860
-                         . "."
3861
-                         . $field_obj->get_table_column()
3862
-                         . " AS '"
3863
-                         . $table_alias_with_model_relation_chain_prefix
3864
-                         . $field_obj->get_table_alias()
3865
-                         . "."
3866
-                         . $field_obj->get_table_column()
3867
-                         . "'";
3868
-        }
3869
-        //make sure we are also getting the PKs of each table
3870
-        $tables = $this->get_tables();
3871
-        if (count($tables) > 1) {
3872
-            foreach ($tables as $table_obj) {
3873
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3874
-                                       . $table_obj->get_fully_qualified_pk_column();
3875
-                if (! in_array($qualified_pk_column, $selects)) {
3876
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3877
-                }
3878
-            }
3879
-        }
3880
-        return $selects;
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3887
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3888
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3889
-     * SQL for joining, and the data types
3890
-     *
3891
-     * @param null|string                 $original_query_param
3892
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3893
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3894
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3895
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3896
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3897
-     *                                                          or 'Registration's
3898
-     * @param string                      $original_query_param what it originally was (eg
3899
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3900
-     *                                                          matches $query_param
3901
-     * @throws EE_Error
3902
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3903
-     */
3904
-    private function _extract_related_model_info_from_query_param(
3905
-        $query_param,
3906
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3907
-        $query_param_type,
3908
-        $original_query_param = null
3909
-    ) {
3910
-        if ($original_query_param === null) {
3911
-            $original_query_param = $query_param;
3912
-        }
3913
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3914
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3915
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3916
-        $allow_fields = in_array(
3917
-            $query_param_type,
3918
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3919
-            true
3920
-        );
3921
-        //check to see if we have a field on this model
3922
-        $this_model_fields = $this->field_settings(true);
3923
-        if (array_key_exists($query_param, $this_model_fields)) {
3924
-            if ($allow_fields) {
3925
-                return;
3926
-            }
3927
-            throw new EE_Error(
3928
-                sprintf(
3929
-                    __(
3930
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3931
-                        "event_espresso"
3932
-                    ),
3933
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3934
-                )
3935
-            );
3936
-        }
3937
-        //check if this is a special logic query param
3938
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3939
-            if ($allow_logic_query_params) {
3940
-                return;
3941
-            }
3942
-            throw new EE_Error(
3943
-                sprintf(
3944
-                    __(
3945
-                        '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',
3946
-                        'event_espresso'
3947
-                    ),
3948
-                    implode('", "', $this->_logic_query_param_keys),
3949
-                    $query_param,
3950
-                    get_class($this),
3951
-                    '<br />',
3952
-                    "\t"
3953
-                    . ' $passed_in_query_info = <pre>'
3954
-                    . print_r($passed_in_query_info, true)
3955
-                    . '</pre>'
3956
-                    . "\n\t"
3957
-                    . ' $query_param_type = '
3958
-                    . $query_param_type
3959
-                    . "\n\t"
3960
-                    . ' $original_query_param = '
3961
-                    . $original_query_param
3962
-                )
3963
-            );
3964
-        }
3965
-        //check if it's a custom selection
3966
-        if ($this->_custom_selections instanceof CustomSelects
3967
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3968
-        ) {
3969
-            return;
3970
-        }
3971
-        //check if has a model name at the beginning
3972
-        //and
3973
-        //check if it's a field on a related model
3974
-        if ($this->extractJoinModelFromQueryParams(
3975
-            $passed_in_query_info,
3976
-            $query_param,
3977
-            $original_query_param,
3978
-            $query_param_type
3979
-        )) {
3980
-            return;
3981
-        }
3982
-
3983
-        //ok so $query_param didn't start with a model name
3984
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3985
-        //it's wack, that's what it is
3986
-        throw new EE_Error(
3987
-            sprintf(
3988
-                esc_html__(
3989
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3990
-                    "event_espresso"
3991
-                ),
3992
-                $query_param,
3993
-                get_class($this),
3994
-                $query_param_type,
3995
-                $original_query_param
3996
-            )
3997
-        );
3998
-    }
3999
-
4000
-
4001
-    /**
4002
-     * Extracts any possible join model information from the provided possible_join_string.
4003
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4004
-     * parts that should be added to the query.
4005
-     *
4006
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4007
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4008
-     * @param null|string                 $original_query_param
4009
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4010
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4011
-     * @return bool  returns true if a join was added and false if not.
4012
-     * @throws EE_Error
4013
-     */
4014
-    private function extractJoinModelFromQueryParams(
4015
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4016
-        $possible_join_string,
4017
-        $original_query_param,
4018
-        $query_parameter_type
4019
-    ) {
4020
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4021
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4022
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4023
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4024
-                if ($possible_join_string === '') {
4025
-                    //nothing left to $query_param
4026
-                    //we should actually end in a field name, not a model like this!
4027
-                    throw new EE_Error(
4028
-                        sprintf(
4029
-                            esc_html__(
4030
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4031
-                                "event_espresso"
4032
-                            ),
4033
-                            $possible_join_string,
4034
-                            $query_parameter_type,
4035
-                            get_class($this),
4036
-                            $valid_related_model_name
4037
-                        )
4038
-                    );
4039
-                }
4040
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4041
-                $related_model_obj->_extract_related_model_info_from_query_param(
4042
-                    $possible_join_string,
4043
-                    $query_info_carrier,
4044
-                    $query_parameter_type,
4045
-                    $original_query_param
4046
-                );
4047
-                return true;
4048
-            }
4049
-            if ($possible_join_string === $valid_related_model_name) {
4050
-                $this->_add_join_to_model(
4051
-                    $valid_related_model_name,
4052
-                    $query_info_carrier,
4053
-                    $original_query_param
4054
-                );
4055
-                return true;
4056
-            }
4057
-        }
4058
-        return false;
4059
-    }
4060
-
4061
-
4062
-    /**
4063
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4064
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4065
-     * @throws EE_Error
4066
-     */
4067
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4068
-    {
4069
-        if ($this->_custom_selections instanceof CustomSelects
4070
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4071
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4072
-            )
4073
-        ) {
4074
-            $original_selects = $this->_custom_selections->originalSelects();
4075
-            foreach ($original_selects as $alias => $select_configuration) {
4076
-                $this->extractJoinModelFromQueryParams(
4077
-                    $query_info_carrier,
4078
-                    $select_configuration[0],
4079
-                    $select_configuration[0],
4080
-                    'custom_selects'
4081
-                );
4082
-            }
4083
-        }
4084
-    }
4085
-
4086
-
4087
-
4088
-    /**
4089
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4090
-     * and store it on $passed_in_query_info
4091
-     *
4092
-     * @param string                      $model_name
4093
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4094
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4095
-     *                                                          model and $model_name. Eg, if we are querying Event,
4096
-     *                                                          and are adding a join to 'Payment' with the original
4097
-     *                                                          query param key
4098
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4099
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4100
-     *                                                          Payment wants to add default query params so that it
4101
-     *                                                          will know what models to prepend onto its default query
4102
-     *                                                          params or in case it wants to rename tables (in case
4103
-     *                                                          there are multiple joins to the same table)
4104
-     * @return void
4105
-     * @throws EE_Error
4106
-     */
4107
-    private function _add_join_to_model(
4108
-        $model_name,
4109
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4110
-        $original_query_param
4111
-    ) {
4112
-        $relation_obj = $this->related_settings_for($model_name);
4113
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4114
-        //check if the relation is HABTM, because then we're essentially doing two joins
4115
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
4116
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4117
-            $join_model_obj = $relation_obj->get_join_model();
4118
-            //replace the model specified with the join model for this relation chain, whi
4119
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4120
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4121
-            $passed_in_query_info->merge(
4122
-                new EE_Model_Query_Info_Carrier(
4123
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4124
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4125
-                )
4126
-            );
4127
-        }
4128
-        //now just join to the other table pointed to by the relation object, and add its data types
4129
-        $passed_in_query_info->merge(
4130
-            new EE_Model_Query_Info_Carrier(
4131
-                array($model_relation_chain => $model_name),
4132
-                $relation_obj->get_join_statement($model_relation_chain)
4133
-            )
4134
-        );
4135
-    }
4136
-
4137
-
4138
-
4139
-    /**
4140
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4141
-     *
4142
-     * @param array $where_params like EEM_Base::get_all
4143
-     * @return string of SQL
4144
-     * @throws EE_Error
4145
-     */
4146
-    private function _construct_where_clause($where_params)
4147
-    {
4148
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4149
-        if ($SQL) {
4150
-            return " WHERE " . $SQL;
4151
-        }
4152
-        return '';
4153
-    }
4154
-
4155
-
4156
-
4157
-    /**
4158
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4159
-     * and should be passed HAVING parameters, not WHERE parameters
4160
-     *
4161
-     * @param array $having_params
4162
-     * @return string
4163
-     * @throws EE_Error
4164
-     */
4165
-    private function _construct_having_clause($having_params)
4166
-    {
4167
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4168
-        if ($SQL) {
4169
-            return " HAVING " . $SQL;
4170
-        }
4171
-        return '';
4172
-    }
4173
-
4174
-
4175
-    /**
4176
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4177
-     * Event_Meta.meta_value = 'foo'))"
4178
-     *
4179
-     * @param array  $where_params see EEM_Base::get_all for documentation
4180
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4181
-     * @throws EE_Error
4182
-     * @return string of SQL
4183
-     */
4184
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4185
-    {
4186
-        $where_clauses = array();
4187
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4188
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4189
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4190
-                switch ($query_param) {
4191
-                    case 'not':
4192
-                    case 'NOT':
4193
-                        $where_clauses[] = "! ("
4194
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4195
-                                $glue)
4196
-                                           . ")";
4197
-                        break;
4198
-                    case 'and':
4199
-                    case 'AND':
4200
-                        $where_clauses[] = " ("
4201
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4202
-                                ' AND ')
4203
-                                           . ")";
4204
-                        break;
4205
-                    case 'or':
4206
-                    case 'OR':
4207
-                        $where_clauses[] = " ("
4208
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4209
-                                ' OR ')
4210
-                                           . ")";
4211
-                        break;
4212
-                }
4213
-            } else {
4214
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4215
-                //if it's not a normal field, maybe it's a custom selection?
4216
-                if (! $field_obj) {
4217
-                    if ($this->_custom_selections instanceof CustomSelects) {
4218
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4219
-                    } else {
4220
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4221
-                            "event_espresso"), $query_param));
4222
-                    }
4223
-                }
4224
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4225
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4226
-            }
4227
-        }
4228
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4229
-    }
4230
-
4231
-
4232
-
4233
-    /**
4234
-     * Takes the input parameter and extract the table name (alias) and column name
4235
-     *
4236
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4237
-     * @throws EE_Error
4238
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4239
-     */
4240
-    private function _deduce_column_name_from_query_param($query_param)
4241
-    {
4242
-        $field = $this->_deduce_field_from_query_param($query_param);
4243
-        if ($field) {
4244
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4245
-                $query_param);
4246
-            return $table_alias_prefix . $field->get_qualified_column();
4247
-        }
4248
-        if ($this->_custom_selections instanceof CustomSelects
4249
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4250
-        ) {
4251
-            //maybe it's custom selection item?
4252
-            //if so, just use it as the "column name"
4253
-            return $query_param;
4254
-        }
4255
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4256
-            ? implode(',', $this->_custom_selections->columnAliases())
4257
-            : '';
4258
-        throw new EE_Error(
4259
-            sprintf(
4260
-                __(
4261
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4262
-                    "event_espresso"
4263
-                ), $query_param, $custom_select_aliases
4264
-            )
4265
-        );
4266
-    }
4267
-
4268
-
4269
-
4270
-    /**
4271
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4272
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4273
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4274
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4275
-     *
4276
-     * @param string $condition_query_param_key
4277
-     * @return string
4278
-     */
4279
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4280
-    {
4281
-        $pos_of_star = strpos($condition_query_param_key, '*');
4282
-        if ($pos_of_star === false) {
4283
-            return $condition_query_param_key;
4284
-        }
4285
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4286
-        return $condition_query_param_sans_star;
4287
-    }
4288
-
4289
-
4290
-
4291
-    /**
4292
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4293
-     *
4294
-     * @param                            mixed      array | string    $op_and_value
4295
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4296
-     * @throws EE_Error
4297
-     * @return string
4298
-     */
4299
-    private function _construct_op_and_value($op_and_value, $field_obj)
4300
-    {
4301
-        if (is_array($op_and_value)) {
4302
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4303
-            if (! $operator) {
4304
-                $php_array_like_string = array();
4305
-                foreach ($op_and_value as $key => $value) {
4306
-                    $php_array_like_string[] = "$key=>$value";
4307
-                }
4308
-                throw new EE_Error(
4309
-                    sprintf(
4310
-                        __(
4311
-                            "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))",
4312
-                            "event_espresso"
4313
-                        ),
4314
-                        implode(",", $php_array_like_string)
4315
-                    )
4316
-                );
4317
-            }
4318
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4319
-        } else {
4320
-            $operator = '=';
4321
-            $value = $op_and_value;
4322
-        }
4323
-        //check to see if the value is actually another field
4324
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4325
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4326
-        }
4327
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4328
-            //in this case, the value should be an array, or at least a comma-separated list
4329
-            //it will need to handle a little differently
4330
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4331
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4332
-            return $operator . SP . $cleaned_value;
4333
-        }
4334
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4335
-            //the value should be an array with count of two.
4336
-            if (count($value) !== 2) {
4337
-                throw new EE_Error(
4338
-                    sprintf(
4339
-                        __(
4340
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4341
-                            'event_espresso'
4342
-                        ),
4343
-                        "BETWEEN"
4344
-                    )
4345
-                );
4346
-            }
4347
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4348
-            return $operator . SP . $cleaned_value;
4349
-        }
4350
-        if (in_array($operator, $this->valid_null_style_operators())) {
4351
-            if ($value !== null) {
4352
-                throw new EE_Error(
4353
-                    sprintf(
4354
-                        __(
4355
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4356
-                            "event_espresso"
4357
-                        ),
4358
-                        $value,
4359
-                        $operator
4360
-                    )
4361
-                );
4362
-            }
4363
-            return $operator;
4364
-        }
4365
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4366
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4367
-            //remove other junk. So just treat it as a string.
4368
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4369
-        }
4370
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4371
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4372
-        }
4373
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4374
-            throw new EE_Error(
4375
-                sprintf(
4376
-                    __(
4377
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4378
-                        'event_espresso'
4379
-                    ),
4380
-                    $operator,
4381
-                    $operator
4382
-                )
4383
-            );
4384
-        }
4385
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4386
-            throw new EE_Error(
4387
-                sprintf(
4388
-                    __(
4389
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4390
-                        'event_espresso'
4391
-                    ),
4392
-                    $operator,
4393
-                    $operator
4394
-                )
4395
-            );
4396
-        }
4397
-        throw new EE_Error(
4398
-            sprintf(
4399
-                __(
4400
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4401
-                    "event_espresso"
4402
-                ),
4403
-                http_build_query($op_and_value)
4404
-            )
4405
-        );
4406
-    }
4407
-
4408
-
4409
-
4410
-    /**
4411
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4412
-     *
4413
-     * @param array                      $values
4414
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4415
-     *                                              '%s'
4416
-     * @return string
4417
-     * @throws EE_Error
4418
-     */
4419
-    public function _construct_between_value($values, $field_obj)
4420
-    {
4421
-        $cleaned_values = array();
4422
-        foreach ($values as $value) {
4423
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4424
-        }
4425
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4426
-    }
4427
-
4428
-
4429
-
4430
-    /**
4431
-     * Takes an array or a comma-separated list of $values and cleans them
4432
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4433
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4434
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4435
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4436
-     *
4437
-     * @param mixed                      $values    array or comma-separated string
4438
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4439
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4440
-     * @throws EE_Error
4441
-     */
4442
-    public function _construct_in_value($values, $field_obj)
4443
-    {
4444
-        //check if the value is a CSV list
4445
-        if (is_string($values)) {
4446
-            //in which case, turn it into an array
4447
-            $values = explode(",", $values);
4448
-        }
4449
-        $cleaned_values = array();
4450
-        foreach ($values as $value) {
4451
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4452
-        }
4453
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4454
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4455
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4456
-        if (empty($cleaned_values)) {
4457
-            $all_fields = $this->field_settings();
4458
-            $a_field = array_shift($all_fields);
4459
-            $main_table = $this->_get_main_table();
4460
-            $cleaned_values[] = "SELECT "
4461
-                                . $a_field->get_table_column()
4462
-                                . " FROM "
4463
-                                . $main_table->get_table_name()
4464
-                                . " WHERE FALSE";
4465
-        }
4466
-        return "(" . implode(",", $cleaned_values) . ")";
4467
-    }
4468
-
4469
-
4470
-
4471
-    /**
4472
-     * @param mixed                      $value
4473
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4474
-     * @throws EE_Error
4475
-     * @return false|null|string
4476
-     */
4477
-    private function _wpdb_prepare_using_field($value, $field_obj)
4478
-    {
4479
-        /** @type WPDB $wpdb */
4480
-        global $wpdb;
4481
-        if ($field_obj instanceof EE_Model_Field_Base) {
4482
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4483
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4484
-        } //$field_obj should really just be a data type
4485
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4486
-            throw new EE_Error(
4487
-                sprintf(
4488
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4489
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4490
-                )
4491
-            );
4492
-        }
4493
-        return $wpdb->prepare($field_obj, $value);
4494
-    }
4495
-
4496
-
4497
-
4498
-    /**
4499
-     * Takes the input parameter and finds the model field that it indicates.
4500
-     *
4501
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4502
-     * @throws EE_Error
4503
-     * @return EE_Model_Field_Base
4504
-     */
4505
-    protected function _deduce_field_from_query_param($query_param_name)
4506
-    {
4507
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4508
-        //which will help us find the database table and column
4509
-        $query_param_parts = explode(".", $query_param_name);
4510
-        if (empty($query_param_parts)) {
4511
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4512
-                'event_espresso'), $query_param_name));
4513
-        }
4514
-        $number_of_parts = count($query_param_parts);
4515
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4516
-        if ($number_of_parts === 1) {
4517
-            $field_name = $last_query_param_part;
4518
-            $model_obj = $this;
4519
-        } else {// $number_of_parts >= 2
4520
-            //the last part is the column name, and there are only 2parts. therefore...
4521
-            $field_name = $last_query_param_part;
4522
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4523
-        }
4524
-        try {
4525
-            return $model_obj->field_settings_for($field_name);
4526
-        } catch (EE_Error $e) {
4527
-            return null;
4528
-        }
4529
-    }
4530
-
4531
-
4532
-
4533
-    /**
4534
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4535
-     * alias and column which corresponds to it
4536
-     *
4537
-     * @param string $field_name
4538
-     * @throws EE_Error
4539
-     * @return string
4540
-     */
4541
-    public function _get_qualified_column_for_field($field_name)
4542
-    {
4543
-        $all_fields = $this->field_settings();
4544
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4545
-        if ($field) {
4546
-            return $field->get_qualified_column();
4547
-        }
4548
-        throw new EE_Error(
4549
-            sprintf(
4550
-                __(
4551
-                    "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.",
4552
-                    'event_espresso'
4553
-                ), $field_name, get_class($this)
4554
-            )
4555
-        );
4556
-    }
4557
-
4558
-
4559
-
4560
-    /**
4561
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4562
-     * Example usage:
4563
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4564
-     *      array(),
4565
-     *      ARRAY_A,
4566
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4567
-     *  );
4568
-     * is equivalent to
4569
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4570
-     * and
4571
-     *  EEM_Event::instance()->get_all_wpdb_results(
4572
-     *      array(
4573
-     *          array(
4574
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4575
-     *          ),
4576
-     *          ARRAY_A,
4577
-     *          implode(
4578
-     *              ', ',
4579
-     *              array_merge(
4580
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4581
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4582
-     *              )
4583
-     *          )
4584
-     *      )
4585
-     *  );
4586
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4587
-     *
4588
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4589
-     *                                            and the one whose fields you are selecting for example: when querying
4590
-     *                                            tickets model and selecting fields from the tickets model you would
4591
-     *                                            leave this parameter empty, because no models are needed to join
4592
-     *                                            between the queried model and the selected one. Likewise when
4593
-     *                                            querying the datetime model and selecting fields from the tickets
4594
-     *                                            model, it would also be left empty, because there is a direct
4595
-     *                                            relation from datetimes to tickets, so no model is needed to join
4596
-     *                                            them together. However, when querying from the event model and
4597
-     *                                            selecting fields from the ticket model, you should provide the string
4598
-     *                                            'Datetime', indicating that the event model must first join to the
4599
-     *                                            datetime model in order to find its relation to ticket model.
4600
-     *                                            Also, when querying from the venue model and selecting fields from
4601
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4602
-     *                                            indicating you need to join the venue model to the event model,
4603
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4604
-     *                                            This string is used to deduce the prefix that gets added onto the
4605
-     *                                            models' tables qualified columns
4606
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4607
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4608
-     *                                            qualified column names
4609
-     * @return array|string
4610
-     */
4611
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4612
-    {
4613
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4614
-        $qualified_columns = array();
4615
-        foreach ($this->field_settings() as $field_name => $field) {
4616
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4617
-        }
4618
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4619
-    }
4620
-
4621
-
4622
-
4623
-    /**
4624
-     * constructs the select use on special limit joins
4625
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4626
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4627
-     * (as that is typically where the limits would be set).
4628
-     *
4629
-     * @param  string       $table_alias The table the select is being built for
4630
-     * @param  mixed|string $limit       The limit for this select
4631
-     * @return string                The final select join element for the query.
4632
-     */
4633
-    public function _construct_limit_join_select($table_alias, $limit)
4634
-    {
4635
-        $SQL = '';
4636
-        foreach ($this->_tables as $table_obj) {
4637
-            if ($table_obj instanceof EE_Primary_Table) {
4638
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4639
-                    ? $table_obj->get_select_join_limit($limit)
4640
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4641
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4642
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4643
-                    ? $table_obj->get_select_join_limit_join($limit)
4644
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4645
-            }
4646
-        }
4647
-        return $SQL;
4648
-    }
4649
-
4650
-
4651
-
4652
-    /**
4653
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4654
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4655
-     *
4656
-     * @return string SQL
4657
-     * @throws EE_Error
4658
-     */
4659
-    public function _construct_internal_join()
4660
-    {
4661
-        $SQL = $this->_get_main_table()->get_table_sql();
4662
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4663
-        return $SQL;
4664
-    }
4665
-
4666
-
4667
-
4668
-    /**
4669
-     * Constructs the SQL for joining all the tables on this model.
4670
-     * Normally $alias should be the primary table's alias, but in cases where
4671
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4672
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4673
-     * alias, this will construct SQL like:
4674
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4675
-     * With $alias being a secondary table's alias, this will construct SQL like:
4676
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4677
-     *
4678
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4679
-     * @return string
4680
-     */
4681
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4682
-    {
4683
-        $SQL = '';
4684
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4685
-        foreach ($this->_tables as $table_obj) {
4686
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4687
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4688
-                    //so we're joining to this table, meaning the table is already in
4689
-                    //the FROM statement, BUT the primary table isn't. So we want
4690
-                    //to add the inverse join sql
4691
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4692
-                } else {
4693
-                    //just add a regular JOIN to this table from the primary table
4694
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4695
-                }
4696
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4697
-        }
4698
-        return $SQL;
4699
-    }
4700
-
4701
-
4702
-
4703
-    /**
4704
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4705
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4706
-     * their data type (eg, '%s', '%d', etc)
4707
-     *
4708
-     * @return array
4709
-     */
4710
-    public function _get_data_types()
4711
-    {
4712
-        $data_types = array();
4713
-        foreach ($this->field_settings() as $field_obj) {
4714
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4715
-            /** @var $field_obj EE_Model_Field_Base */
4716
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4717
-        }
4718
-        return $data_types;
4719
-    }
4720
-
4721
-
4722
-
4723
-    /**
4724
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4725
-     *
4726
-     * @param string $model_name
4727
-     * @throws EE_Error
4728
-     * @return EEM_Base
4729
-     */
4730
-    public function get_related_model_obj($model_name)
4731
-    {
4732
-        $model_classname = "EEM_" . $model_name;
4733
-        if (! class_exists($model_classname)) {
4734
-            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",
4735
-                'event_espresso'), $model_name, $model_classname));
4736
-        }
4737
-        return call_user_func($model_classname . "::instance");
4738
-    }
4739
-
4740
-
4741
-
4742
-    /**
4743
-     * Returns the array of EE_ModelRelations for this model.
4744
-     *
4745
-     * @return EE_Model_Relation_Base[]
4746
-     */
4747
-    public function relation_settings()
4748
-    {
4749
-        return $this->_model_relations;
4750
-    }
4751
-
4752
-
4753
-
4754
-    /**
4755
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4756
-     * because without THOSE models, this model probably doesn't have much purpose.
4757
-     * (Eg, without an event, datetimes have little purpose.)
4758
-     *
4759
-     * @return EE_Belongs_To_Relation[]
4760
-     */
4761
-    public function belongs_to_relations()
4762
-    {
4763
-        $belongs_to_relations = array();
4764
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4765
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4766
-                $belongs_to_relations[$model_name] = $relation_obj;
4767
-            }
4768
-        }
4769
-        return $belongs_to_relations;
4770
-    }
4771
-
4772
-
4773
-
4774
-    /**
4775
-     * Returns the specified EE_Model_Relation, or throws an exception
4776
-     *
4777
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4778
-     * @throws EE_Error
4779
-     * @return EE_Model_Relation_Base
4780
-     */
4781
-    public function related_settings_for($relation_name)
4782
-    {
4783
-        $relatedModels = $this->relation_settings();
4784
-        if (! array_key_exists($relation_name, $relatedModels)) {
4785
-            throw new EE_Error(
4786
-                sprintf(
4787
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4788
-                        'event_espresso'),
4789
-                    $relation_name,
4790
-                    $this->_get_class_name(),
4791
-                    implode(', ', array_keys($relatedModels))
4792
-                )
4793
-            );
4794
-        }
4795
-        return $relatedModels[$relation_name];
4796
-    }
4797
-
4798
-
4799
-
4800
-    /**
4801
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4802
-     * fields
4803
-     *
4804
-     * @param string $fieldName
4805
-     * @param boolean $include_db_only_fields
4806
-     * @throws EE_Error
4807
-     * @return EE_Model_Field_Base
4808
-     */
4809
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4810
-    {
4811
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4812
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4813
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4814
-                get_class($this)));
4815
-        }
4816
-        return $fieldSettings[$fieldName];
4817
-    }
4818
-
4819
-
4820
-
4821
-    /**
4822
-     * Checks if this field exists on this model
4823
-     *
4824
-     * @param string $fieldName a key in the model's _field_settings array
4825
-     * @return boolean
4826
-     */
4827
-    public function has_field($fieldName)
4828
-    {
4829
-        $fieldSettings = $this->field_settings(true);
4830
-        if (isset($fieldSettings[$fieldName])) {
4831
-            return true;
4832
-        }
4833
-        return false;
4834
-    }
4835
-
4836
-
4837
-
4838
-    /**
4839
-     * Returns whether or not this model has a relation to the specified model
4840
-     *
4841
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4842
-     * @return boolean
4843
-     */
4844
-    public function has_relation($relation_name)
4845
-    {
4846
-        $relations = $this->relation_settings();
4847
-        if (isset($relations[$relation_name])) {
4848
-            return true;
4849
-        }
4850
-        return false;
4851
-    }
4852
-
4853
-
4854
-
4855
-    /**
4856
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4857
-     * Eg, on EE_Answer that would be ANS_ID field object
4858
-     *
4859
-     * @param $field_obj
4860
-     * @return boolean
4861
-     */
4862
-    public function is_primary_key_field($field_obj)
4863
-    {
4864
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4865
-    }
4866
-
4867
-
4868
-
4869
-    /**
4870
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4871
-     * Eg, on EE_Answer that would be ANS_ID field object
4872
-     *
4873
-     * @return EE_Model_Field_Base
4874
-     * @throws EE_Error
4875
-     */
4876
-    public function get_primary_key_field()
4877
-    {
4878
-        if ($this->_primary_key_field === null) {
4879
-            foreach ($this->field_settings(true) as $field_obj) {
4880
-                if ($this->is_primary_key_field($field_obj)) {
4881
-                    $this->_primary_key_field = $field_obj;
4882
-                    break;
4883
-                }
4884
-            }
4885
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4886
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4887
-                    get_class($this)));
4888
-            }
4889
-        }
4890
-        return $this->_primary_key_field;
4891
-    }
4892
-
4893
-
4894
-
4895
-    /**
4896
-     * Returns whether or not not there is a primary key on this model.
4897
-     * Internally does some caching.
4898
-     *
4899
-     * @return boolean
4900
-     */
4901
-    public function has_primary_key_field()
4902
-    {
4903
-        if ($this->_has_primary_key_field === null) {
4904
-            try {
4905
-                $this->get_primary_key_field();
4906
-                $this->_has_primary_key_field = true;
4907
-            } catch (EE_Error $e) {
4908
-                $this->_has_primary_key_field = false;
4909
-            }
4910
-        }
4911
-        return $this->_has_primary_key_field;
4912
-    }
4913
-
4914
-
4915
-
4916
-    /**
4917
-     * Finds the first field of type $field_class_name.
4918
-     *
4919
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4920
-     *                                 EE_Foreign_Key_Field, etc
4921
-     * @return EE_Model_Field_Base or null if none is found
4922
-     */
4923
-    public function get_a_field_of_type($field_class_name)
4924
-    {
4925
-        foreach ($this->field_settings() as $field) {
4926
-            if ($field instanceof $field_class_name) {
4927
-                return $field;
4928
-            }
4929
-        }
4930
-        return null;
4931
-    }
4932
-
4933
-
4934
-
4935
-    /**
4936
-     * Gets a foreign key field pointing to model.
4937
-     *
4938
-     * @param string $model_name eg Event, Registration, not EEM_Event
4939
-     * @return EE_Foreign_Key_Field_Base
4940
-     * @throws EE_Error
4941
-     */
4942
-    public function get_foreign_key_to($model_name)
4943
-    {
4944
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4945
-            foreach ($this->field_settings() as $field) {
4946
-                if (
4947
-                    $field instanceof EE_Foreign_Key_Field_Base
4948
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4949
-                ) {
4950
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4951
-                    break;
4952
-                }
4953
-            }
4954
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4955
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4956
-                    'event_espresso'), $model_name, get_class($this)));
4957
-            }
4958
-        }
4959
-        return $this->_cache_foreign_key_to_fields[$model_name];
4960
-    }
4961
-
4962
-
4963
-
4964
-    /**
4965
-     * Gets the table name (including $wpdb->prefix) for the table alias
4966
-     *
4967
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4968
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4969
-     *                            Either one works
4970
-     * @return string
4971
-     */
4972
-    public function get_table_for_alias($table_alias)
4973
-    {
4974
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4975
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4976
-    }
4977
-
4978
-
4979
-
4980
-    /**
4981
-     * Returns a flat array of all field son this model, instead of organizing them
4982
-     * by table_alias as they are in the constructor.
4983
-     *
4984
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4985
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4986
-     */
4987
-    public function field_settings($include_db_only_fields = false)
4988
-    {
4989
-        if ($include_db_only_fields) {
4990
-            if ($this->_cached_fields === null) {
4991
-                $this->_cached_fields = array();
4992
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4993
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4994
-                        $this->_cached_fields[$field_name] = $field_obj;
4995
-                    }
4996
-                }
4997
-            }
4998
-            return $this->_cached_fields;
4999
-        }
5000
-        if ($this->_cached_fields_non_db_only === null) {
5001
-            $this->_cached_fields_non_db_only = array();
5002
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5003
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5004
-                    /** @var $field_obj EE_Model_Field_Base */
5005
-                    if (! $field_obj->is_db_only_field()) {
5006
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5007
-                    }
5008
-                }
5009
-            }
5010
-        }
5011
-        return $this->_cached_fields_non_db_only;
5012
-    }
5013
-
5014
-
5015
-
5016
-    /**
5017
-     *        cycle though array of attendees and create objects out of each item
5018
-     *
5019
-     * @access        private
5020
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5021
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5022
-     *                           numerically indexed)
5023
-     * @throws EE_Error
5024
-     */
5025
-    protected function _create_objects($rows = array())
5026
-    {
5027
-        $array_of_objects = array();
5028
-        if (empty($rows)) {
5029
-            return array();
5030
-        }
5031
-        $count_if_model_has_no_primary_key = 0;
5032
-        $has_primary_key = $this->has_primary_key_field();
5033
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5034
-        foreach ((array)$rows as $row) {
5035
-            if (empty($row)) {
5036
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5037
-                return array();
5038
-            }
5039
-            //check if we've already set this object in the results array,
5040
-            //in which case there's no need to process it further (again)
5041
-            if ($has_primary_key) {
5042
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5043
-                    $row,
5044
-                    $primary_key_field->get_qualified_column(),
5045
-                    $primary_key_field->get_table_column()
5046
-                );
5047
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5048
-                    continue;
5049
-                }
5050
-            }
5051
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5052
-            if (! $classInstance) {
5053
-                throw new EE_Error(
5054
-                    sprintf(
5055
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5056
-                        $this->get_this_model_name(),
5057
-                        http_build_query($row)
5058
-                    )
5059
-                );
5060
-            }
5061
-            //set the timezone on the instantiated objects
5062
-            $classInstance->set_timezone($this->_timezone);
5063
-            //make sure if there is any timezone setting present that we set the timezone for the object
5064
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5065
-            $array_of_objects[$key] = $classInstance;
5066
-            //also, for all the relations of type BelongsTo, see if we can cache
5067
-            //those related models
5068
-            //(we could do this for other relations too, but if there are conditions
5069
-            //that filtered out some fo the results, then we'd be caching an incomplete set
5070
-            //so it requires a little more thought than just caching them immediately...)
5071
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5072
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5073
-                    //check if this model's INFO is present. If so, cache it on the model
5074
-                    $other_model = $relation_obj->get_other_model();
5075
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5076
-                    //if we managed to make a model object from the results, cache it on the main model object
5077
-                    if ($other_model_obj_maybe) {
5078
-                        //set timezone on these other model objects if they are present
5079
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5080
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5081
-                    }
5082
-                }
5083
-            }
5084
-            //also, if this was a custom select query, let's see if there are any results for the custom select fields
5085
-            //and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5086
-            //the field in the CustomSelects object
5087
-            if ($this->_custom_selections instanceof CustomSelects) {
5088
-                $classInstance->setCustomSelectsValues(
5089
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5090
-                );
5091
-            }
5092
-        }
5093
-        return $array_of_objects;
5094
-    }
5095
-
5096
-
5097
-    /**
5098
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5099
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5100
-     *
5101
-     * @param array $db_results_row
5102
-     * @return array
5103
-     */
5104
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5105
-    {
5106
-        $results = array();
5107
-        if ($this->_custom_selections instanceof CustomSelects) {
5108
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5109
-                if (isset($db_results_row[$alias])) {
5110
-                    $results[$alias] = $this->convertValueToDataType(
5111
-                        $db_results_row[$alias],
5112
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5113
-                    );
5114
-                }
5115
-            }
5116
-        }
5117
-        return $results;
5118
-    }
5119
-
5120
-
5121
-    /**
5122
-     * This will set the value for the given alias
5123
-     * @param string $value
5124
-     * @param string $datatype (one of %d, %s, %f)
5125
-     * @return int|string|float (int for %d, string for %s, float for %f)
5126
-     */
5127
-    protected function convertValueToDataType($value, $datatype)
5128
-    {
5129
-        switch ($datatype) {
5130
-            case '%f':
5131
-                return (float) $value;
5132
-            case '%d':
5133
-                return (int) $value;
5134
-            default:
5135
-                return (string) $value;
5136
-        }
5137
-    }
5138
-
5139
-
5140
-    /**
5141
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5142
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5143
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5144
-     * object (as set in the model_field!).
5145
-     *
5146
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5147
-     */
5148
-    public function create_default_object()
5149
-    {
5150
-        $this_model_fields_and_values = array();
5151
-        //setup the row using default values;
5152
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5153
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5154
-        }
5155
-        $className = $this->_get_class_name();
5156
-        $classInstance = EE_Registry::instance()
5157
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5158
-        return $classInstance;
5159
-    }
5160
-
5161
-
5162
-
5163
-    /**
5164
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5165
-     *                             or an stdClass where each property is the name of a column,
5166
-     * @return EE_Base_Class
5167
-     * @throws EE_Error
5168
-     */
5169
-    public function instantiate_class_from_array_or_object($cols_n_values)
5170
-    {
5171
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5172
-            $cols_n_values = get_object_vars($cols_n_values);
5173
-        }
5174
-        $primary_key = null;
5175
-        //make sure the array only has keys that are fields/columns on this model
5176
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5177
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5178
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5179
-        }
5180
-        $className = $this->_get_class_name();
5181
-        //check we actually found results that we can use to build our model object
5182
-        //if not, return null
5183
-        if ($this->has_primary_key_field()) {
5184
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5185
-                return null;
5186
-            }
5187
-        } else if ($this->unique_indexes()) {
5188
-            $first_column = reset($this_model_fields_n_values);
5189
-            if (empty($first_column)) {
5190
-                return null;
5191
-            }
5192
-        }
5193
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5194
-        if ($primary_key) {
5195
-            $classInstance = $this->get_from_entity_map($primary_key);
5196
-            if (! $classInstance) {
5197
-                $classInstance = EE_Registry::instance()
5198
-                                            ->load_class($className,
5199
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5200
-                // add this new object to the entity map
5201
-                $classInstance = $this->add_to_entity_map($classInstance);
5202
-            }
5203
-        } else {
5204
-            $classInstance = EE_Registry::instance()
5205
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5206
-                                            true, false);
5207
-        }
5208
-        return $classInstance;
5209
-    }
5210
-
5211
-
5212
-
5213
-    /**
5214
-     * Gets the model object from the  entity map if it exists
5215
-     *
5216
-     * @param int|string $id the ID of the model object
5217
-     * @return EE_Base_Class
5218
-     */
5219
-    public function get_from_entity_map($id)
5220
-    {
5221
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5222
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5223
-    }
5224
-
5225
-
5226
-
5227
-    /**
5228
-     * add_to_entity_map
5229
-     * Adds the object to the model's entity mappings
5230
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5231
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5232
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5233
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5234
-     *        then this method should be called immediately after the update query
5235
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5236
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5237
-     *
5238
-     * @param    EE_Base_Class $object
5239
-     * @throws EE_Error
5240
-     * @return \EE_Base_Class
5241
-     */
5242
-    public function add_to_entity_map(EE_Base_Class $object)
5243
-    {
5244
-        $className = $this->_get_class_name();
5245
-        if (! $object instanceof $className) {
5246
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5247
-                is_object($object) ? get_class($object) : $object, $className));
5248
-        }
5249
-        /** @var $object EE_Base_Class */
5250
-        if (! $object->ID()) {
5251
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5252
-                "event_espresso"), get_class($this)));
5253
-        }
5254
-        // double check it's not already there
5255
-        $classInstance = $this->get_from_entity_map($object->ID());
5256
-        if ($classInstance) {
5257
-            return $classInstance;
5258
-        }
5259
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5260
-        return $object;
5261
-    }
5262
-
5263
-
5264
-
5265
-    /**
5266
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5267
-     * if no identifier is provided, then the entire entity map is emptied
5268
-     *
5269
-     * @param int|string $id the ID of the model object
5270
-     * @return boolean
5271
-     */
5272
-    public function clear_entity_map($id = null)
5273
-    {
5274
-        if (empty($id)) {
5275
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5276
-            return true;
5277
-        }
5278
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5279
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5280
-            return true;
5281
-        }
5282
-        return false;
5283
-    }
5284
-
5285
-
5286
-
5287
-    /**
5288
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5289
-     * Given an array where keys are column (or column alias) names and values,
5290
-     * returns an array of their corresponding field names and database values
5291
-     *
5292
-     * @param array $cols_n_values
5293
-     * @return array
5294
-     */
5295
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5296
-    {
5297
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * _deduce_fields_n_values_from_cols_n_values
5304
-     * Given an array where keys are column (or column alias) names and values,
5305
-     * returns an array of their corresponding field names and database values
5306
-     *
5307
-     * @param string $cols_n_values
5308
-     * @return array
5309
-     */
5310
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5311
-    {
5312
-        $this_model_fields_n_values = array();
5313
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5314
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5315
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5316
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5317
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5318
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5319
-                    if (! $field_obj->is_db_only_field()) {
5320
-                        //prepare field as if its coming from db
5321
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5322
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5323
-                    }
5324
-                }
5325
-            } else {
5326
-                //the table's rows existed. Use their values
5327
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5328
-                    if (! $field_obj->is_db_only_field()) {
5329
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5330
-                            $cols_n_values, $field_obj->get_qualified_column(),
5331
-                            $field_obj->get_table_column()
5332
-                        );
5333
-                    }
5334
-                }
5335
-            }
5336
-        }
5337
-        return $this_model_fields_n_values;
5338
-    }
5339
-
5340
-
5341
-
5342
-    /**
5343
-     * @param $cols_n_values
5344
-     * @param $qualified_column
5345
-     * @param $regular_column
5346
-     * @return null
5347
-     */
5348
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5349
-    {
5350
-        $value = null;
5351
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5352
-        //does the field on the model relate to this column retrieved from the db?
5353
-        //or is it a db-only field? (not relating to the model)
5354
-        if (isset($cols_n_values[$qualified_column])) {
5355
-            $value = $cols_n_values[$qualified_column];
5356
-        } elseif (isset($cols_n_values[$regular_column])) {
5357
-            $value = $cols_n_values[$regular_column];
5358
-        }
5359
-        return $value;
5360
-    }
5361
-
5362
-
5363
-
5364
-    /**
5365
-     * refresh_entity_map_from_db
5366
-     * Makes sure the model object in the entity map at $id assumes the values
5367
-     * of the database (opposite of EE_base_Class::save())
5368
-     *
5369
-     * @param int|string $id
5370
-     * @return EE_Base_Class
5371
-     * @throws EE_Error
5372
-     */
5373
-    public function refresh_entity_map_from_db($id)
5374
-    {
5375
-        $obj_in_map = $this->get_from_entity_map($id);
5376
-        if ($obj_in_map) {
5377
-            $wpdb_results = $this->_get_all_wpdb_results(
5378
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5379
-            );
5380
-            if ($wpdb_results && is_array($wpdb_results)) {
5381
-                $one_row = reset($wpdb_results);
5382
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5383
-                    $obj_in_map->set_from_db($field_name, $db_value);
5384
-                }
5385
-                //clear the cache of related model objects
5386
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5387
-                    $obj_in_map->clear_cache($relation_name, null, true);
5388
-                }
5389
-            }
5390
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5391
-            return $obj_in_map;
5392
-        }
5393
-        return $this->get_one_by_ID($id);
5394
-    }
5395
-
5396
-
5397
-
5398
-    /**
5399
-     * refresh_entity_map_with
5400
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5401
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5402
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5403
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5404
-     *
5405
-     * @param int|string    $id
5406
-     * @param EE_Base_Class $replacing_model_obj
5407
-     * @return \EE_Base_Class
5408
-     * @throws EE_Error
5409
-     */
5410
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5411
-    {
5412
-        $obj_in_map = $this->get_from_entity_map($id);
5413
-        if ($obj_in_map) {
5414
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5415
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5416
-                    $obj_in_map->set($field_name, $value);
5417
-                }
5418
-                //make the model object in the entity map's cache match the $replacing_model_obj
5419
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5420
-                    $obj_in_map->clear_cache($relation_name, null, true);
5421
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5422
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5423
-                    }
5424
-                }
5425
-            }
5426
-            return $obj_in_map;
5427
-        }
5428
-        $this->add_to_entity_map($replacing_model_obj);
5429
-        return $replacing_model_obj;
5430
-    }
5431
-
5432
-
5433
-
5434
-    /**
5435
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5436
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5437
-     * require_once($this->_getClassName().".class.php");
5438
-     *
5439
-     * @return string
5440
-     */
5441
-    private function _get_class_name()
5442
-    {
5443
-        return "EE_" . $this->get_this_model_name();
5444
-    }
5445
-
5446
-
5447
-
5448
-    /**
5449
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5450
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5451
-     * it would be 'Events'.
5452
-     *
5453
-     * @param int $quantity
5454
-     * @return string
5455
-     */
5456
-    public function item_name($quantity = 1)
5457
-    {
5458
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5459
-    }
5460
-
5461
-
5462
-
5463
-    /**
5464
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5465
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5466
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5467
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5468
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5469
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5470
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5471
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5472
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5473
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5474
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5475
-     *        return $previousReturnValue.$returnString;
5476
-     * }
5477
-     * require('EEM_Answer.model.php');
5478
-     * $answer=EEM_Answer::instance();
5479
-     * echo $answer->my_callback('monkeys',100);
5480
-     * //will output "you called my_callback! and passed args:monkeys,100"
5481
-     *
5482
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5483
-     * @param array  $args       array of original arguments passed to the function
5484
-     * @throws EE_Error
5485
-     * @return mixed whatever the plugin which calls add_filter decides
5486
-     */
5487
-    public function __call($methodName, $args)
5488
-    {
5489
-        $className = get_class($this);
5490
-        $tagName = "FHEE__{$className}__{$methodName}";
5491
-        if (! has_filter($tagName)) {
5492
-            throw new EE_Error(
5493
-                sprintf(
5494
-                    __('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 );',
5495
-                        'event_espresso'),
5496
-                    $methodName,
5497
-                    $className,
5498
-                    $tagName,
5499
-                    '<br />'
5500
-                )
5501
-            );
5502
-        }
5503
-        return apply_filters($tagName, null, $this, $args);
5504
-    }
5505
-
5506
-
5507
-
5508
-    /**
5509
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5510
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5511
-     *
5512
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5513
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5514
-     *                                                       the object's class name
5515
-     *                                                       or object's ID
5516
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5517
-     *                                                       exists in the database. If it does not, we add it
5518
-     * @throws EE_Error
5519
-     * @return EE_Base_Class
5520
-     */
5521
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5522
-    {
5523
-        $className = $this->_get_class_name();
5524
-        if ($base_class_obj_or_id instanceof $className) {
5525
-            $model_object = $base_class_obj_or_id;
5526
-        } else {
5527
-            $primary_key_field = $this->get_primary_key_field();
5528
-            if (
5529
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5530
-                && (
5531
-                    is_int($base_class_obj_or_id)
5532
-                    || is_string($base_class_obj_or_id)
5533
-                )
5534
-            ) {
5535
-                // assume it's an ID.
5536
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5537
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5538
-            } else if (
5539
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5540
-                && is_string($base_class_obj_or_id)
5541
-            ) {
5542
-                // assume its a string representation of the object
5543
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5544
-            } else {
5545
-                throw new EE_Error(
5546
-                    sprintf(
5547
-                        __(
5548
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5549
-                            'event_espresso'
5550
-                        ),
5551
-                        $base_class_obj_or_id,
5552
-                        $this->_get_class_name(),
5553
-                        print_r($base_class_obj_or_id, true)
5554
-                    )
5555
-                );
5556
-            }
5557
-        }
5558
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5559
-            $model_object->save();
5560
-        }
5561
-        return $model_object;
5562
-    }
5563
-
5564
-
5565
-
5566
-    /**
5567
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5568
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5569
-     * returns it ID.
5570
-     *
5571
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5572
-     * @return int|string depending on the type of this model object's ID
5573
-     * @throws EE_Error
5574
-     */
5575
-    public function ensure_is_ID($base_class_obj_or_id)
5576
-    {
5577
-        $className = $this->_get_class_name();
5578
-        if ($base_class_obj_or_id instanceof $className) {
5579
-            /** @var $base_class_obj_or_id EE_Base_Class */
5580
-            $id = $base_class_obj_or_id->ID();
5581
-        } elseif (is_int($base_class_obj_or_id)) {
5582
-            //assume it's an ID
5583
-            $id = $base_class_obj_or_id;
5584
-        } elseif (is_string($base_class_obj_or_id)) {
5585
-            //assume its a string representation of the object
5586
-            $id = $base_class_obj_or_id;
5587
-        } else {
5588
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5589
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5590
-                print_r($base_class_obj_or_id, true)));
5591
-        }
5592
-        return $id;
5593
-    }
5594
-
5595
-
5596
-
5597
-    /**
5598
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5599
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5600
-     * been sanitized and converted into the appropriate domain.
5601
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5602
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5603
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5604
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5605
-     * $EVT = EEM_Event::instance(); $old_setting =
5606
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5607
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5608
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5609
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5610
-     *
5611
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5612
-     * @return void
5613
-     */
5614
-    public function assume_values_already_prepared_by_model_object(
5615
-        $values_already_prepared = self::not_prepared_by_model_object
5616
-    ) {
5617
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5618
-    }
5619
-
5620
-
5621
-
5622
-    /**
5623
-     * Read comments for assume_values_already_prepared_by_model_object()
5624
-     *
5625
-     * @return int
5626
-     */
5627
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5628
-    {
5629
-        return $this->_values_already_prepared_by_model_object;
5630
-    }
5631
-
5632
-
5633
-
5634
-    /**
5635
-     * Gets all the indexes on this model
5636
-     *
5637
-     * @return EE_Index[]
5638
-     */
5639
-    public function indexes()
5640
-    {
5641
-        return $this->_indexes;
5642
-    }
5643
-
5644
-
5645
-
5646
-    /**
5647
-     * Gets all the Unique Indexes on this model
5648
-     *
5649
-     * @return EE_Unique_Index[]
5650
-     */
5651
-    public function unique_indexes()
5652
-    {
5653
-        $unique_indexes = array();
5654
-        foreach ($this->_indexes as $name => $index) {
5655
-            if ($index instanceof EE_Unique_Index) {
5656
-                $unique_indexes [$name] = $index;
5657
-            }
5658
-        }
5659
-        return $unique_indexes;
5660
-    }
5661
-
5662
-
5663
-
5664
-    /**
5665
-     * Gets all the fields which, when combined, make the primary key.
5666
-     * This is usually just an array with 1 element (the primary key), but in cases
5667
-     * where there is no primary key, it's a combination of fields as defined
5668
-     * on a primary index
5669
-     *
5670
-     * @return EE_Model_Field_Base[] indexed by the field's name
5671
-     * @throws EE_Error
5672
-     */
5673
-    public function get_combined_primary_key_fields()
5674
-    {
5675
-        foreach ($this->indexes() as $index) {
5676
-            if ($index instanceof EE_Primary_Key_Index) {
5677
-                return $index->fields();
5678
-            }
5679
-        }
5680
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5681
-    }
5682
-
5683
-
5684
-
5685
-    /**
5686
-     * Used to build a primary key string (when the model has no primary key),
5687
-     * which can be used a unique string to identify this model object.
5688
-     *
5689
-     * @param array $cols_n_values keys are field names, values are their values
5690
-     * @return string
5691
-     * @throws EE_Error
5692
-     */
5693
-    public function get_index_primary_key_string($cols_n_values)
5694
-    {
5695
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5696
-            $this->get_combined_primary_key_fields());
5697
-        return http_build_query($cols_n_values_for_primary_key_index);
5698
-    }
5699
-
5700
-
5701
-
5702
-    /**
5703
-     * Gets the field values from the primary key string
5704
-     *
5705
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5706
-     * @param string $index_primary_key_string
5707
-     * @return null|array
5708
-     * @throws EE_Error
5709
-     */
5710
-    public function parse_index_primary_key_string($index_primary_key_string)
5711
-    {
5712
-        $key_fields = $this->get_combined_primary_key_fields();
5713
-        //check all of them are in the $id
5714
-        $key_vals_in_combined_pk = array();
5715
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5716
-        foreach ($key_fields as $key_field_name => $field_obj) {
5717
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5718
-                return null;
5719
-            }
5720
-        }
5721
-        return $key_vals_in_combined_pk;
5722
-    }
5723
-
5724
-
5725
-
5726
-    /**
5727
-     * verifies that an array of key-value pairs for model fields has a key
5728
-     * for each field comprising the primary key index
5729
-     *
5730
-     * @param array $key_vals
5731
-     * @return boolean
5732
-     * @throws EE_Error
5733
-     */
5734
-    public function has_all_combined_primary_key_fields($key_vals)
5735
-    {
5736
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5737
-        foreach ($keys_it_should_have as $key) {
5738
-            if (! isset($key_vals[$key])) {
5739
-                return false;
5740
-            }
5741
-        }
5742
-        return true;
5743
-    }
5744
-
5745
-
5746
-
5747
-    /**
5748
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5749
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5750
-     *
5751
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5752
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5753
-     * @throws EE_Error
5754
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5755
-     *                                                              indexed)
5756
-     */
5757
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5758
-    {
5759
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5760
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5761
-        } elseif (is_array($model_object_or_attributes_array)) {
5762
-            $attributes_array = $model_object_or_attributes_array;
5763
-        } else {
5764
-            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",
5765
-                "event_espresso"), $model_object_or_attributes_array));
5766
-        }
5767
-        //even copies obviously won't have the same ID, so remove the primary key
5768
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5769
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5770
-            unset($attributes_array[$this->primary_key_name()]);
5771
-        }
5772
-        if (isset($query_params[0])) {
5773
-            $query_params[0] = array_merge($attributes_array, $query_params);
5774
-        } else {
5775
-            $query_params[0] = $attributes_array;
5776
-        }
5777
-        return $this->get_all($query_params);
5778
-    }
5779
-
5780
-
5781
-
5782
-    /**
5783
-     * Gets the first copy we find. See get_all_copies for more details
5784
-     *
5785
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5786
-     * @param array $query_params
5787
-     * @return EE_Base_Class
5788
-     * @throws EE_Error
5789
-     */
5790
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5791
-    {
5792
-        if (! is_array($query_params)) {
5793
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5794
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5795
-                    gettype($query_params)), '4.6.0');
5796
-            $query_params = array();
5797
-        }
5798
-        $query_params['limit'] = 1;
5799
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5800
-        if (is_array($copies)) {
5801
-            return array_shift($copies);
5802
-        }
5803
-        return null;
5804
-    }
5805
-
5806
-
5807
-
5808
-    /**
5809
-     * Updates the item with the specified id. Ignores default query parameters because
5810
-     * we have specified the ID, and its assumed we KNOW what we're doing
5811
-     *
5812
-     * @param array      $fields_n_values keys are field names, values are their new values
5813
-     * @param int|string $id              the value of the primary key to update
5814
-     * @return int number of rows updated
5815
-     * @throws EE_Error
5816
-     */
5817
-    public function update_by_ID($fields_n_values, $id)
5818
-    {
5819
-        $query_params = array(
5820
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5821
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5822
-        );
5823
-        return $this->update($fields_n_values, $query_params);
5824
-    }
5825
-
5826
-
5827
-
5828
-    /**
5829
-     * Changes an operator which was supplied to the models into one usable in SQL
5830
-     *
5831
-     * @param string $operator_supplied
5832
-     * @return string an operator which can be used in SQL
5833
-     * @throws EE_Error
5834
-     */
5835
-    private function _prepare_operator_for_sql($operator_supplied)
5836
-    {
5837
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5838
-            : null;
5839
-        if ($sql_operator) {
5840
-            return $sql_operator;
5841
-        }
5842
-        throw new EE_Error(
5843
-            sprintf(
5844
-                __(
5845
-                    "The operator '%s' is not in the list of valid operators: %s",
5846
-                    "event_espresso"
5847
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5848
-            )
5849
-        );
5850
-    }
5851
-
5852
-
5853
-
5854
-    /**
5855
-     * Gets the valid operators
5856
-     * @return array keys are accepted strings, values are the SQL they are converted to
5857
-     */
5858
-    public function valid_operators(){
5859
-        return $this->_valid_operators;
5860
-    }
5861
-
5862
-
5863
-
5864
-    /**
5865
-     * Gets the between-style operators (take 2 arguments).
5866
-     * @return array keys are accepted strings, values are the SQL they are converted to
5867
-     */
5868
-    public function valid_between_style_operators()
5869
-    {
5870
-        return array_intersect(
5871
-            $this->valid_operators(),
5872
-            $this->_between_style_operators
5873
-        );
5874
-    }
5875
-
5876
-    /**
5877
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5878
-     * @return array keys are accepted strings, values are the SQL they are converted to
5879
-     */
5880
-    public function valid_like_style_operators()
5881
-    {
5882
-        return array_intersect(
5883
-            $this->valid_operators(),
5884
-            $this->_like_style_operators
5885
-        );
5886
-    }
5887
-
5888
-    /**
5889
-     * Gets the "in"-style operators
5890
-     * @return array keys are accepted strings, values are the SQL they are converted to
5891
-     */
5892
-    public function valid_in_style_operators()
5893
-    {
5894
-        return array_intersect(
5895
-            $this->valid_operators(),
5896
-            $this->_in_style_operators
5897
-        );
5898
-    }
5899
-
5900
-    /**
5901
-     * Gets the "null"-style operators (accept no arguments)
5902
-     * @return array keys are accepted strings, values are the SQL they are converted to
5903
-     */
5904
-    public function valid_null_style_operators()
5905
-    {
5906
-        return array_intersect(
5907
-            $this->valid_operators(),
5908
-            $this->_null_style_operators
5909
-        );
5910
-    }
5911
-
5912
-    /**
5913
-     * Gets an array where keys are the primary keys and values are their 'names'
5914
-     * (as determined by the model object's name() function, which is often overridden)
5915
-     *
5916
-     * @param array $query_params like get_all's
5917
-     * @return string[]
5918
-     * @throws EE_Error
5919
-     */
5920
-    public function get_all_names($query_params = array())
5921
-    {
5922
-        $objs = $this->get_all($query_params);
5923
-        $names = array();
5924
-        foreach ($objs as $obj) {
5925
-            $names[$obj->ID()] = $obj->name();
5926
-        }
5927
-        return $names;
5928
-    }
5929
-
5930
-
5931
-
5932
-    /**
5933
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5934
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5935
-     * this is duplicated effort and reduces efficiency) you would be better to use
5936
-     * array_keys() on $model_objects.
5937
-     *
5938
-     * @param \EE_Base_Class[] $model_objects
5939
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5940
-     *                                               in the returned array
5941
-     * @return array
5942
-     * @throws EE_Error
5943
-     */
5944
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5945
-    {
5946
-        if (! $this->has_primary_key_field()) {
5947
-            if (WP_DEBUG) {
5948
-                EE_Error::add_error(
5949
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5950
-                    __FILE__,
5951
-                    __FUNCTION__,
5952
-                    __LINE__
5953
-                );
5954
-            }
5955
-        }
5956
-        $IDs = array();
5957
-        foreach ($model_objects as $model_object) {
5958
-            $id = $model_object->ID();
5959
-            if (! $id) {
5960
-                if ($filter_out_empty_ids) {
5961
-                    continue;
5962
-                }
5963
-                if (WP_DEBUG) {
5964
-                    EE_Error::add_error(
5965
-                        __(
5966
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5967
-                            'event_espresso'
5968
-                        ),
5969
-                        __FILE__,
5970
-                        __FUNCTION__,
5971
-                        __LINE__
5972
-                    );
5973
-                }
5974
-            }
5975
-            $IDs[] = $id;
5976
-        }
5977
-        return $IDs;
5978
-    }
5979
-
5980
-
5981
-
5982
-    /**
5983
-     * Returns the string used in capabilities relating to this model. If there
5984
-     * are no capabilities that relate to this model returns false
5985
-     *
5986
-     * @return string|false
5987
-     */
5988
-    public function cap_slug()
5989
-    {
5990
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5991
-    }
5992
-
5993
-
5994
-
5995
-    /**
5996
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5997
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5998
-     * only returns the cap restrictions array in that context (ie, the array
5999
-     * at that key)
6000
-     *
6001
-     * @param string $context
6002
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6003
-     * @throws EE_Error
6004
-     */
6005
-    public function cap_restrictions($context = EEM_Base::caps_read)
6006
-    {
6007
-        EEM_Base::verify_is_valid_cap_context($context);
6008
-        //check if we ought to run the restriction generator first
6009
-        if (
6010
-            isset($this->_cap_restriction_generators[$context])
6011
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6012
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6013
-        ) {
6014
-            $this->_cap_restrictions[$context] = array_merge(
6015
-                $this->_cap_restrictions[$context],
6016
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
6017
-            );
6018
-        }
6019
-        //and make sure we've finalized the construction of each restriction
6020
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6021
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6022
-                $where_conditions_obj->_finalize_construct($this);
6023
-            }
6024
-        }
6025
-        return $this->_cap_restrictions[$context];
6026
-    }
6027
-
6028
-
6029
-
6030
-    /**
6031
-     * Indicating whether or not this model thinks its a wp core model
6032
-     *
6033
-     * @return boolean
6034
-     */
6035
-    public function is_wp_core_model()
6036
-    {
6037
-        return $this->_wp_core_model;
6038
-    }
6039
-
6040
-
6041
-
6042
-    /**
6043
-     * Gets all the caps that are missing which impose a restriction on
6044
-     * queries made in this context
6045
-     *
6046
-     * @param string $context one of EEM_Base::caps_ constants
6047
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6048
-     * @throws EE_Error
6049
-     */
6050
-    public function caps_missing($context = EEM_Base::caps_read)
6051
-    {
6052
-        $missing_caps = array();
6053
-        $cap_restrictions = $this->cap_restrictions($context);
6054
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6055
-            if (! EE_Capabilities::instance()
6056
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6057
-            ) {
6058
-                $missing_caps[$cap] = $restriction_if_no_cap;
6059
-            }
6060
-        }
6061
-        return $missing_caps;
6062
-    }
6063
-
6064
-
6065
-
6066
-    /**
6067
-     * Gets the mapping from capability contexts to action strings used in capability names
6068
-     *
6069
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6070
-     * one of 'read', 'edit', or 'delete'
6071
-     */
6072
-    public function cap_contexts_to_cap_action_map()
6073
-    {
6074
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6075
-            $this);
6076
-    }
6077
-
6078
-
6079
-
6080
-    /**
6081
-     * Gets the action string for the specified capability context
6082
-     *
6083
-     * @param string $context
6084
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6085
-     * @throws EE_Error
6086
-     */
6087
-    public function cap_action_for_context($context)
6088
-    {
6089
-        $mapping = $this->cap_contexts_to_cap_action_map();
6090
-        if (isset($mapping[$context])) {
6091
-            return $mapping[$context];
6092
-        }
6093
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6094
-            return $action;
6095
-        }
6096
-        throw new EE_Error(
6097
-            sprintf(
6098
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6099
-                $context,
6100
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6101
-            )
6102
-        );
6103
-    }
6104
-
6105
-
6106
-
6107
-    /**
6108
-     * Returns all the capability contexts which are valid when querying models
6109
-     *
6110
-     * @return array
6111
-     */
6112
-    public static function valid_cap_contexts()
6113
-    {
6114
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6115
-            self::caps_read,
6116
-            self::caps_read_admin,
6117
-            self::caps_edit,
6118
-            self::caps_delete,
6119
-        ));
6120
-    }
6121
-
6122
-
6123
-
6124
-    /**
6125
-     * Returns all valid options for 'default_where_conditions'
6126
-     *
6127
-     * @return array
6128
-     */
6129
-    public static function valid_default_where_conditions()
6130
-    {
6131
-        return array(
6132
-            EEM_Base::default_where_conditions_all,
6133
-            EEM_Base::default_where_conditions_this_only,
6134
-            EEM_Base::default_where_conditions_others_only,
6135
-            EEM_Base::default_where_conditions_minimum_all,
6136
-            EEM_Base::default_where_conditions_minimum_others,
6137
-            EEM_Base::default_where_conditions_none
6138
-        );
6139
-    }
6140
-
6141
-    // public static function default_where_conditions_full
6142
-    /**
6143
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6144
-     *
6145
-     * @param string $context
6146
-     * @return bool
6147
-     * @throws EE_Error
6148
-     */
6149
-    static public function verify_is_valid_cap_context($context)
6150
-    {
6151
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6152
-        if (in_array($context, $valid_cap_contexts)) {
6153
-            return true;
6154
-        }
6155
-        throw new EE_Error(
6156
-            sprintf(
6157
-                __(
6158
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6159
-                    'event_espresso'
6160
-                ),
6161
-                $context,
6162
-                'EEM_Base',
6163
-                implode(',', $valid_cap_contexts)
6164
-            )
6165
-        );
6166
-    }
6167
-
6168
-
6169
-
6170
-    /**
6171
-     * Clears all the models field caches. This is only useful when a sub-class
6172
-     * might have added a field or something and these caches might be invalidated
6173
-     */
6174
-    protected function _invalidate_field_caches()
6175
-    {
6176
-        $this->_cache_foreign_key_to_fields = array();
6177
-        $this->_cached_fields = null;
6178
-        $this->_cached_fields_non_db_only = null;
6179
-    }
6180
-
6181
-
6182
-
6183
-    /**
6184
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6185
-     * (eg "and", "or", "not").
6186
-     *
6187
-     * @return array
6188
-     */
6189
-    public function logic_query_param_keys()
6190
-    {
6191
-        return $this->_logic_query_param_keys;
6192
-    }
6193
-
6194
-
6195
-
6196
-    /**
6197
-     * Determines whether or not the where query param array key is for a logic query param.
6198
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6199
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6200
-     *
6201
-     * @param $query_param_key
6202
-     * @return bool
6203
-     */
6204
-    public function is_logic_query_param_key($query_param_key)
6205
-    {
6206
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6207
-            if ($query_param_key === $logic_query_param_key
6208
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6209
-            ) {
6210
-                return true;
6211
-            }
6212
-        }
6213
-        return false;
6214
-    }
3773
+		}
3774
+		return $null_friendly_where_conditions;
3775
+	}
3776
+
3777
+
3778
+
3779
+	/**
3780
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3781
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3782
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3783
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3784
+	 *
3785
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3786
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3787
+	 */
3788
+	private function _get_default_where_conditions($model_relation_path = null)
3789
+	{
3790
+		if ($this->_ignore_where_strategy) {
3791
+			return array();
3792
+		}
3793
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3794
+	}
3795
+
3796
+
3797
+
3798
+	/**
3799
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3800
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3801
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3802
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3803
+	 * Similar to _get_default_where_conditions
3804
+	 *
3805
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3806
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3807
+	 */
3808
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3809
+	{
3810
+		if ($this->_ignore_where_strategy) {
3811
+			return array();
3812
+		}
3813
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3814
+	}
3815
+
3816
+
3817
+
3818
+	/**
3819
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3820
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3821
+	 *
3822
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3823
+	 * @return string
3824
+	 * @throws EE_Error
3825
+	 */
3826
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3827
+	{
3828
+		$selects = $this->_get_columns_to_select_for_this_model();
3829
+		foreach (
3830
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3831
+			$name_of_other_model_included
3832
+		) {
3833
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3834
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3835
+			foreach ($other_model_selects as $key => $value) {
3836
+				$selects[] = $value;
3837
+			}
3838
+		}
3839
+		return implode(", ", $selects);
3840
+	}
3841
+
3842
+
3843
+
3844
+	/**
3845
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3846
+	 * So that's going to be the columns for all the fields on the model
3847
+	 *
3848
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3849
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3850
+	 */
3851
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3852
+	{
3853
+		$fields = $this->field_settings();
3854
+		$selects = array();
3855
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3856
+			$this->get_this_model_name());
3857
+		foreach ($fields as $field_obj) {
3858
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3859
+						 . $field_obj->get_table_alias()
3860
+						 . "."
3861
+						 . $field_obj->get_table_column()
3862
+						 . " AS '"
3863
+						 . $table_alias_with_model_relation_chain_prefix
3864
+						 . $field_obj->get_table_alias()
3865
+						 . "."
3866
+						 . $field_obj->get_table_column()
3867
+						 . "'";
3868
+		}
3869
+		//make sure we are also getting the PKs of each table
3870
+		$tables = $this->get_tables();
3871
+		if (count($tables) > 1) {
3872
+			foreach ($tables as $table_obj) {
3873
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3874
+									   . $table_obj->get_fully_qualified_pk_column();
3875
+				if (! in_array($qualified_pk_column, $selects)) {
3876
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3877
+				}
3878
+			}
3879
+		}
3880
+		return $selects;
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3887
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3888
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3889
+	 * SQL for joining, and the data types
3890
+	 *
3891
+	 * @param null|string                 $original_query_param
3892
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3893
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3894
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3895
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3896
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3897
+	 *                                                          or 'Registration's
3898
+	 * @param string                      $original_query_param what it originally was (eg
3899
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3900
+	 *                                                          matches $query_param
3901
+	 * @throws EE_Error
3902
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3903
+	 */
3904
+	private function _extract_related_model_info_from_query_param(
3905
+		$query_param,
3906
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3907
+		$query_param_type,
3908
+		$original_query_param = null
3909
+	) {
3910
+		if ($original_query_param === null) {
3911
+			$original_query_param = $query_param;
3912
+		}
3913
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3914
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3915
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3916
+		$allow_fields = in_array(
3917
+			$query_param_type,
3918
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3919
+			true
3920
+		);
3921
+		//check to see if we have a field on this model
3922
+		$this_model_fields = $this->field_settings(true);
3923
+		if (array_key_exists($query_param, $this_model_fields)) {
3924
+			if ($allow_fields) {
3925
+				return;
3926
+			}
3927
+			throw new EE_Error(
3928
+				sprintf(
3929
+					__(
3930
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3931
+						"event_espresso"
3932
+					),
3933
+					$query_param, get_class($this), $query_param_type, $original_query_param
3934
+				)
3935
+			);
3936
+		}
3937
+		//check if this is a special logic query param
3938
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3939
+			if ($allow_logic_query_params) {
3940
+				return;
3941
+			}
3942
+			throw new EE_Error(
3943
+				sprintf(
3944
+					__(
3945
+						'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',
3946
+						'event_espresso'
3947
+					),
3948
+					implode('", "', $this->_logic_query_param_keys),
3949
+					$query_param,
3950
+					get_class($this),
3951
+					'<br />',
3952
+					"\t"
3953
+					. ' $passed_in_query_info = <pre>'
3954
+					. print_r($passed_in_query_info, true)
3955
+					. '</pre>'
3956
+					. "\n\t"
3957
+					. ' $query_param_type = '
3958
+					. $query_param_type
3959
+					. "\n\t"
3960
+					. ' $original_query_param = '
3961
+					. $original_query_param
3962
+				)
3963
+			);
3964
+		}
3965
+		//check if it's a custom selection
3966
+		if ($this->_custom_selections instanceof CustomSelects
3967
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
3968
+		) {
3969
+			return;
3970
+		}
3971
+		//check if has a model name at the beginning
3972
+		//and
3973
+		//check if it's a field on a related model
3974
+		if ($this->extractJoinModelFromQueryParams(
3975
+			$passed_in_query_info,
3976
+			$query_param,
3977
+			$original_query_param,
3978
+			$query_param_type
3979
+		)) {
3980
+			return;
3981
+		}
3982
+
3983
+		//ok so $query_param didn't start with a model name
3984
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3985
+		//it's wack, that's what it is
3986
+		throw new EE_Error(
3987
+			sprintf(
3988
+				esc_html__(
3989
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3990
+					"event_espresso"
3991
+				),
3992
+				$query_param,
3993
+				get_class($this),
3994
+				$query_param_type,
3995
+				$original_query_param
3996
+			)
3997
+		);
3998
+	}
3999
+
4000
+
4001
+	/**
4002
+	 * Extracts any possible join model information from the provided possible_join_string.
4003
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4004
+	 * parts that should be added to the query.
4005
+	 *
4006
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4007
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4008
+	 * @param null|string                 $original_query_param
4009
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4010
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4011
+	 * @return bool  returns true if a join was added and false if not.
4012
+	 * @throws EE_Error
4013
+	 */
4014
+	private function extractJoinModelFromQueryParams(
4015
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4016
+		$possible_join_string,
4017
+		$original_query_param,
4018
+		$query_parameter_type
4019
+	) {
4020
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4021
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4022
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4023
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4024
+				if ($possible_join_string === '') {
4025
+					//nothing left to $query_param
4026
+					//we should actually end in a field name, not a model like this!
4027
+					throw new EE_Error(
4028
+						sprintf(
4029
+							esc_html__(
4030
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4031
+								"event_espresso"
4032
+							),
4033
+							$possible_join_string,
4034
+							$query_parameter_type,
4035
+							get_class($this),
4036
+							$valid_related_model_name
4037
+						)
4038
+					);
4039
+				}
4040
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4041
+				$related_model_obj->_extract_related_model_info_from_query_param(
4042
+					$possible_join_string,
4043
+					$query_info_carrier,
4044
+					$query_parameter_type,
4045
+					$original_query_param
4046
+				);
4047
+				return true;
4048
+			}
4049
+			if ($possible_join_string === $valid_related_model_name) {
4050
+				$this->_add_join_to_model(
4051
+					$valid_related_model_name,
4052
+					$query_info_carrier,
4053
+					$original_query_param
4054
+				);
4055
+				return true;
4056
+			}
4057
+		}
4058
+		return false;
4059
+	}
4060
+
4061
+
4062
+	/**
4063
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4064
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4065
+	 * @throws EE_Error
4066
+	 */
4067
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4068
+	{
4069
+		if ($this->_custom_selections instanceof CustomSelects
4070
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4071
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4072
+			)
4073
+		) {
4074
+			$original_selects = $this->_custom_selections->originalSelects();
4075
+			foreach ($original_selects as $alias => $select_configuration) {
4076
+				$this->extractJoinModelFromQueryParams(
4077
+					$query_info_carrier,
4078
+					$select_configuration[0],
4079
+					$select_configuration[0],
4080
+					'custom_selects'
4081
+				);
4082
+			}
4083
+		}
4084
+	}
4085
+
4086
+
4087
+
4088
+	/**
4089
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4090
+	 * and store it on $passed_in_query_info
4091
+	 *
4092
+	 * @param string                      $model_name
4093
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4094
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4095
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4096
+	 *                                                          and are adding a join to 'Payment' with the original
4097
+	 *                                                          query param key
4098
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4099
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4100
+	 *                                                          Payment wants to add default query params so that it
4101
+	 *                                                          will know what models to prepend onto its default query
4102
+	 *                                                          params or in case it wants to rename tables (in case
4103
+	 *                                                          there are multiple joins to the same table)
4104
+	 * @return void
4105
+	 * @throws EE_Error
4106
+	 */
4107
+	private function _add_join_to_model(
4108
+		$model_name,
4109
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4110
+		$original_query_param
4111
+	) {
4112
+		$relation_obj = $this->related_settings_for($model_name);
4113
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4114
+		//check if the relation is HABTM, because then we're essentially doing two joins
4115
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
4116
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4117
+			$join_model_obj = $relation_obj->get_join_model();
4118
+			//replace the model specified with the join model for this relation chain, whi
4119
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4120
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4121
+			$passed_in_query_info->merge(
4122
+				new EE_Model_Query_Info_Carrier(
4123
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4124
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4125
+				)
4126
+			);
4127
+		}
4128
+		//now just join to the other table pointed to by the relation object, and add its data types
4129
+		$passed_in_query_info->merge(
4130
+			new EE_Model_Query_Info_Carrier(
4131
+				array($model_relation_chain => $model_name),
4132
+				$relation_obj->get_join_statement($model_relation_chain)
4133
+			)
4134
+		);
4135
+	}
4136
+
4137
+
4138
+
4139
+	/**
4140
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4141
+	 *
4142
+	 * @param array $where_params like EEM_Base::get_all
4143
+	 * @return string of SQL
4144
+	 * @throws EE_Error
4145
+	 */
4146
+	private function _construct_where_clause($where_params)
4147
+	{
4148
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4149
+		if ($SQL) {
4150
+			return " WHERE " . $SQL;
4151
+		}
4152
+		return '';
4153
+	}
4154
+
4155
+
4156
+
4157
+	/**
4158
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4159
+	 * and should be passed HAVING parameters, not WHERE parameters
4160
+	 *
4161
+	 * @param array $having_params
4162
+	 * @return string
4163
+	 * @throws EE_Error
4164
+	 */
4165
+	private function _construct_having_clause($having_params)
4166
+	{
4167
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4168
+		if ($SQL) {
4169
+			return " HAVING " . $SQL;
4170
+		}
4171
+		return '';
4172
+	}
4173
+
4174
+
4175
+	/**
4176
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4177
+	 * Event_Meta.meta_value = 'foo'))"
4178
+	 *
4179
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4180
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4181
+	 * @throws EE_Error
4182
+	 * @return string of SQL
4183
+	 */
4184
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4185
+	{
4186
+		$where_clauses = array();
4187
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4188
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4189
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4190
+				switch ($query_param) {
4191
+					case 'not':
4192
+					case 'NOT':
4193
+						$where_clauses[] = "! ("
4194
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4195
+								$glue)
4196
+										   . ")";
4197
+						break;
4198
+					case 'and':
4199
+					case 'AND':
4200
+						$where_clauses[] = " ("
4201
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4202
+								' AND ')
4203
+										   . ")";
4204
+						break;
4205
+					case 'or':
4206
+					case 'OR':
4207
+						$where_clauses[] = " ("
4208
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4209
+								' OR ')
4210
+										   . ")";
4211
+						break;
4212
+				}
4213
+			} else {
4214
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4215
+				//if it's not a normal field, maybe it's a custom selection?
4216
+				if (! $field_obj) {
4217
+					if ($this->_custom_selections instanceof CustomSelects) {
4218
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4219
+					} else {
4220
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4221
+							"event_espresso"), $query_param));
4222
+					}
4223
+				}
4224
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4225
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4226
+			}
4227
+		}
4228
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4229
+	}
4230
+
4231
+
4232
+
4233
+	/**
4234
+	 * Takes the input parameter and extract the table name (alias) and column name
4235
+	 *
4236
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4237
+	 * @throws EE_Error
4238
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4239
+	 */
4240
+	private function _deduce_column_name_from_query_param($query_param)
4241
+	{
4242
+		$field = $this->_deduce_field_from_query_param($query_param);
4243
+		if ($field) {
4244
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4245
+				$query_param);
4246
+			return $table_alias_prefix . $field->get_qualified_column();
4247
+		}
4248
+		if ($this->_custom_selections instanceof CustomSelects
4249
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4250
+		) {
4251
+			//maybe it's custom selection item?
4252
+			//if so, just use it as the "column name"
4253
+			return $query_param;
4254
+		}
4255
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4256
+			? implode(',', $this->_custom_selections->columnAliases())
4257
+			: '';
4258
+		throw new EE_Error(
4259
+			sprintf(
4260
+				__(
4261
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4262
+					"event_espresso"
4263
+				), $query_param, $custom_select_aliases
4264
+			)
4265
+		);
4266
+	}
4267
+
4268
+
4269
+
4270
+	/**
4271
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4272
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4273
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4274
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4275
+	 *
4276
+	 * @param string $condition_query_param_key
4277
+	 * @return string
4278
+	 */
4279
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4280
+	{
4281
+		$pos_of_star = strpos($condition_query_param_key, '*');
4282
+		if ($pos_of_star === false) {
4283
+			return $condition_query_param_key;
4284
+		}
4285
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4286
+		return $condition_query_param_sans_star;
4287
+	}
4288
+
4289
+
4290
+
4291
+	/**
4292
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4293
+	 *
4294
+	 * @param                            mixed      array | string    $op_and_value
4295
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4296
+	 * @throws EE_Error
4297
+	 * @return string
4298
+	 */
4299
+	private function _construct_op_and_value($op_and_value, $field_obj)
4300
+	{
4301
+		if (is_array($op_and_value)) {
4302
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4303
+			if (! $operator) {
4304
+				$php_array_like_string = array();
4305
+				foreach ($op_and_value as $key => $value) {
4306
+					$php_array_like_string[] = "$key=>$value";
4307
+				}
4308
+				throw new EE_Error(
4309
+					sprintf(
4310
+						__(
4311
+							"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))",
4312
+							"event_espresso"
4313
+						),
4314
+						implode(",", $php_array_like_string)
4315
+					)
4316
+				);
4317
+			}
4318
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4319
+		} else {
4320
+			$operator = '=';
4321
+			$value = $op_and_value;
4322
+		}
4323
+		//check to see if the value is actually another field
4324
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4325
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4326
+		}
4327
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4328
+			//in this case, the value should be an array, or at least a comma-separated list
4329
+			//it will need to handle a little differently
4330
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4331
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4332
+			return $operator . SP . $cleaned_value;
4333
+		}
4334
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4335
+			//the value should be an array with count of two.
4336
+			if (count($value) !== 2) {
4337
+				throw new EE_Error(
4338
+					sprintf(
4339
+						__(
4340
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4341
+							'event_espresso'
4342
+						),
4343
+						"BETWEEN"
4344
+					)
4345
+				);
4346
+			}
4347
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4348
+			return $operator . SP . $cleaned_value;
4349
+		}
4350
+		if (in_array($operator, $this->valid_null_style_operators())) {
4351
+			if ($value !== null) {
4352
+				throw new EE_Error(
4353
+					sprintf(
4354
+						__(
4355
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4356
+							"event_espresso"
4357
+						),
4358
+						$value,
4359
+						$operator
4360
+					)
4361
+				);
4362
+			}
4363
+			return $operator;
4364
+		}
4365
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4366
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4367
+			//remove other junk. So just treat it as a string.
4368
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4369
+		}
4370
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4371
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4372
+		}
4373
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4374
+			throw new EE_Error(
4375
+				sprintf(
4376
+					__(
4377
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4378
+						'event_espresso'
4379
+					),
4380
+					$operator,
4381
+					$operator
4382
+				)
4383
+			);
4384
+		}
4385
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4386
+			throw new EE_Error(
4387
+				sprintf(
4388
+					__(
4389
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4390
+						'event_espresso'
4391
+					),
4392
+					$operator,
4393
+					$operator
4394
+				)
4395
+			);
4396
+		}
4397
+		throw new EE_Error(
4398
+			sprintf(
4399
+				__(
4400
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4401
+					"event_espresso"
4402
+				),
4403
+				http_build_query($op_and_value)
4404
+			)
4405
+		);
4406
+	}
4407
+
4408
+
4409
+
4410
+	/**
4411
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4412
+	 *
4413
+	 * @param array                      $values
4414
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4415
+	 *                                              '%s'
4416
+	 * @return string
4417
+	 * @throws EE_Error
4418
+	 */
4419
+	public function _construct_between_value($values, $field_obj)
4420
+	{
4421
+		$cleaned_values = array();
4422
+		foreach ($values as $value) {
4423
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4424
+		}
4425
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4426
+	}
4427
+
4428
+
4429
+
4430
+	/**
4431
+	 * Takes an array or a comma-separated list of $values and cleans them
4432
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4433
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4434
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4435
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4436
+	 *
4437
+	 * @param mixed                      $values    array or comma-separated string
4438
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4439
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4440
+	 * @throws EE_Error
4441
+	 */
4442
+	public function _construct_in_value($values, $field_obj)
4443
+	{
4444
+		//check if the value is a CSV list
4445
+		if (is_string($values)) {
4446
+			//in which case, turn it into an array
4447
+			$values = explode(",", $values);
4448
+		}
4449
+		$cleaned_values = array();
4450
+		foreach ($values as $value) {
4451
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4452
+		}
4453
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4454
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4455
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4456
+		if (empty($cleaned_values)) {
4457
+			$all_fields = $this->field_settings();
4458
+			$a_field = array_shift($all_fields);
4459
+			$main_table = $this->_get_main_table();
4460
+			$cleaned_values[] = "SELECT "
4461
+								. $a_field->get_table_column()
4462
+								. " FROM "
4463
+								. $main_table->get_table_name()
4464
+								. " WHERE FALSE";
4465
+		}
4466
+		return "(" . implode(",", $cleaned_values) . ")";
4467
+	}
4468
+
4469
+
4470
+
4471
+	/**
4472
+	 * @param mixed                      $value
4473
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4474
+	 * @throws EE_Error
4475
+	 * @return false|null|string
4476
+	 */
4477
+	private function _wpdb_prepare_using_field($value, $field_obj)
4478
+	{
4479
+		/** @type WPDB $wpdb */
4480
+		global $wpdb;
4481
+		if ($field_obj instanceof EE_Model_Field_Base) {
4482
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4483
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4484
+		} //$field_obj should really just be a data type
4485
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4486
+			throw new EE_Error(
4487
+				sprintf(
4488
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4489
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4490
+				)
4491
+			);
4492
+		}
4493
+		return $wpdb->prepare($field_obj, $value);
4494
+	}
4495
+
4496
+
4497
+
4498
+	/**
4499
+	 * Takes the input parameter and finds the model field that it indicates.
4500
+	 *
4501
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4502
+	 * @throws EE_Error
4503
+	 * @return EE_Model_Field_Base
4504
+	 */
4505
+	protected function _deduce_field_from_query_param($query_param_name)
4506
+	{
4507
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4508
+		//which will help us find the database table and column
4509
+		$query_param_parts = explode(".", $query_param_name);
4510
+		if (empty($query_param_parts)) {
4511
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4512
+				'event_espresso'), $query_param_name));
4513
+		}
4514
+		$number_of_parts = count($query_param_parts);
4515
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4516
+		if ($number_of_parts === 1) {
4517
+			$field_name = $last_query_param_part;
4518
+			$model_obj = $this;
4519
+		} else {// $number_of_parts >= 2
4520
+			//the last part is the column name, and there are only 2parts. therefore...
4521
+			$field_name = $last_query_param_part;
4522
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4523
+		}
4524
+		try {
4525
+			return $model_obj->field_settings_for($field_name);
4526
+		} catch (EE_Error $e) {
4527
+			return null;
4528
+		}
4529
+	}
4530
+
4531
+
4532
+
4533
+	/**
4534
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4535
+	 * alias and column which corresponds to it
4536
+	 *
4537
+	 * @param string $field_name
4538
+	 * @throws EE_Error
4539
+	 * @return string
4540
+	 */
4541
+	public function _get_qualified_column_for_field($field_name)
4542
+	{
4543
+		$all_fields = $this->field_settings();
4544
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4545
+		if ($field) {
4546
+			return $field->get_qualified_column();
4547
+		}
4548
+		throw new EE_Error(
4549
+			sprintf(
4550
+				__(
4551
+					"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.",
4552
+					'event_espresso'
4553
+				), $field_name, get_class($this)
4554
+			)
4555
+		);
4556
+	}
4557
+
4558
+
4559
+
4560
+	/**
4561
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4562
+	 * Example usage:
4563
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4564
+	 *      array(),
4565
+	 *      ARRAY_A,
4566
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4567
+	 *  );
4568
+	 * is equivalent to
4569
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4570
+	 * and
4571
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4572
+	 *      array(
4573
+	 *          array(
4574
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4575
+	 *          ),
4576
+	 *          ARRAY_A,
4577
+	 *          implode(
4578
+	 *              ', ',
4579
+	 *              array_merge(
4580
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4581
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4582
+	 *              )
4583
+	 *          )
4584
+	 *      )
4585
+	 *  );
4586
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4587
+	 *
4588
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4589
+	 *                                            and the one whose fields you are selecting for example: when querying
4590
+	 *                                            tickets model and selecting fields from the tickets model you would
4591
+	 *                                            leave this parameter empty, because no models are needed to join
4592
+	 *                                            between the queried model and the selected one. Likewise when
4593
+	 *                                            querying the datetime model and selecting fields from the tickets
4594
+	 *                                            model, it would also be left empty, because there is a direct
4595
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4596
+	 *                                            them together. However, when querying from the event model and
4597
+	 *                                            selecting fields from the ticket model, you should provide the string
4598
+	 *                                            'Datetime', indicating that the event model must first join to the
4599
+	 *                                            datetime model in order to find its relation to ticket model.
4600
+	 *                                            Also, when querying from the venue model and selecting fields from
4601
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4602
+	 *                                            indicating you need to join the venue model to the event model,
4603
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4604
+	 *                                            This string is used to deduce the prefix that gets added onto the
4605
+	 *                                            models' tables qualified columns
4606
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4607
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4608
+	 *                                            qualified column names
4609
+	 * @return array|string
4610
+	 */
4611
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4612
+	{
4613
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4614
+		$qualified_columns = array();
4615
+		foreach ($this->field_settings() as $field_name => $field) {
4616
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4617
+		}
4618
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4619
+	}
4620
+
4621
+
4622
+
4623
+	/**
4624
+	 * constructs the select use on special limit joins
4625
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4626
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4627
+	 * (as that is typically where the limits would be set).
4628
+	 *
4629
+	 * @param  string       $table_alias The table the select is being built for
4630
+	 * @param  mixed|string $limit       The limit for this select
4631
+	 * @return string                The final select join element for the query.
4632
+	 */
4633
+	public function _construct_limit_join_select($table_alias, $limit)
4634
+	{
4635
+		$SQL = '';
4636
+		foreach ($this->_tables as $table_obj) {
4637
+			if ($table_obj instanceof EE_Primary_Table) {
4638
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4639
+					? $table_obj->get_select_join_limit($limit)
4640
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4641
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4642
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4643
+					? $table_obj->get_select_join_limit_join($limit)
4644
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4645
+			}
4646
+		}
4647
+		return $SQL;
4648
+	}
4649
+
4650
+
4651
+
4652
+	/**
4653
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4654
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4655
+	 *
4656
+	 * @return string SQL
4657
+	 * @throws EE_Error
4658
+	 */
4659
+	public function _construct_internal_join()
4660
+	{
4661
+		$SQL = $this->_get_main_table()->get_table_sql();
4662
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4663
+		return $SQL;
4664
+	}
4665
+
4666
+
4667
+
4668
+	/**
4669
+	 * Constructs the SQL for joining all the tables on this model.
4670
+	 * Normally $alias should be the primary table's alias, but in cases where
4671
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4672
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4673
+	 * alias, this will construct SQL like:
4674
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4675
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4676
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4677
+	 *
4678
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4679
+	 * @return string
4680
+	 */
4681
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4682
+	{
4683
+		$SQL = '';
4684
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4685
+		foreach ($this->_tables as $table_obj) {
4686
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4687
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4688
+					//so we're joining to this table, meaning the table is already in
4689
+					//the FROM statement, BUT the primary table isn't. So we want
4690
+					//to add the inverse join sql
4691
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4692
+				} else {
4693
+					//just add a regular JOIN to this table from the primary table
4694
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4695
+				}
4696
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4697
+		}
4698
+		return $SQL;
4699
+	}
4700
+
4701
+
4702
+
4703
+	/**
4704
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4705
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4706
+	 * their data type (eg, '%s', '%d', etc)
4707
+	 *
4708
+	 * @return array
4709
+	 */
4710
+	public function _get_data_types()
4711
+	{
4712
+		$data_types = array();
4713
+		foreach ($this->field_settings() as $field_obj) {
4714
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4715
+			/** @var $field_obj EE_Model_Field_Base */
4716
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4717
+		}
4718
+		return $data_types;
4719
+	}
4720
+
4721
+
4722
+
4723
+	/**
4724
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4725
+	 *
4726
+	 * @param string $model_name
4727
+	 * @throws EE_Error
4728
+	 * @return EEM_Base
4729
+	 */
4730
+	public function get_related_model_obj($model_name)
4731
+	{
4732
+		$model_classname = "EEM_" . $model_name;
4733
+		if (! class_exists($model_classname)) {
4734
+			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",
4735
+				'event_espresso'), $model_name, $model_classname));
4736
+		}
4737
+		return call_user_func($model_classname . "::instance");
4738
+	}
4739
+
4740
+
4741
+
4742
+	/**
4743
+	 * Returns the array of EE_ModelRelations for this model.
4744
+	 *
4745
+	 * @return EE_Model_Relation_Base[]
4746
+	 */
4747
+	public function relation_settings()
4748
+	{
4749
+		return $this->_model_relations;
4750
+	}
4751
+
4752
+
4753
+
4754
+	/**
4755
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4756
+	 * because without THOSE models, this model probably doesn't have much purpose.
4757
+	 * (Eg, without an event, datetimes have little purpose.)
4758
+	 *
4759
+	 * @return EE_Belongs_To_Relation[]
4760
+	 */
4761
+	public function belongs_to_relations()
4762
+	{
4763
+		$belongs_to_relations = array();
4764
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4765
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4766
+				$belongs_to_relations[$model_name] = $relation_obj;
4767
+			}
4768
+		}
4769
+		return $belongs_to_relations;
4770
+	}
4771
+
4772
+
4773
+
4774
+	/**
4775
+	 * Returns the specified EE_Model_Relation, or throws an exception
4776
+	 *
4777
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4778
+	 * @throws EE_Error
4779
+	 * @return EE_Model_Relation_Base
4780
+	 */
4781
+	public function related_settings_for($relation_name)
4782
+	{
4783
+		$relatedModels = $this->relation_settings();
4784
+		if (! array_key_exists($relation_name, $relatedModels)) {
4785
+			throw new EE_Error(
4786
+				sprintf(
4787
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4788
+						'event_espresso'),
4789
+					$relation_name,
4790
+					$this->_get_class_name(),
4791
+					implode(', ', array_keys($relatedModels))
4792
+				)
4793
+			);
4794
+		}
4795
+		return $relatedModels[$relation_name];
4796
+	}
4797
+
4798
+
4799
+
4800
+	/**
4801
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4802
+	 * fields
4803
+	 *
4804
+	 * @param string $fieldName
4805
+	 * @param boolean $include_db_only_fields
4806
+	 * @throws EE_Error
4807
+	 * @return EE_Model_Field_Base
4808
+	 */
4809
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4810
+	{
4811
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4812
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4813
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4814
+				get_class($this)));
4815
+		}
4816
+		return $fieldSettings[$fieldName];
4817
+	}
4818
+
4819
+
4820
+
4821
+	/**
4822
+	 * Checks if this field exists on this model
4823
+	 *
4824
+	 * @param string $fieldName a key in the model's _field_settings array
4825
+	 * @return boolean
4826
+	 */
4827
+	public function has_field($fieldName)
4828
+	{
4829
+		$fieldSettings = $this->field_settings(true);
4830
+		if (isset($fieldSettings[$fieldName])) {
4831
+			return true;
4832
+		}
4833
+		return false;
4834
+	}
4835
+
4836
+
4837
+
4838
+	/**
4839
+	 * Returns whether or not this model has a relation to the specified model
4840
+	 *
4841
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4842
+	 * @return boolean
4843
+	 */
4844
+	public function has_relation($relation_name)
4845
+	{
4846
+		$relations = $this->relation_settings();
4847
+		if (isset($relations[$relation_name])) {
4848
+			return true;
4849
+		}
4850
+		return false;
4851
+	}
4852
+
4853
+
4854
+
4855
+	/**
4856
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4857
+	 * Eg, on EE_Answer that would be ANS_ID field object
4858
+	 *
4859
+	 * @param $field_obj
4860
+	 * @return boolean
4861
+	 */
4862
+	public function is_primary_key_field($field_obj)
4863
+	{
4864
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4865
+	}
4866
+
4867
+
4868
+
4869
+	/**
4870
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4871
+	 * Eg, on EE_Answer that would be ANS_ID field object
4872
+	 *
4873
+	 * @return EE_Model_Field_Base
4874
+	 * @throws EE_Error
4875
+	 */
4876
+	public function get_primary_key_field()
4877
+	{
4878
+		if ($this->_primary_key_field === null) {
4879
+			foreach ($this->field_settings(true) as $field_obj) {
4880
+				if ($this->is_primary_key_field($field_obj)) {
4881
+					$this->_primary_key_field = $field_obj;
4882
+					break;
4883
+				}
4884
+			}
4885
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4886
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4887
+					get_class($this)));
4888
+			}
4889
+		}
4890
+		return $this->_primary_key_field;
4891
+	}
4892
+
4893
+
4894
+
4895
+	/**
4896
+	 * Returns whether or not not there is a primary key on this model.
4897
+	 * Internally does some caching.
4898
+	 *
4899
+	 * @return boolean
4900
+	 */
4901
+	public function has_primary_key_field()
4902
+	{
4903
+		if ($this->_has_primary_key_field === null) {
4904
+			try {
4905
+				$this->get_primary_key_field();
4906
+				$this->_has_primary_key_field = true;
4907
+			} catch (EE_Error $e) {
4908
+				$this->_has_primary_key_field = false;
4909
+			}
4910
+		}
4911
+		return $this->_has_primary_key_field;
4912
+	}
4913
+
4914
+
4915
+
4916
+	/**
4917
+	 * Finds the first field of type $field_class_name.
4918
+	 *
4919
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4920
+	 *                                 EE_Foreign_Key_Field, etc
4921
+	 * @return EE_Model_Field_Base or null if none is found
4922
+	 */
4923
+	public function get_a_field_of_type($field_class_name)
4924
+	{
4925
+		foreach ($this->field_settings() as $field) {
4926
+			if ($field instanceof $field_class_name) {
4927
+				return $field;
4928
+			}
4929
+		}
4930
+		return null;
4931
+	}
4932
+
4933
+
4934
+
4935
+	/**
4936
+	 * Gets a foreign key field pointing to model.
4937
+	 *
4938
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4939
+	 * @return EE_Foreign_Key_Field_Base
4940
+	 * @throws EE_Error
4941
+	 */
4942
+	public function get_foreign_key_to($model_name)
4943
+	{
4944
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4945
+			foreach ($this->field_settings() as $field) {
4946
+				if (
4947
+					$field instanceof EE_Foreign_Key_Field_Base
4948
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4949
+				) {
4950
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4951
+					break;
4952
+				}
4953
+			}
4954
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4955
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4956
+					'event_espresso'), $model_name, get_class($this)));
4957
+			}
4958
+		}
4959
+		return $this->_cache_foreign_key_to_fields[$model_name];
4960
+	}
4961
+
4962
+
4963
+
4964
+	/**
4965
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4966
+	 *
4967
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4968
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4969
+	 *                            Either one works
4970
+	 * @return string
4971
+	 */
4972
+	public function get_table_for_alias($table_alias)
4973
+	{
4974
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4975
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4976
+	}
4977
+
4978
+
4979
+
4980
+	/**
4981
+	 * Returns a flat array of all field son this model, instead of organizing them
4982
+	 * by table_alias as they are in the constructor.
4983
+	 *
4984
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4985
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4986
+	 */
4987
+	public function field_settings($include_db_only_fields = false)
4988
+	{
4989
+		if ($include_db_only_fields) {
4990
+			if ($this->_cached_fields === null) {
4991
+				$this->_cached_fields = array();
4992
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4993
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4994
+						$this->_cached_fields[$field_name] = $field_obj;
4995
+					}
4996
+				}
4997
+			}
4998
+			return $this->_cached_fields;
4999
+		}
5000
+		if ($this->_cached_fields_non_db_only === null) {
5001
+			$this->_cached_fields_non_db_only = array();
5002
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5003
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5004
+					/** @var $field_obj EE_Model_Field_Base */
5005
+					if (! $field_obj->is_db_only_field()) {
5006
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
5007
+					}
5008
+				}
5009
+			}
5010
+		}
5011
+		return $this->_cached_fields_non_db_only;
5012
+	}
5013
+
5014
+
5015
+
5016
+	/**
5017
+	 *        cycle though array of attendees and create objects out of each item
5018
+	 *
5019
+	 * @access        private
5020
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5021
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5022
+	 *                           numerically indexed)
5023
+	 * @throws EE_Error
5024
+	 */
5025
+	protected function _create_objects($rows = array())
5026
+	{
5027
+		$array_of_objects = array();
5028
+		if (empty($rows)) {
5029
+			return array();
5030
+		}
5031
+		$count_if_model_has_no_primary_key = 0;
5032
+		$has_primary_key = $this->has_primary_key_field();
5033
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5034
+		foreach ((array)$rows as $row) {
5035
+			if (empty($row)) {
5036
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5037
+				return array();
5038
+			}
5039
+			//check if we've already set this object in the results array,
5040
+			//in which case there's no need to process it further (again)
5041
+			if ($has_primary_key) {
5042
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5043
+					$row,
5044
+					$primary_key_field->get_qualified_column(),
5045
+					$primary_key_field->get_table_column()
5046
+				);
5047
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5048
+					continue;
5049
+				}
5050
+			}
5051
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5052
+			if (! $classInstance) {
5053
+				throw new EE_Error(
5054
+					sprintf(
5055
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5056
+						$this->get_this_model_name(),
5057
+						http_build_query($row)
5058
+					)
5059
+				);
5060
+			}
5061
+			//set the timezone on the instantiated objects
5062
+			$classInstance->set_timezone($this->_timezone);
5063
+			//make sure if there is any timezone setting present that we set the timezone for the object
5064
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5065
+			$array_of_objects[$key] = $classInstance;
5066
+			//also, for all the relations of type BelongsTo, see if we can cache
5067
+			//those related models
5068
+			//(we could do this for other relations too, but if there are conditions
5069
+			//that filtered out some fo the results, then we'd be caching an incomplete set
5070
+			//so it requires a little more thought than just caching them immediately...)
5071
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5072
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5073
+					//check if this model's INFO is present. If so, cache it on the model
5074
+					$other_model = $relation_obj->get_other_model();
5075
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5076
+					//if we managed to make a model object from the results, cache it on the main model object
5077
+					if ($other_model_obj_maybe) {
5078
+						//set timezone on these other model objects if they are present
5079
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5080
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5081
+					}
5082
+				}
5083
+			}
5084
+			//also, if this was a custom select query, let's see if there are any results for the custom select fields
5085
+			//and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5086
+			//the field in the CustomSelects object
5087
+			if ($this->_custom_selections instanceof CustomSelects) {
5088
+				$classInstance->setCustomSelectsValues(
5089
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5090
+				);
5091
+			}
5092
+		}
5093
+		return $array_of_objects;
5094
+	}
5095
+
5096
+
5097
+	/**
5098
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5099
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5100
+	 *
5101
+	 * @param array $db_results_row
5102
+	 * @return array
5103
+	 */
5104
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5105
+	{
5106
+		$results = array();
5107
+		if ($this->_custom_selections instanceof CustomSelects) {
5108
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5109
+				if (isset($db_results_row[$alias])) {
5110
+					$results[$alias] = $this->convertValueToDataType(
5111
+						$db_results_row[$alias],
5112
+						$this->_custom_selections->getDataTypeForAlias($alias)
5113
+					);
5114
+				}
5115
+			}
5116
+		}
5117
+		return $results;
5118
+	}
5119
+
5120
+
5121
+	/**
5122
+	 * This will set the value for the given alias
5123
+	 * @param string $value
5124
+	 * @param string $datatype (one of %d, %s, %f)
5125
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5126
+	 */
5127
+	protected function convertValueToDataType($value, $datatype)
5128
+	{
5129
+		switch ($datatype) {
5130
+			case '%f':
5131
+				return (float) $value;
5132
+			case '%d':
5133
+				return (int) $value;
5134
+			default:
5135
+				return (string) $value;
5136
+		}
5137
+	}
5138
+
5139
+
5140
+	/**
5141
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5142
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5143
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5144
+	 * object (as set in the model_field!).
5145
+	 *
5146
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5147
+	 */
5148
+	public function create_default_object()
5149
+	{
5150
+		$this_model_fields_and_values = array();
5151
+		//setup the row using default values;
5152
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5153
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5154
+		}
5155
+		$className = $this->_get_class_name();
5156
+		$classInstance = EE_Registry::instance()
5157
+									->load_class($className, array($this_model_fields_and_values), false, false);
5158
+		return $classInstance;
5159
+	}
5160
+
5161
+
5162
+
5163
+	/**
5164
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5165
+	 *                             or an stdClass where each property is the name of a column,
5166
+	 * @return EE_Base_Class
5167
+	 * @throws EE_Error
5168
+	 */
5169
+	public function instantiate_class_from_array_or_object($cols_n_values)
5170
+	{
5171
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5172
+			$cols_n_values = get_object_vars($cols_n_values);
5173
+		}
5174
+		$primary_key = null;
5175
+		//make sure the array only has keys that are fields/columns on this model
5176
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5177
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5178
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5179
+		}
5180
+		$className = $this->_get_class_name();
5181
+		//check we actually found results that we can use to build our model object
5182
+		//if not, return null
5183
+		if ($this->has_primary_key_field()) {
5184
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5185
+				return null;
5186
+			}
5187
+		} else if ($this->unique_indexes()) {
5188
+			$first_column = reset($this_model_fields_n_values);
5189
+			if (empty($first_column)) {
5190
+				return null;
5191
+			}
5192
+		}
5193
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5194
+		if ($primary_key) {
5195
+			$classInstance = $this->get_from_entity_map($primary_key);
5196
+			if (! $classInstance) {
5197
+				$classInstance = EE_Registry::instance()
5198
+											->load_class($className,
5199
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5200
+				// add this new object to the entity map
5201
+				$classInstance = $this->add_to_entity_map($classInstance);
5202
+			}
5203
+		} else {
5204
+			$classInstance = EE_Registry::instance()
5205
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5206
+											true, false);
5207
+		}
5208
+		return $classInstance;
5209
+	}
5210
+
5211
+
5212
+
5213
+	/**
5214
+	 * Gets the model object from the  entity map if it exists
5215
+	 *
5216
+	 * @param int|string $id the ID of the model object
5217
+	 * @return EE_Base_Class
5218
+	 */
5219
+	public function get_from_entity_map($id)
5220
+	{
5221
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5222
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5223
+	}
5224
+
5225
+
5226
+
5227
+	/**
5228
+	 * add_to_entity_map
5229
+	 * Adds the object to the model's entity mappings
5230
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5231
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5232
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5233
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5234
+	 *        then this method should be called immediately after the update query
5235
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5236
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5237
+	 *
5238
+	 * @param    EE_Base_Class $object
5239
+	 * @throws EE_Error
5240
+	 * @return \EE_Base_Class
5241
+	 */
5242
+	public function add_to_entity_map(EE_Base_Class $object)
5243
+	{
5244
+		$className = $this->_get_class_name();
5245
+		if (! $object instanceof $className) {
5246
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5247
+				is_object($object) ? get_class($object) : $object, $className));
5248
+		}
5249
+		/** @var $object EE_Base_Class */
5250
+		if (! $object->ID()) {
5251
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5252
+				"event_espresso"), get_class($this)));
5253
+		}
5254
+		// double check it's not already there
5255
+		$classInstance = $this->get_from_entity_map($object->ID());
5256
+		if ($classInstance) {
5257
+			return $classInstance;
5258
+		}
5259
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5260
+		return $object;
5261
+	}
5262
+
5263
+
5264
+
5265
+	/**
5266
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5267
+	 * if no identifier is provided, then the entire entity map is emptied
5268
+	 *
5269
+	 * @param int|string $id the ID of the model object
5270
+	 * @return boolean
5271
+	 */
5272
+	public function clear_entity_map($id = null)
5273
+	{
5274
+		if (empty($id)) {
5275
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5276
+			return true;
5277
+		}
5278
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5279
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5280
+			return true;
5281
+		}
5282
+		return false;
5283
+	}
5284
+
5285
+
5286
+
5287
+	/**
5288
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5289
+	 * Given an array where keys are column (or column alias) names and values,
5290
+	 * returns an array of their corresponding field names and database values
5291
+	 *
5292
+	 * @param array $cols_n_values
5293
+	 * @return array
5294
+	 */
5295
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5296
+	{
5297
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * _deduce_fields_n_values_from_cols_n_values
5304
+	 * Given an array where keys are column (or column alias) names and values,
5305
+	 * returns an array of their corresponding field names and database values
5306
+	 *
5307
+	 * @param string $cols_n_values
5308
+	 * @return array
5309
+	 */
5310
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5311
+	{
5312
+		$this_model_fields_n_values = array();
5313
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5314
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5315
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5316
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5317
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5318
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5319
+					if (! $field_obj->is_db_only_field()) {
5320
+						//prepare field as if its coming from db
5321
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5322
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5323
+					}
5324
+				}
5325
+			} else {
5326
+				//the table's rows existed. Use their values
5327
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5328
+					if (! $field_obj->is_db_only_field()) {
5329
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5330
+							$cols_n_values, $field_obj->get_qualified_column(),
5331
+							$field_obj->get_table_column()
5332
+						);
5333
+					}
5334
+				}
5335
+			}
5336
+		}
5337
+		return $this_model_fields_n_values;
5338
+	}
5339
+
5340
+
5341
+
5342
+	/**
5343
+	 * @param $cols_n_values
5344
+	 * @param $qualified_column
5345
+	 * @param $regular_column
5346
+	 * @return null
5347
+	 */
5348
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5349
+	{
5350
+		$value = null;
5351
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5352
+		//does the field on the model relate to this column retrieved from the db?
5353
+		//or is it a db-only field? (not relating to the model)
5354
+		if (isset($cols_n_values[$qualified_column])) {
5355
+			$value = $cols_n_values[$qualified_column];
5356
+		} elseif (isset($cols_n_values[$regular_column])) {
5357
+			$value = $cols_n_values[$regular_column];
5358
+		}
5359
+		return $value;
5360
+	}
5361
+
5362
+
5363
+
5364
+	/**
5365
+	 * refresh_entity_map_from_db
5366
+	 * Makes sure the model object in the entity map at $id assumes the values
5367
+	 * of the database (opposite of EE_base_Class::save())
5368
+	 *
5369
+	 * @param int|string $id
5370
+	 * @return EE_Base_Class
5371
+	 * @throws EE_Error
5372
+	 */
5373
+	public function refresh_entity_map_from_db($id)
5374
+	{
5375
+		$obj_in_map = $this->get_from_entity_map($id);
5376
+		if ($obj_in_map) {
5377
+			$wpdb_results = $this->_get_all_wpdb_results(
5378
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5379
+			);
5380
+			if ($wpdb_results && is_array($wpdb_results)) {
5381
+				$one_row = reset($wpdb_results);
5382
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5383
+					$obj_in_map->set_from_db($field_name, $db_value);
5384
+				}
5385
+				//clear the cache of related model objects
5386
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5387
+					$obj_in_map->clear_cache($relation_name, null, true);
5388
+				}
5389
+			}
5390
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5391
+			return $obj_in_map;
5392
+		}
5393
+		return $this->get_one_by_ID($id);
5394
+	}
5395
+
5396
+
5397
+
5398
+	/**
5399
+	 * refresh_entity_map_with
5400
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5401
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5402
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5403
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5404
+	 *
5405
+	 * @param int|string    $id
5406
+	 * @param EE_Base_Class $replacing_model_obj
5407
+	 * @return \EE_Base_Class
5408
+	 * @throws EE_Error
5409
+	 */
5410
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5411
+	{
5412
+		$obj_in_map = $this->get_from_entity_map($id);
5413
+		if ($obj_in_map) {
5414
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5415
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5416
+					$obj_in_map->set($field_name, $value);
5417
+				}
5418
+				//make the model object in the entity map's cache match the $replacing_model_obj
5419
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5420
+					$obj_in_map->clear_cache($relation_name, null, true);
5421
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5422
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5423
+					}
5424
+				}
5425
+			}
5426
+			return $obj_in_map;
5427
+		}
5428
+		$this->add_to_entity_map($replacing_model_obj);
5429
+		return $replacing_model_obj;
5430
+	}
5431
+
5432
+
5433
+
5434
+	/**
5435
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5436
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5437
+	 * require_once($this->_getClassName().".class.php");
5438
+	 *
5439
+	 * @return string
5440
+	 */
5441
+	private function _get_class_name()
5442
+	{
5443
+		return "EE_" . $this->get_this_model_name();
5444
+	}
5445
+
5446
+
5447
+
5448
+	/**
5449
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5450
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5451
+	 * it would be 'Events'.
5452
+	 *
5453
+	 * @param int $quantity
5454
+	 * @return string
5455
+	 */
5456
+	public function item_name($quantity = 1)
5457
+	{
5458
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5459
+	}
5460
+
5461
+
5462
+
5463
+	/**
5464
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5465
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5466
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5467
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5468
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5469
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5470
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5471
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5472
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5473
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5474
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5475
+	 *        return $previousReturnValue.$returnString;
5476
+	 * }
5477
+	 * require('EEM_Answer.model.php');
5478
+	 * $answer=EEM_Answer::instance();
5479
+	 * echo $answer->my_callback('monkeys',100);
5480
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5481
+	 *
5482
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5483
+	 * @param array  $args       array of original arguments passed to the function
5484
+	 * @throws EE_Error
5485
+	 * @return mixed whatever the plugin which calls add_filter decides
5486
+	 */
5487
+	public function __call($methodName, $args)
5488
+	{
5489
+		$className = get_class($this);
5490
+		$tagName = "FHEE__{$className}__{$methodName}";
5491
+		if (! has_filter($tagName)) {
5492
+			throw new EE_Error(
5493
+				sprintf(
5494
+					__('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 );',
5495
+						'event_espresso'),
5496
+					$methodName,
5497
+					$className,
5498
+					$tagName,
5499
+					'<br />'
5500
+				)
5501
+			);
5502
+		}
5503
+		return apply_filters($tagName, null, $this, $args);
5504
+	}
5505
+
5506
+
5507
+
5508
+	/**
5509
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5510
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5511
+	 *
5512
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5513
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5514
+	 *                                                       the object's class name
5515
+	 *                                                       or object's ID
5516
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5517
+	 *                                                       exists in the database. If it does not, we add it
5518
+	 * @throws EE_Error
5519
+	 * @return EE_Base_Class
5520
+	 */
5521
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5522
+	{
5523
+		$className = $this->_get_class_name();
5524
+		if ($base_class_obj_or_id instanceof $className) {
5525
+			$model_object = $base_class_obj_or_id;
5526
+		} else {
5527
+			$primary_key_field = $this->get_primary_key_field();
5528
+			if (
5529
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5530
+				&& (
5531
+					is_int($base_class_obj_or_id)
5532
+					|| is_string($base_class_obj_or_id)
5533
+				)
5534
+			) {
5535
+				// assume it's an ID.
5536
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5537
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5538
+			} else if (
5539
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5540
+				&& is_string($base_class_obj_or_id)
5541
+			) {
5542
+				// assume its a string representation of the object
5543
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5544
+			} else {
5545
+				throw new EE_Error(
5546
+					sprintf(
5547
+						__(
5548
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5549
+							'event_espresso'
5550
+						),
5551
+						$base_class_obj_or_id,
5552
+						$this->_get_class_name(),
5553
+						print_r($base_class_obj_or_id, true)
5554
+					)
5555
+				);
5556
+			}
5557
+		}
5558
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5559
+			$model_object->save();
5560
+		}
5561
+		return $model_object;
5562
+	}
5563
+
5564
+
5565
+
5566
+	/**
5567
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5568
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5569
+	 * returns it ID.
5570
+	 *
5571
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5572
+	 * @return int|string depending on the type of this model object's ID
5573
+	 * @throws EE_Error
5574
+	 */
5575
+	public function ensure_is_ID($base_class_obj_or_id)
5576
+	{
5577
+		$className = $this->_get_class_name();
5578
+		if ($base_class_obj_or_id instanceof $className) {
5579
+			/** @var $base_class_obj_or_id EE_Base_Class */
5580
+			$id = $base_class_obj_or_id->ID();
5581
+		} elseif (is_int($base_class_obj_or_id)) {
5582
+			//assume it's an ID
5583
+			$id = $base_class_obj_or_id;
5584
+		} elseif (is_string($base_class_obj_or_id)) {
5585
+			//assume its a string representation of the object
5586
+			$id = $base_class_obj_or_id;
5587
+		} else {
5588
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5589
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5590
+				print_r($base_class_obj_or_id, true)));
5591
+		}
5592
+		return $id;
5593
+	}
5594
+
5595
+
5596
+
5597
+	/**
5598
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5599
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5600
+	 * been sanitized and converted into the appropriate domain.
5601
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5602
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5603
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5604
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5605
+	 * $EVT = EEM_Event::instance(); $old_setting =
5606
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5607
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5608
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5609
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5610
+	 *
5611
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5612
+	 * @return void
5613
+	 */
5614
+	public function assume_values_already_prepared_by_model_object(
5615
+		$values_already_prepared = self::not_prepared_by_model_object
5616
+	) {
5617
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5618
+	}
5619
+
5620
+
5621
+
5622
+	/**
5623
+	 * Read comments for assume_values_already_prepared_by_model_object()
5624
+	 *
5625
+	 * @return int
5626
+	 */
5627
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5628
+	{
5629
+		return $this->_values_already_prepared_by_model_object;
5630
+	}
5631
+
5632
+
5633
+
5634
+	/**
5635
+	 * Gets all the indexes on this model
5636
+	 *
5637
+	 * @return EE_Index[]
5638
+	 */
5639
+	public function indexes()
5640
+	{
5641
+		return $this->_indexes;
5642
+	}
5643
+
5644
+
5645
+
5646
+	/**
5647
+	 * Gets all the Unique Indexes on this model
5648
+	 *
5649
+	 * @return EE_Unique_Index[]
5650
+	 */
5651
+	public function unique_indexes()
5652
+	{
5653
+		$unique_indexes = array();
5654
+		foreach ($this->_indexes as $name => $index) {
5655
+			if ($index instanceof EE_Unique_Index) {
5656
+				$unique_indexes [$name] = $index;
5657
+			}
5658
+		}
5659
+		return $unique_indexes;
5660
+	}
5661
+
5662
+
5663
+
5664
+	/**
5665
+	 * Gets all the fields which, when combined, make the primary key.
5666
+	 * This is usually just an array with 1 element (the primary key), but in cases
5667
+	 * where there is no primary key, it's a combination of fields as defined
5668
+	 * on a primary index
5669
+	 *
5670
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5671
+	 * @throws EE_Error
5672
+	 */
5673
+	public function get_combined_primary_key_fields()
5674
+	{
5675
+		foreach ($this->indexes() as $index) {
5676
+			if ($index instanceof EE_Primary_Key_Index) {
5677
+				return $index->fields();
5678
+			}
5679
+		}
5680
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5681
+	}
5682
+
5683
+
5684
+
5685
+	/**
5686
+	 * Used to build a primary key string (when the model has no primary key),
5687
+	 * which can be used a unique string to identify this model object.
5688
+	 *
5689
+	 * @param array $cols_n_values keys are field names, values are their values
5690
+	 * @return string
5691
+	 * @throws EE_Error
5692
+	 */
5693
+	public function get_index_primary_key_string($cols_n_values)
5694
+	{
5695
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5696
+			$this->get_combined_primary_key_fields());
5697
+		return http_build_query($cols_n_values_for_primary_key_index);
5698
+	}
5699
+
5700
+
5701
+
5702
+	/**
5703
+	 * Gets the field values from the primary key string
5704
+	 *
5705
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5706
+	 * @param string $index_primary_key_string
5707
+	 * @return null|array
5708
+	 * @throws EE_Error
5709
+	 */
5710
+	public function parse_index_primary_key_string($index_primary_key_string)
5711
+	{
5712
+		$key_fields = $this->get_combined_primary_key_fields();
5713
+		//check all of them are in the $id
5714
+		$key_vals_in_combined_pk = array();
5715
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5716
+		foreach ($key_fields as $key_field_name => $field_obj) {
5717
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5718
+				return null;
5719
+			}
5720
+		}
5721
+		return $key_vals_in_combined_pk;
5722
+	}
5723
+
5724
+
5725
+
5726
+	/**
5727
+	 * verifies that an array of key-value pairs for model fields has a key
5728
+	 * for each field comprising the primary key index
5729
+	 *
5730
+	 * @param array $key_vals
5731
+	 * @return boolean
5732
+	 * @throws EE_Error
5733
+	 */
5734
+	public function has_all_combined_primary_key_fields($key_vals)
5735
+	{
5736
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5737
+		foreach ($keys_it_should_have as $key) {
5738
+			if (! isset($key_vals[$key])) {
5739
+				return false;
5740
+			}
5741
+		}
5742
+		return true;
5743
+	}
5744
+
5745
+
5746
+
5747
+	/**
5748
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5749
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5750
+	 *
5751
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5752
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5753
+	 * @throws EE_Error
5754
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5755
+	 *                                                              indexed)
5756
+	 */
5757
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5758
+	{
5759
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5760
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5761
+		} elseif (is_array($model_object_or_attributes_array)) {
5762
+			$attributes_array = $model_object_or_attributes_array;
5763
+		} else {
5764
+			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",
5765
+				"event_espresso"), $model_object_or_attributes_array));
5766
+		}
5767
+		//even copies obviously won't have the same ID, so remove the primary key
5768
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5769
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5770
+			unset($attributes_array[$this->primary_key_name()]);
5771
+		}
5772
+		if (isset($query_params[0])) {
5773
+			$query_params[0] = array_merge($attributes_array, $query_params);
5774
+		} else {
5775
+			$query_params[0] = $attributes_array;
5776
+		}
5777
+		return $this->get_all($query_params);
5778
+	}
5779
+
5780
+
5781
+
5782
+	/**
5783
+	 * Gets the first copy we find. See get_all_copies for more details
5784
+	 *
5785
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5786
+	 * @param array $query_params
5787
+	 * @return EE_Base_Class
5788
+	 * @throws EE_Error
5789
+	 */
5790
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5791
+	{
5792
+		if (! is_array($query_params)) {
5793
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5794
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5795
+					gettype($query_params)), '4.6.0');
5796
+			$query_params = array();
5797
+		}
5798
+		$query_params['limit'] = 1;
5799
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5800
+		if (is_array($copies)) {
5801
+			return array_shift($copies);
5802
+		}
5803
+		return null;
5804
+	}
5805
+
5806
+
5807
+
5808
+	/**
5809
+	 * Updates the item with the specified id. Ignores default query parameters because
5810
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5811
+	 *
5812
+	 * @param array      $fields_n_values keys are field names, values are their new values
5813
+	 * @param int|string $id              the value of the primary key to update
5814
+	 * @return int number of rows updated
5815
+	 * @throws EE_Error
5816
+	 */
5817
+	public function update_by_ID($fields_n_values, $id)
5818
+	{
5819
+		$query_params = array(
5820
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5821
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5822
+		);
5823
+		return $this->update($fields_n_values, $query_params);
5824
+	}
5825
+
5826
+
5827
+
5828
+	/**
5829
+	 * Changes an operator which was supplied to the models into one usable in SQL
5830
+	 *
5831
+	 * @param string $operator_supplied
5832
+	 * @return string an operator which can be used in SQL
5833
+	 * @throws EE_Error
5834
+	 */
5835
+	private function _prepare_operator_for_sql($operator_supplied)
5836
+	{
5837
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5838
+			: null;
5839
+		if ($sql_operator) {
5840
+			return $sql_operator;
5841
+		}
5842
+		throw new EE_Error(
5843
+			sprintf(
5844
+				__(
5845
+					"The operator '%s' is not in the list of valid operators: %s",
5846
+					"event_espresso"
5847
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5848
+			)
5849
+		);
5850
+	}
5851
+
5852
+
5853
+
5854
+	/**
5855
+	 * Gets the valid operators
5856
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5857
+	 */
5858
+	public function valid_operators(){
5859
+		return $this->_valid_operators;
5860
+	}
5861
+
5862
+
5863
+
5864
+	/**
5865
+	 * Gets the between-style operators (take 2 arguments).
5866
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5867
+	 */
5868
+	public function valid_between_style_operators()
5869
+	{
5870
+		return array_intersect(
5871
+			$this->valid_operators(),
5872
+			$this->_between_style_operators
5873
+		);
5874
+	}
5875
+
5876
+	/**
5877
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5878
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5879
+	 */
5880
+	public function valid_like_style_operators()
5881
+	{
5882
+		return array_intersect(
5883
+			$this->valid_operators(),
5884
+			$this->_like_style_operators
5885
+		);
5886
+	}
5887
+
5888
+	/**
5889
+	 * Gets the "in"-style operators
5890
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5891
+	 */
5892
+	public function valid_in_style_operators()
5893
+	{
5894
+		return array_intersect(
5895
+			$this->valid_operators(),
5896
+			$this->_in_style_operators
5897
+		);
5898
+	}
5899
+
5900
+	/**
5901
+	 * Gets the "null"-style operators (accept no arguments)
5902
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5903
+	 */
5904
+	public function valid_null_style_operators()
5905
+	{
5906
+		return array_intersect(
5907
+			$this->valid_operators(),
5908
+			$this->_null_style_operators
5909
+		);
5910
+	}
5911
+
5912
+	/**
5913
+	 * Gets an array where keys are the primary keys and values are their 'names'
5914
+	 * (as determined by the model object's name() function, which is often overridden)
5915
+	 *
5916
+	 * @param array $query_params like get_all's
5917
+	 * @return string[]
5918
+	 * @throws EE_Error
5919
+	 */
5920
+	public function get_all_names($query_params = array())
5921
+	{
5922
+		$objs = $this->get_all($query_params);
5923
+		$names = array();
5924
+		foreach ($objs as $obj) {
5925
+			$names[$obj->ID()] = $obj->name();
5926
+		}
5927
+		return $names;
5928
+	}
5929
+
5930
+
5931
+
5932
+	/**
5933
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5934
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5935
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5936
+	 * array_keys() on $model_objects.
5937
+	 *
5938
+	 * @param \EE_Base_Class[] $model_objects
5939
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5940
+	 *                                               in the returned array
5941
+	 * @return array
5942
+	 * @throws EE_Error
5943
+	 */
5944
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5945
+	{
5946
+		if (! $this->has_primary_key_field()) {
5947
+			if (WP_DEBUG) {
5948
+				EE_Error::add_error(
5949
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5950
+					__FILE__,
5951
+					__FUNCTION__,
5952
+					__LINE__
5953
+				);
5954
+			}
5955
+		}
5956
+		$IDs = array();
5957
+		foreach ($model_objects as $model_object) {
5958
+			$id = $model_object->ID();
5959
+			if (! $id) {
5960
+				if ($filter_out_empty_ids) {
5961
+					continue;
5962
+				}
5963
+				if (WP_DEBUG) {
5964
+					EE_Error::add_error(
5965
+						__(
5966
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5967
+							'event_espresso'
5968
+						),
5969
+						__FILE__,
5970
+						__FUNCTION__,
5971
+						__LINE__
5972
+					);
5973
+				}
5974
+			}
5975
+			$IDs[] = $id;
5976
+		}
5977
+		return $IDs;
5978
+	}
5979
+
5980
+
5981
+
5982
+	/**
5983
+	 * Returns the string used in capabilities relating to this model. If there
5984
+	 * are no capabilities that relate to this model returns false
5985
+	 *
5986
+	 * @return string|false
5987
+	 */
5988
+	public function cap_slug()
5989
+	{
5990
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5991
+	}
5992
+
5993
+
5994
+
5995
+	/**
5996
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5997
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5998
+	 * only returns the cap restrictions array in that context (ie, the array
5999
+	 * at that key)
6000
+	 *
6001
+	 * @param string $context
6002
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6003
+	 * @throws EE_Error
6004
+	 */
6005
+	public function cap_restrictions($context = EEM_Base::caps_read)
6006
+	{
6007
+		EEM_Base::verify_is_valid_cap_context($context);
6008
+		//check if we ought to run the restriction generator first
6009
+		if (
6010
+			isset($this->_cap_restriction_generators[$context])
6011
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6012
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6013
+		) {
6014
+			$this->_cap_restrictions[$context] = array_merge(
6015
+				$this->_cap_restrictions[$context],
6016
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
6017
+			);
6018
+		}
6019
+		//and make sure we've finalized the construction of each restriction
6020
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6021
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6022
+				$where_conditions_obj->_finalize_construct($this);
6023
+			}
6024
+		}
6025
+		return $this->_cap_restrictions[$context];
6026
+	}
6027
+
6028
+
6029
+
6030
+	/**
6031
+	 * Indicating whether or not this model thinks its a wp core model
6032
+	 *
6033
+	 * @return boolean
6034
+	 */
6035
+	public function is_wp_core_model()
6036
+	{
6037
+		return $this->_wp_core_model;
6038
+	}
6039
+
6040
+
6041
+
6042
+	/**
6043
+	 * Gets all the caps that are missing which impose a restriction on
6044
+	 * queries made in this context
6045
+	 *
6046
+	 * @param string $context one of EEM_Base::caps_ constants
6047
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6048
+	 * @throws EE_Error
6049
+	 */
6050
+	public function caps_missing($context = EEM_Base::caps_read)
6051
+	{
6052
+		$missing_caps = array();
6053
+		$cap_restrictions = $this->cap_restrictions($context);
6054
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6055
+			if (! EE_Capabilities::instance()
6056
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6057
+			) {
6058
+				$missing_caps[$cap] = $restriction_if_no_cap;
6059
+			}
6060
+		}
6061
+		return $missing_caps;
6062
+	}
6063
+
6064
+
6065
+
6066
+	/**
6067
+	 * Gets the mapping from capability contexts to action strings used in capability names
6068
+	 *
6069
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6070
+	 * one of 'read', 'edit', or 'delete'
6071
+	 */
6072
+	public function cap_contexts_to_cap_action_map()
6073
+	{
6074
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6075
+			$this);
6076
+	}
6077
+
6078
+
6079
+
6080
+	/**
6081
+	 * Gets the action string for the specified capability context
6082
+	 *
6083
+	 * @param string $context
6084
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6085
+	 * @throws EE_Error
6086
+	 */
6087
+	public function cap_action_for_context($context)
6088
+	{
6089
+		$mapping = $this->cap_contexts_to_cap_action_map();
6090
+		if (isset($mapping[$context])) {
6091
+			return $mapping[$context];
6092
+		}
6093
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6094
+			return $action;
6095
+		}
6096
+		throw new EE_Error(
6097
+			sprintf(
6098
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6099
+				$context,
6100
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6101
+			)
6102
+		);
6103
+	}
6104
+
6105
+
6106
+
6107
+	/**
6108
+	 * Returns all the capability contexts which are valid when querying models
6109
+	 *
6110
+	 * @return array
6111
+	 */
6112
+	public static function valid_cap_contexts()
6113
+	{
6114
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6115
+			self::caps_read,
6116
+			self::caps_read_admin,
6117
+			self::caps_edit,
6118
+			self::caps_delete,
6119
+		));
6120
+	}
6121
+
6122
+
6123
+
6124
+	/**
6125
+	 * Returns all valid options for 'default_where_conditions'
6126
+	 *
6127
+	 * @return array
6128
+	 */
6129
+	public static function valid_default_where_conditions()
6130
+	{
6131
+		return array(
6132
+			EEM_Base::default_where_conditions_all,
6133
+			EEM_Base::default_where_conditions_this_only,
6134
+			EEM_Base::default_where_conditions_others_only,
6135
+			EEM_Base::default_where_conditions_minimum_all,
6136
+			EEM_Base::default_where_conditions_minimum_others,
6137
+			EEM_Base::default_where_conditions_none
6138
+		);
6139
+	}
6140
+
6141
+	// public static function default_where_conditions_full
6142
+	/**
6143
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6144
+	 *
6145
+	 * @param string $context
6146
+	 * @return bool
6147
+	 * @throws EE_Error
6148
+	 */
6149
+	static public function verify_is_valid_cap_context($context)
6150
+	{
6151
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6152
+		if (in_array($context, $valid_cap_contexts)) {
6153
+			return true;
6154
+		}
6155
+		throw new EE_Error(
6156
+			sprintf(
6157
+				__(
6158
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6159
+					'event_espresso'
6160
+				),
6161
+				$context,
6162
+				'EEM_Base',
6163
+				implode(',', $valid_cap_contexts)
6164
+			)
6165
+		);
6166
+	}
6167
+
6168
+
6169
+
6170
+	/**
6171
+	 * Clears all the models field caches. This is only useful when a sub-class
6172
+	 * might have added a field or something and these caches might be invalidated
6173
+	 */
6174
+	protected function _invalidate_field_caches()
6175
+	{
6176
+		$this->_cache_foreign_key_to_fields = array();
6177
+		$this->_cached_fields = null;
6178
+		$this->_cached_fields_non_db_only = null;
6179
+	}
6180
+
6181
+
6182
+
6183
+	/**
6184
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6185
+	 * (eg "and", "or", "not").
6186
+	 *
6187
+	 * @return array
6188
+	 */
6189
+	public function logic_query_param_keys()
6190
+	{
6191
+		return $this->_logic_query_param_keys;
6192
+	}
6193
+
6194
+
6195
+
6196
+	/**
6197
+	 * Determines whether or not the where query param array key is for a logic query param.
6198
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6199
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6200
+	 *
6201
+	 * @param $query_param_key
6202
+	 * @return bool
6203
+	 */
6204
+	public function is_logic_query_param_key($query_param_key)
6205
+	{
6206
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6207
+			if ($query_param_key === $logic_query_param_key
6208
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6209
+			) {
6210
+				return true;
6211
+			}
6212
+		}
6213
+		return false;
6214
+	}
6215 6215
 
6216 6216
 
6217 6217
 
Please login to merge, or discard this patch.
Spacing   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+            throw new EE_Error(
520 520
                 sprintf(
521 521
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522 522
                         'event_espresso'),
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
          *
537 537
          * @var EE_Table_Base[] $_tables
538 538
          */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
539
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
540 540
         foreach ($this->_tables as $table_alias => $table_obj) {
541 541
             /** @var $table_obj EE_Table_Base */
542 542
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -551,10 +551,10 @@  discard block
 block discarded – undo
551 551
          *
552 552
          * @param EE_Model_Field_Base[] $_fields
553 553
          */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
554
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
555 555
         $this->_invalidate_field_caches();
556 556
         foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
557
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
558 558
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559 559
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
560 560
             }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
          *
583 583
          * @param EE_Model_Relation_Base[] $_model_relations
584 584
          */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
585
+        $this->_model_relations = (array) apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
586 586
             $this->_model_relations);
587 587
         foreach ($this->_model_relations as $model_name => $relation_obj) {
588 588
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -594,12 +594,12 @@  discard block
 block discarded – undo
594 594
         }
595 595
         $this->set_timezone($timezone);
596 596
         //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
597
+        if ( ! $this->_default_where_conditions_strategy) {
598 598
             //nothing was set during child constructor, so set default
599 599
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600 600
         }
601 601
         $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
602
+        if ( ! $this->_minimum_where_conditions_strategy) {
603 603
             //nothing was set during child constructor, so set default
604 604
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605 605
         }
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
         //initialize the standard cap restriction generators if none were specified by the child constructor
613 613
         if ($this->_cap_restriction_generators !== false) {
614 614
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
615
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
616 616
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
617 617
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618 618
                         new EE_Restriction_Generator_Protected(),
@@ -625,10 +625,10 @@  discard block
 block discarded – undo
625 625
         //if there are cap restriction generators, use them to make the default cap restrictions
626 626
         if ($this->_cap_restriction_generators !== false) {
627 627
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
628
+                if ( ! $generator_object) {
629 629
                     continue;
630 630
                 }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
631
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
632 632
                     throw new EE_Error(
633 633
                         sprintf(
634 634
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
                     );
640 640
                 }
641 641
                 $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
642
+                if ( ! $generator_object->construction_finalized()) {
643 643
                     $generator_object->_construct_finalize($this, $action);
644 644
                 }
645 645
             }
646 646
         }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
647
+        do_action('AHEE__'.get_class($this).'__construct__end');
648 648
     }
649 649
 
650 650
 
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
      */
658 658
     public static function set_model_query_blog_id($blog_id = 0)
659 659
     {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
660
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
661 661
     }
662 662
 
663 663
 
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
     public static function instance($timezone = null)
692 692
     {
693 693
         // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
694
+        if ( ! static::$_instance instanceof static) {
695 695
             // instantiate Espresso_model
696 696
             static::$_instance = new static(
697 697
                 $timezone,
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
             foreach ($r->getDefaultProperties() as $property => $value) {
731 731
                 //don't set instance to null like it was originally,
732 732
                 //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
733
+                if ( ! isset($static_properties[$property])) {
734 734
                     static::$_instance->{$property} = $value;
735 735
                 }
736 736
             }
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
      */
755 755
     private static function getLoader()
756 756
     {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
757
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
758 758
             EEM_Base::$loader = LoaderFactory::getLoader();
759 759
         }
760 760
         return EEM_Base::$loader;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
      */
775 775
     public function status_array($translated = false)
776 776
     {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
777
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
778 778
             return array();
779 779
         }
780 780
         $model_name = $this->get_this_model_name();
@@ -977,17 +977,17 @@  discard block
 block discarded – undo
977 977
     public function wp_user_field_name()
978 978
     {
979 979
         try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
980
+            if ( ! empty($this->_model_chain_to_wp_user)) {
981 981
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982 982
                 $last_model_name = end($models_to_follow_to_wp_users);
983 983
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
984
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
985 985
             } else {
986 986
                 $model_with_fk_to_wp_users = $this;
987 987
                 $model_chain_to_wp_user = '';
988 988
             }
989 989
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
990
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
991 991
         } catch (EE_Error $e) {
992 992
             return false;
993 993
         }
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
      */
1056 1056
     protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057 1057
     {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1058
+        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select); ;
1059 1059
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060 1060
         $select_expressions = $columns_to_select === null
1061 1061
             ? $this->_construct_default_select_sql($model_query_info)
@@ -1063,11 +1063,11 @@  discard block
 block discarded – undo
1063 1063
         if ($this->_custom_selections instanceof CustomSelects) {
1064 1064
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065 1065
             $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1066
+                ? ', '.$custom_expressions
1067 1067
                 : $custom_expressions;
1068 1068
         }
1069 1069
 
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1070
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1071 1071
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072 1072
     }
1073 1073
 
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
      */
1085 1085
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086 1086
     {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1087
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088 1088
             return null;
1089 1089
         }
1090 1090
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
         if (is_array($columns_to_select)) {
1134 1134
             $select_sql_array = array();
1135 1135
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1136
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137 1137
                     throw new EE_Error(
1138 1138
                         sprintf(
1139 1139
                             __(
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
                         )
1146 1146
                     );
1147 1147
                 }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1148
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149 1149
                     throw new EE_Error(
1150 1150
                         sprintf(
1151 1151
                             esc_html__(
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
      */
1218 1218
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219 1219
     {
1220
-        if (! isset($query_params[0])) {
1220
+        if ( ! isset($query_params[0])) {
1221 1221
             $query_params[0] = array();
1222 1222
         }
1223 1223
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
      */
1243 1243
     public function get_one($query_params = array())
1244 1244
     {
1245
-        if (! is_array($query_params)) {
1245
+        if ( ! is_array($query_params)) {
1246 1246
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1247 1247
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248 1248
                     gettype($query_params)), '4.6.0');
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
                 return array();
1434 1434
             }
1435 1435
         }
1436
-        if (! is_array($query_params)) {
1436
+        if ( ! is_array($query_params)) {
1437 1437
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438 1438
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439 1439
                     gettype($query_params)), '4.6.0');
@@ -1443,7 +1443,7 @@  discard block
 block discarded – undo
1443 1443
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444 1444
         $query_params['limit'] = $limit;
1445 1445
         //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1446
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1447 1447
         $query_params['order_by'] = $operand === '>'
1448 1448
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449 1449
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
     {
1522 1522
         $field_settings = $this->field_settings_for($field_name);
1523 1523
         //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1524
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1525 1525
             throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1526 1526
                 'event_espresso'), $field_name));
1527 1527
         }
@@ -1600,7 +1600,7 @@  discard block
 block discarded – undo
1600 1600
         //load EEH_DTT_Helper
1601 1601
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602 1602
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1603
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1604 1604
     }
1605 1605
 
1606 1606
 
@@ -1668,7 +1668,7 @@  discard block
 block discarded – undo
1668 1668
      */
1669 1669
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1670 1670
     {
1671
-        if (! is_array($query_params)) {
1671
+        if ( ! is_array($query_params)) {
1672 1672
             EE_Error::doing_it_wrong('EEM_Base::update',
1673 1673
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1674 1674
                     gettype($query_params)), '4.6.0');
@@ -1690,7 +1690,7 @@  discard block
 block discarded – undo
1690 1690
          * @param EEM_Base $model           the model being queried
1691 1691
          * @param array    $query_params    see EEM_Base::get_all()
1692 1692
          */
1693
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1693
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1694 1694
             $query_params);
1695 1695
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1696 1696
         //to do that, for each table, verify that it's PK isn't null.
@@ -1704,7 +1704,7 @@  discard block
 block discarded – undo
1704 1704
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1705 1705
         foreach ($wpdb_select_results as $wpdb_result) {
1706 1706
             // type cast stdClass as array
1707
-            $wpdb_result = (array)$wpdb_result;
1707
+            $wpdb_result = (array) $wpdb_result;
1708 1708
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1709 1709
             if ($this->has_primary_key_field()) {
1710 1710
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1721,13 +1721,13 @@  discard block
 block discarded – undo
1721 1721
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1722 1722
                     //if there is no private key for this table on the results, it means there's no entry
1723 1723
                     //in this table, right? so insert a row in the current table, using any fields available
1724
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1724
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1725 1725
                            && $wpdb_result[$this_table_pk_column])
1726 1726
                     ) {
1727 1727
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1728 1728
                             $main_table_pk_value);
1729 1729
                         //if we died here, report the error
1730
-                        if (! $success) {
1730
+                        if ( ! $success) {
1731 1731
                             return false;
1732 1732
                         }
1733 1733
                     }
@@ -1758,7 +1758,7 @@  discard block
 block discarded – undo
1758 1758
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1759 1759
                 }
1760 1760
             }
1761
-            if (! $model_objs_affected_ids) {
1761
+            if ( ! $model_objs_affected_ids) {
1762 1762
                 //wait wait wait- if nothing was affected let's stop here
1763 1763
                 return 0;
1764 1764
             }
@@ -1785,7 +1785,7 @@  discard block
 block discarded – undo
1785 1785
                . $model_query_info->get_full_join_sql()
1786 1786
                . " SET "
1787 1787
                . $this->_construct_update_sql($fields_n_values)
1788
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1788
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1789 1789
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1790 1790
         /**
1791 1791
          * Action called after a model update call has been made.
@@ -1796,7 +1796,7 @@  discard block
 block discarded – undo
1796 1796
          * @param int      $rows_affected
1797 1797
          */
1798 1798
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1799
-        return $rows_affected;//how many supposedly got updated
1799
+        return $rows_affected; //how many supposedly got updated
1800 1800
     }
1801 1801
 
1802 1802
 
@@ -1824,7 +1824,7 @@  discard block
 block discarded – undo
1824 1824
         }
1825 1825
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1826 1826
         $select_expressions = $field->get_qualified_column();
1827
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1827
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1828 1828
         return $this->_do_wpdb_query('get_col', array($SQL));
1829 1829
     }
1830 1830
 
@@ -1842,7 +1842,7 @@  discard block
 block discarded – undo
1842 1842
     {
1843 1843
         $query_params['limit'] = 1;
1844 1844
         $col = $this->get_col($query_params, $field_to_select);
1845
-        if (! empty($col)) {
1845
+        if ( ! empty($col)) {
1846 1846
             return reset($col);
1847 1847
         }
1848 1848
         return null;
@@ -1873,7 +1873,7 @@  discard block
 block discarded – undo
1873 1873
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1874 1874
             $value_sql = $prepared_value === null ? 'NULL'
1875 1875
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1876
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1876
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1877 1877
         }
1878 1878
         return implode(",", $cols_n_values);
1879 1879
     }
@@ -2055,7 +2055,7 @@  discard block
 block discarded – undo
2055 2055
          * @param int      $rows_deleted
2056 2056
          */
2057 2057
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
-        return $rows_deleted;//how many supposedly got deleted
2058
+        return $rows_deleted; //how many supposedly got deleted
2059 2059
     }
2060 2060
 
2061 2061
 
@@ -2205,7 +2205,7 @@  discard block
 block discarded – undo
2205 2205
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2206 2206
                 //make sure we have unique $ids
2207 2207
                 $ids = array_unique($ids);
2208
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2208
+                $query[] = $column.' IN('.implode(',', $ids).')';
2209 2209
             }
2210 2210
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2211 2211
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2213,7 +2213,7 @@  discard block
 block discarded – undo
2213 2213
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2214 2214
                 $values_for_each_combined_primary_key_for_a_row = array();
2215 2215
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2216
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2216
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2217 2217
                 }
2218 2218
                 $ways_to_identify_a_row[] = '('
2219 2219
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2233,8 +2233,8 @@  discard block
 block discarded – undo
2233 2233
      */
2234 2234
     public function get_field_by_column($qualified_column_name)
2235 2235
     {
2236
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2237
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2236
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2237
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2238 2238
                return $field_obj;
2239 2239
            }
2240 2240
        }
@@ -2285,9 +2285,9 @@  discard block
 block discarded – undo
2285 2285
                 $column_to_count = '*';
2286 2286
             }
2287 2287
         }
2288
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2289
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2288
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2289
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2290
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2291 2291
     }
2292 2292
 
2293 2293
 
@@ -2309,14 +2309,14 @@  discard block
 block discarded – undo
2309 2309
             $field_obj = $this->get_primary_key_field();
2310 2310
         }
2311 2311
         $column_to_count = $field_obj->get_qualified_column();
2312
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2312
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2313 2313
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2314 2314
         $data_type = $field_obj->get_wpdb_data_type();
2315 2315
         if ($data_type === '%d' || $data_type === '%s') {
2316
-            return (float)$return_value;
2316
+            return (float) $return_value;
2317 2317
         }
2318 2318
         //must be %f
2319
-        return (float)$return_value;
2319
+        return (float) $return_value;
2320 2320
     }
2321 2321
 
2322 2322
 
@@ -2336,13 +2336,13 @@  discard block
 block discarded – undo
2336 2336
         //if we're in maintenance mode level 2, DON'T run any queries
2337 2337
         //because level 2 indicates the database needs updating and
2338 2338
         //is probably out of sync with the code
2339
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2339
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2340 2340
             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.",
2341 2341
                 "event_espresso")));
2342 2342
         }
2343 2343
         /** @type WPDB $wpdb */
2344 2344
         global $wpdb;
2345
-        if (! method_exists($wpdb, $wpdb_method)) {
2345
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2346 2346
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2347 2347
                 'event_espresso'), $wpdb_method));
2348 2348
         }
@@ -2354,7 +2354,7 @@  discard block
 block discarded – undo
2354 2354
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2355 2355
         if (WP_DEBUG) {
2356 2356
             $wpdb->show_errors($old_show_errors_value);
2357
-            if (! empty($wpdb->last_error)) {
2357
+            if ( ! empty($wpdb->last_error)) {
2358 2358
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2359 2359
             }
2360 2360
             if ($result === false) {
@@ -2415,7 +2415,7 @@  discard block
 block discarded – undo
2415 2415
                     return $result;
2416 2416
                     break;
2417 2417
             }
2418
-            if (! empty($error_message)) {
2418
+            if ( ! empty($error_message)) {
2419 2419
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2420 2420
                 trigger_error($error_message);
2421 2421
             }
@@ -2491,11 +2491,11 @@  discard block
 block discarded – undo
2491 2491
      */
2492 2492
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2493 2493
     {
2494
-        return " FROM " . $model_query_info->get_full_join_sql() .
2495
-               $model_query_info->get_where_sql() .
2496
-               $model_query_info->get_group_by_sql() .
2497
-               $model_query_info->get_having_sql() .
2498
-               $model_query_info->get_order_by_sql() .
2494
+        return " FROM ".$model_query_info->get_full_join_sql().
2495
+               $model_query_info->get_where_sql().
2496
+               $model_query_info->get_group_by_sql().
2497
+               $model_query_info->get_having_sql().
2498
+               $model_query_info->get_order_by_sql().
2499 2499
                $model_query_info->get_limit_sql();
2500 2500
     }
2501 2501
 
@@ -2691,12 +2691,12 @@  discard block
 block discarded – undo
2691 2691
         $related_model = $this->get_related_model_obj($model_name);
2692 2692
         //we're just going to use the query params on the related model's normal get_all query,
2693 2693
         //except add a condition to say to match the current mod
2694
-        if (! isset($query_params['default_where_conditions'])) {
2694
+        if ( ! isset($query_params['default_where_conditions'])) {
2695 2695
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696 2696
         }
2697 2697
         $this_model_name = $this->get_this_model_name();
2698 2698
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2699
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2700 2700
         return $related_model->count($query_params, $field_to_count, $distinct);
2701 2701
     }
2702 2702
 
@@ -2716,7 +2716,7 @@  discard block
 block discarded – undo
2716 2716
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2717 2717
     {
2718 2718
         $related_model = $this->get_related_model_obj($model_name);
2719
-        if (! is_array($query_params)) {
2719
+        if ( ! is_array($query_params)) {
2720 2720
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2721 2721
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2722 2722
                     gettype($query_params)), '4.6.0');
@@ -2724,12 +2724,12 @@  discard block
 block discarded – undo
2724 2724
         }
2725 2725
         //we're just going to use the query params on the related model's normal get_all query,
2726 2726
         //except add a condition to say to match the current mod
2727
-        if (! isset($query_params['default_where_conditions'])) {
2727
+        if ( ! isset($query_params['default_where_conditions'])) {
2728 2728
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729 2729
         }
2730 2730
         $this_model_name = $this->get_this_model_name();
2731 2731
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2732
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2733 2733
         return $related_model->sum($query_params, $field_to_sum);
2734 2734
     }
2735 2735
 
@@ -2782,7 +2782,7 @@  discard block
 block discarded – undo
2782 2782
                 $field_with_model_name = $field;
2783 2783
             }
2784 2784
         }
2785
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2785
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2786 2786
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2787 2787
                 $this->get_this_model_name()));
2788 2788
         }
@@ -2815,7 +2815,7 @@  discard block
 block discarded – undo
2815 2815
          * @param array    $fields_n_values keys are the fields and values are their new values
2816 2816
          * @param EEM_Base $model           the model used
2817 2817
          */
2818
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2818
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2819 2819
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2820 2820
             $main_table = $this->_get_main_table();
2821 2821
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2922,7 +2922,7 @@  discard block
 block discarded – undo
2922 2922
         }
2923 2923
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2924 2924
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2925
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2925
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2926 2926
         }
2927 2927
         //if there is nothing to base this search on, then we shouldn't find anything
2928 2928
         if (empty($query_params)) {
@@ -3008,7 +3008,7 @@  discard block
 block discarded – undo
3008 3008
             //its not the main table, so we should have already saved the main table's PK which we just inserted
3009 3009
             //so add the fk to the main table as a column
3010 3010
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3011
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3011
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
3012 3012
         }
3013 3013
         //insert the new entry
3014 3014
         $result = $this->_do_wpdb_query('insert',
@@ -3212,7 +3212,7 @@  discard block
 block discarded – undo
3212 3212
                     $query_info_carrier,
3213 3213
                     'group_by'
3214 3214
                 );
3215
-            } elseif (! empty ($query_params['group_by'])) {
3215
+            } elseif ( ! empty ($query_params['group_by'])) {
3216 3216
                 $this->_extract_related_model_info_from_query_param(
3217 3217
                     $query_params['group_by'],
3218 3218
                     $query_info_carrier,
@@ -3234,7 +3234,7 @@  discard block
 block discarded – undo
3234 3234
                     $query_info_carrier,
3235 3235
                     'order_by'
3236 3236
                 );
3237
-            } elseif (! empty($query_params['order_by'])) {
3237
+            } elseif ( ! empty($query_params['order_by'])) {
3238 3238
                 $this->_extract_related_model_info_from_query_param(
3239 3239
                     $query_params['order_by'],
3240 3240
                     $query_info_carrier,
@@ -3270,8 +3270,8 @@  discard block
 block discarded – undo
3270 3270
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3271 3271
         $query_param_type
3272 3272
     ) {
3273
-        if (! empty($sub_query_params)) {
3274
-            $sub_query_params = (array)$sub_query_params;
3273
+        if ( ! empty($sub_query_params)) {
3274
+            $sub_query_params = (array) $sub_query_params;
3275 3275
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3276 3276
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3277 3277
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3282,7 +3282,7 @@  discard block
 block discarded – undo
3282 3282
                 //of array('Registration.TXN_ID'=>23)
3283 3283
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284 3284
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3285
+                    if ( ! is_array($possibly_array_of_params)) {
3286 3286
                         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'))",
3287 3287
                             "event_espresso"),
3288 3288
                             $param, $possibly_array_of_params));
@@ -3299,7 +3299,7 @@  discard block
 block discarded – undo
3299 3299
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3300 3300
                     //indicating that $possible_array_of_params[1] is actually a field name,
3301 3301
                     //from which we should extract query parameters!
3302
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3302
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3303 3303
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3304 3304
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3305 3305
                     }
@@ -3329,8 +3329,8 @@  discard block
 block discarded – undo
3329 3329
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330 3330
         $query_param_type
3331 3331
     ) {
3332
-        if (! empty($sub_query_params)) {
3333
-            if (! is_array($sub_query_params)) {
3332
+        if ( ! empty($sub_query_params)) {
3333
+            if ( ! is_array($sub_query_params)) {
3334 3334
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3335 3335
                     $sub_query_params));
3336 3336
             }
@@ -3359,7 +3359,7 @@  discard block
 block discarded – undo
3359 3359
      */
3360 3360
     public function _create_model_query_info_carrier($query_params)
3361 3361
     {
3362
-        if (! is_array($query_params)) {
3362
+        if ( ! is_array($query_params)) {
3363 3363
             EE_Error::doing_it_wrong(
3364 3364
                 'EEM_Base::_create_model_query_info_carrier',
3365 3365
                 sprintf(
@@ -3435,7 +3435,7 @@  discard block
 block discarded – undo
3435 3435
         //set limit
3436 3436
         if (array_key_exists('limit', $query_params)) {
3437 3437
             if (is_array($query_params['limit'])) {
3438
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3438
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3439 3439
                     $e = sprintf(
3440 3440
                         __(
3441 3441
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3443,12 +3443,12 @@  discard block
 block discarded – undo
3443 3443
                         ),
3444 3444
                         http_build_query($query_params['limit'])
3445 3445
                     );
3446
-                    throw new EE_Error($e . "|" . $e);
3446
+                    throw new EE_Error($e."|".$e);
3447 3447
                 }
3448 3448
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3449
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3450
-            } elseif (! empty ($query_params['limit'])) {
3451
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3449
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3450
+            } elseif ( ! empty ($query_params['limit'])) {
3451
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3452 3452
             }
3453 3453
         }
3454 3454
         //set order by
@@ -3480,10 +3480,10 @@  discard block
 block discarded – undo
3480 3480
                 $order_array = array();
3481 3481
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3482 3482
                     $order = $this->_extract_order($order);
3483
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3483
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3484 3484
                 }
3485
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3486
-            } elseif (! empty ($query_params['order_by'])) {
3485
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3486
+            } elseif ( ! empty ($query_params['order_by'])) {
3487 3487
                 $this->_extract_related_model_info_from_query_param(
3488 3488
                     $query_params['order_by'],
3489 3489
                     $query_object,
@@ -3494,18 +3494,18 @@  discard block
 block discarded – undo
3494 3494
                     ? $this->_extract_order($query_params['order'])
3495 3495
                     : 'DESC';
3496 3496
                 $query_object->set_order_by_sql(
3497
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3497
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3498 3498
                 );
3499 3499
             }
3500 3500
         }
3501 3501
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3502
-        if (! array_key_exists('order_by', $query_params)
3502
+        if ( ! array_key_exists('order_by', $query_params)
3503 3503
             && array_key_exists('order', $query_params)
3504 3504
             && ! empty($query_params['order'])
3505 3505
         ) {
3506 3506
             $pk_field = $this->get_primary_key_field();
3507 3507
             $order = $this->_extract_order($query_params['order']);
3508
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3508
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3509 3509
         }
3510 3510
         //set group by
3511 3511
         if (array_key_exists('group_by', $query_params)) {
@@ -3515,10 +3515,10 @@  discard block
 block discarded – undo
3515 3515
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3516 3516
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3517 3517
                 }
3518
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3519
-            } elseif (! empty ($query_params['group_by'])) {
3518
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3519
+            } elseif ( ! empty ($query_params['group_by'])) {
3520 3520
                 $query_object->set_group_by_sql(
3521
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3521
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3522 3522
                 );
3523 3523
             }
3524 3524
         }
@@ -3528,7 +3528,7 @@  discard block
 block discarded – undo
3528 3528
         }
3529 3529
         //now, just verify they didn't pass anything wack
3530 3530
         foreach ($query_params as $query_key => $query_value) {
3531
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3531
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3532 3532
                 throw new EE_Error(
3533 3533
                     sprintf(
3534 3534
                         __(
@@ -3627,22 +3627,22 @@  discard block
 block discarded – undo
3627 3627
         $where_query_params = array()
3628 3628
     ) {
3629 3629
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3630
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3630
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3631 3631
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3632 3632
                 "event_espresso"), $use_default_where_conditions,
3633 3633
                 implode(", ", $allowed_used_default_where_conditions_values)));
3634 3634
         }
3635 3635
         $universal_query_params = array();
3636
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3636
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3637 3637
             $universal_query_params = $this->_get_default_where_conditions();
3638
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3638
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3639 3639
             $universal_query_params = $this->_get_minimum_where_conditions();
3640 3640
         }
3641 3641
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3642 3642
             $related_model = $this->get_related_model_obj($model_name);
3643
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3643
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3644 3644
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3645
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3645
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3646 3646
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3647 3647
             } else {
3648 3648
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3675,7 +3675,7 @@  discard block
 block discarded – undo
3675 3675
      * @param bool $for_this_model false means this is for OTHER related models
3676 3676
      * @return bool
3677 3677
      */
3678
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3678
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3679 3679
     {
3680 3680
         return (
3681 3681
                    $for_this_model
@@ -3754,7 +3754,7 @@  discard block
 block discarded – undo
3754 3754
     ) {
3755 3755
         $null_friendly_where_conditions = array();
3756 3756
         $none_overridden = true;
3757
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3757
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3758 3758
         foreach ($default_where_conditions as $key => $val) {
3759 3759
             if (isset($provided_where_conditions[$key])) {
3760 3760
                 $none_overridden = false;
@@ -3872,7 +3872,7 @@  discard block
 block discarded – undo
3872 3872
             foreach ($tables as $table_obj) {
3873 3873
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3874 3874
                                        . $table_obj->get_fully_qualified_pk_column();
3875
-                if (! in_array($qualified_pk_column, $selects)) {
3875
+                if ( ! in_array($qualified_pk_column, $selects)) {
3876 3876
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3877 3877
                 }
3878 3878
             }
@@ -4018,9 +4018,9 @@  discard block
 block discarded – undo
4018 4018
         $query_parameter_type
4019 4019
     ) {
4020 4020
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4021
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4021
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4022 4022
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4023
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4023
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4024 4024
                 if ($possible_join_string === '') {
4025 4025
                     //nothing left to $query_param
4026 4026
                     //we should actually end in a field name, not a model like this!
@@ -4147,7 +4147,7 @@  discard block
 block discarded – undo
4147 4147
     {
4148 4148
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4149 4149
         if ($SQL) {
4150
-            return " WHERE " . $SQL;
4150
+            return " WHERE ".$SQL;
4151 4151
         }
4152 4152
         return '';
4153 4153
     }
@@ -4166,7 +4166,7 @@  discard block
 block discarded – undo
4166 4166
     {
4167 4167
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4168 4168
         if ($SQL) {
4169
-            return " HAVING " . $SQL;
4169
+            return " HAVING ".$SQL;
4170 4170
         }
4171 4171
         return '';
4172 4172
     }
@@ -4185,7 +4185,7 @@  discard block
 block discarded – undo
4185 4185
     {
4186 4186
         $where_clauses = array();
4187 4187
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4188
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4188
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4189 4189
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4190 4190
                 switch ($query_param) {
4191 4191
                     case 'not':
@@ -4213,7 +4213,7 @@  discard block
 block discarded – undo
4213 4213
             } else {
4214 4214
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4215 4215
                 //if it's not a normal field, maybe it's a custom selection?
4216
-                if (! $field_obj) {
4216
+                if ( ! $field_obj) {
4217 4217
                     if ($this->_custom_selections instanceof CustomSelects) {
4218 4218
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4219 4219
                     } else {
@@ -4222,7 +4222,7 @@  discard block
 block discarded – undo
4222 4222
                     }
4223 4223
                 }
4224 4224
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4225
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4225
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4226 4226
             }
4227 4227
         }
4228 4228
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4243,7 +4243,7 @@  discard block
 block discarded – undo
4243 4243
         if ($field) {
4244 4244
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4245 4245
                 $query_param);
4246
-            return $table_alias_prefix . $field->get_qualified_column();
4246
+            return $table_alias_prefix.$field->get_qualified_column();
4247 4247
         }
4248 4248
         if ($this->_custom_selections instanceof CustomSelects
4249 4249
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4300,7 +4300,7 @@  discard block
 block discarded – undo
4300 4300
     {
4301 4301
         if (is_array($op_and_value)) {
4302 4302
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4303
-            if (! $operator) {
4303
+            if ( ! $operator) {
4304 4304
                 $php_array_like_string = array();
4305 4305
                 foreach ($op_and_value as $key => $value) {
4306 4306
                     $php_array_like_string[] = "$key=>$value";
@@ -4322,14 +4322,14 @@  discard block
 block discarded – undo
4322 4322
         }
4323 4323
         //check to see if the value is actually another field
4324 4324
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4325
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4325
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4326 4326
         }
4327 4327
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4328 4328
             //in this case, the value should be an array, or at least a comma-separated list
4329 4329
             //it will need to handle a little differently
4330 4330
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4331 4331
             //note: $cleaned_value has already been run through $wpdb->prepare()
4332
-            return $operator . SP . $cleaned_value;
4332
+            return $operator.SP.$cleaned_value;
4333 4333
         }
4334 4334
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4335 4335
             //the value should be an array with count of two.
@@ -4345,7 +4345,7 @@  discard block
 block discarded – undo
4345 4345
                 );
4346 4346
             }
4347 4347
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4348
-            return $operator . SP . $cleaned_value;
4348
+            return $operator.SP.$cleaned_value;
4349 4349
         }
4350 4350
         if (in_array($operator, $this->valid_null_style_operators())) {
4351 4351
             if ($value !== null) {
@@ -4365,10 +4365,10 @@  discard block
 block discarded – undo
4365 4365
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4366 4366
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4367 4367
             //remove other junk. So just treat it as a string.
4368
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4368
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4369 4369
         }
4370
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4371
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4370
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4371
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4372 4372
         }
4373 4373
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4374 4374
             throw new EE_Error(
@@ -4382,7 +4382,7 @@  discard block
 block discarded – undo
4382 4382
                 )
4383 4383
             );
4384 4384
         }
4385
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4385
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4386 4386
             throw new EE_Error(
4387 4387
                 sprintf(
4388 4388
                     __(
@@ -4422,7 +4422,7 @@  discard block
 block discarded – undo
4422 4422
         foreach ($values as $value) {
4423 4423
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4424 4424
         }
4425
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4425
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4426 4426
     }
4427 4427
 
4428 4428
 
@@ -4463,7 +4463,7 @@  discard block
 block discarded – undo
4463 4463
                                 . $main_table->get_table_name()
4464 4464
                                 . " WHERE FALSE";
4465 4465
         }
4466
-        return "(" . implode(",", $cleaned_values) . ")";
4466
+        return "(".implode(",", $cleaned_values).")";
4467 4467
     }
4468 4468
 
4469 4469
 
@@ -4482,7 +4482,7 @@  discard block
 block discarded – undo
4482 4482
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4483 4483
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4484 4484
         } //$field_obj should really just be a data type
4485
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4485
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4486 4486
             throw new EE_Error(
4487 4487
                 sprintf(
4488 4488
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4610,10 +4610,10 @@  discard block
 block discarded – undo
4610 4610
      */
4611 4611
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4612 4612
     {
4613
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4613
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4614 4614
         $qualified_columns = array();
4615 4615
         foreach ($this->field_settings() as $field_name => $field) {
4616
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4616
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4617 4617
         }
4618 4618
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4619 4619
     }
@@ -4637,11 +4637,11 @@  discard block
 block discarded – undo
4637 4637
             if ($table_obj instanceof EE_Primary_Table) {
4638 4638
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4639 4639
                     ? $table_obj->get_select_join_limit($limit)
4640
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4640
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4641 4641
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4642 4642
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4643 4643
                     ? $table_obj->get_select_join_limit_join($limit)
4644
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4644
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4645 4645
             }
4646 4646
         }
4647 4647
         return $SQL;
@@ -4729,12 +4729,12 @@  discard block
 block discarded – undo
4729 4729
      */
4730 4730
     public function get_related_model_obj($model_name)
4731 4731
     {
4732
-        $model_classname = "EEM_" . $model_name;
4733
-        if (! class_exists($model_classname)) {
4732
+        $model_classname = "EEM_".$model_name;
4733
+        if ( ! class_exists($model_classname)) {
4734 4734
             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",
4735 4735
                 'event_espresso'), $model_name, $model_classname));
4736 4736
         }
4737
-        return call_user_func($model_classname . "::instance");
4737
+        return call_user_func($model_classname."::instance");
4738 4738
     }
4739 4739
 
4740 4740
 
@@ -4781,7 +4781,7 @@  discard block
 block discarded – undo
4781 4781
     public function related_settings_for($relation_name)
4782 4782
     {
4783 4783
         $relatedModels = $this->relation_settings();
4784
-        if (! array_key_exists($relation_name, $relatedModels)) {
4784
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4785 4785
             throw new EE_Error(
4786 4786
                 sprintf(
4787 4787
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4809,7 +4809,7 @@  discard block
 block discarded – undo
4809 4809
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4810 4810
     {
4811 4811
         $fieldSettings = $this->field_settings($include_db_only_fields);
4812
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4812
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4813 4813
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4814 4814
                 get_class($this)));
4815 4815
         }
@@ -4882,7 +4882,7 @@  discard block
 block discarded – undo
4882 4882
                     break;
4883 4883
                 }
4884 4884
             }
4885
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4885
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4886 4886
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4887 4887
                     get_class($this)));
4888 4888
             }
@@ -4941,7 +4941,7 @@  discard block
 block discarded – undo
4941 4941
      */
4942 4942
     public function get_foreign_key_to($model_name)
4943 4943
     {
4944
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4944
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4945 4945
             foreach ($this->field_settings() as $field) {
4946 4946
                 if (
4947 4947
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4951,7 +4951,7 @@  discard block
 block discarded – undo
4951 4951
                     break;
4952 4952
                 }
4953 4953
             }
4954
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4954
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4955 4955
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4956 4956
                     'event_espresso'), $model_name, get_class($this)));
4957 4957
             }
@@ -5002,7 +5002,7 @@  discard block
 block discarded – undo
5002 5002
             foreach ($this->_fields as $fields_corresponding_to_table) {
5003 5003
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5004 5004
                     /** @var $field_obj EE_Model_Field_Base */
5005
-                    if (! $field_obj->is_db_only_field()) {
5005
+                    if ( ! $field_obj->is_db_only_field()) {
5006 5006
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5007 5007
                     }
5008 5008
                 }
@@ -5031,7 +5031,7 @@  discard block
 block discarded – undo
5031 5031
         $count_if_model_has_no_primary_key = 0;
5032 5032
         $has_primary_key = $this->has_primary_key_field();
5033 5033
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5034
-        foreach ((array)$rows as $row) {
5034
+        foreach ((array) $rows as $row) {
5035 5035
             if (empty($row)) {
5036 5036
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5037 5037
                 return array();
@@ -5049,7 +5049,7 @@  discard block
 block discarded – undo
5049 5049
                 }
5050 5050
             }
5051 5051
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5052
-            if (! $classInstance) {
5052
+            if ( ! $classInstance) {
5053 5053
                 throw new EE_Error(
5054 5054
                     sprintf(
5055 5055
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5168,7 +5168,7 @@  discard block
 block discarded – undo
5168 5168
      */
5169 5169
     public function instantiate_class_from_array_or_object($cols_n_values)
5170 5170
     {
5171
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5171
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5172 5172
             $cols_n_values = get_object_vars($cols_n_values);
5173 5173
         }
5174 5174
         $primary_key = null;
@@ -5193,7 +5193,7 @@  discard block
 block discarded – undo
5193 5193
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5194 5194
         if ($primary_key) {
5195 5195
             $classInstance = $this->get_from_entity_map($primary_key);
5196
-            if (! $classInstance) {
5196
+            if ( ! $classInstance) {
5197 5197
                 $classInstance = EE_Registry::instance()
5198 5198
                                             ->load_class($className,
5199 5199
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5242,12 +5242,12 @@  discard block
 block discarded – undo
5242 5242
     public function add_to_entity_map(EE_Base_Class $object)
5243 5243
     {
5244 5244
         $className = $this->_get_class_name();
5245
-        if (! $object instanceof $className) {
5245
+        if ( ! $object instanceof $className) {
5246 5246
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5247 5247
                 is_object($object) ? get_class($object) : $object, $className));
5248 5248
         }
5249 5249
         /** @var $object EE_Base_Class */
5250
-        if (! $object->ID()) {
5250
+        if ( ! $object->ID()) {
5251 5251
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5252 5252
                 "event_espresso"), get_class($this)));
5253 5253
         }
@@ -5316,7 +5316,7 @@  discard block
 block discarded – undo
5316 5316
             //there is a primary key on this table and its not set. Use defaults for all its columns
5317 5317
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5318 5318
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5319
-                    if (! $field_obj->is_db_only_field()) {
5319
+                    if ( ! $field_obj->is_db_only_field()) {
5320 5320
                         //prepare field as if its coming from db
5321 5321
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5322 5322
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5325,7 +5325,7 @@  discard block
 block discarded – undo
5325 5325
             } else {
5326 5326
                 //the table's rows existed. Use their values
5327 5327
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5328
-                    if (! $field_obj->is_db_only_field()) {
5328
+                    if ( ! $field_obj->is_db_only_field()) {
5329 5329
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5330 5330
                             $cols_n_values, $field_obj->get_qualified_column(),
5331 5331
                             $field_obj->get_table_column()
@@ -5440,7 +5440,7 @@  discard block
 block discarded – undo
5440 5440
      */
5441 5441
     private function _get_class_name()
5442 5442
     {
5443
-        return "EE_" . $this->get_this_model_name();
5443
+        return "EE_".$this->get_this_model_name();
5444 5444
     }
5445 5445
 
5446 5446
 
@@ -5455,7 +5455,7 @@  discard block
 block discarded – undo
5455 5455
      */
5456 5456
     public function item_name($quantity = 1)
5457 5457
     {
5458
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5458
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5459 5459
     }
5460 5460
 
5461 5461
 
@@ -5488,7 +5488,7 @@  discard block
 block discarded – undo
5488 5488
     {
5489 5489
         $className = get_class($this);
5490 5490
         $tagName = "FHEE__{$className}__{$methodName}";
5491
-        if (! has_filter($tagName)) {
5491
+        if ( ! has_filter($tagName)) {
5492 5492
             throw new EE_Error(
5493 5493
                 sprintf(
5494 5494
                     __('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 );',
@@ -5714,7 +5714,7 @@  discard block
 block discarded – undo
5714 5714
         $key_vals_in_combined_pk = array();
5715 5715
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5716 5716
         foreach ($key_fields as $key_field_name => $field_obj) {
5717
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5717
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5718 5718
                 return null;
5719 5719
             }
5720 5720
         }
@@ -5735,7 +5735,7 @@  discard block
 block discarded – undo
5735 5735
     {
5736 5736
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5737 5737
         foreach ($keys_it_should_have as $key) {
5738
-            if (! isset($key_vals[$key])) {
5738
+            if ( ! isset($key_vals[$key])) {
5739 5739
                 return false;
5740 5740
             }
5741 5741
         }
@@ -5789,7 +5789,7 @@  discard block
 block discarded – undo
5789 5789
      */
5790 5790
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5791 5791
     {
5792
-        if (! is_array($query_params)) {
5792
+        if ( ! is_array($query_params)) {
5793 5793
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5794 5794
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5795 5795
                     gettype($query_params)), '4.6.0');
@@ -5855,7 +5855,7 @@  discard block
 block discarded – undo
5855 5855
      * Gets the valid operators
5856 5856
      * @return array keys are accepted strings, values are the SQL they are converted to
5857 5857
      */
5858
-    public function valid_operators(){
5858
+    public function valid_operators() {
5859 5859
         return $this->_valid_operators;
5860 5860
     }
5861 5861
 
@@ -5943,7 +5943,7 @@  discard block
 block discarded – undo
5943 5943
      */
5944 5944
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5945 5945
     {
5946
-        if (! $this->has_primary_key_field()) {
5946
+        if ( ! $this->has_primary_key_field()) {
5947 5947
             if (WP_DEBUG) {
5948 5948
                 EE_Error::add_error(
5949 5949
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5956,7 +5956,7 @@  discard block
 block discarded – undo
5956 5956
         $IDs = array();
5957 5957
         foreach ($model_objects as $model_object) {
5958 5958
             $id = $model_object->ID();
5959
-            if (! $id) {
5959
+            if ( ! $id) {
5960 5960
                 if ($filter_out_empty_ids) {
5961 5961
                     continue;
5962 5962
                 }
@@ -6052,8 +6052,8 @@  discard block
 block discarded – undo
6052 6052
         $missing_caps = array();
6053 6053
         $cap_restrictions = $this->cap_restrictions($context);
6054 6054
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6055
-            if (! EE_Capabilities::instance()
6056
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6055
+            if ( ! EE_Capabilities::instance()
6056
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6057 6057
             ) {
6058 6058
                 $missing_caps[$cap] = $restriction_if_no_cap;
6059 6059
             }
@@ -6205,7 +6205,7 @@  discard block
 block discarded – undo
6205 6205
     {
6206 6206
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6207 6207
             if ($query_param_key === $logic_query_param_key
6208
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6208
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6209 6209
             ) {
6210 6210
                 return true;
6211 6211
             }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +2766 added lines, -2766 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2771 +25,2771 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
-     * access to it.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_timezone;
48
-
49
-
50
-
51
-    /**
52
-     * date format
53
-     * pattern or format for displaying dates
54
-     *
55
-     * @var string $_dt_frmt
56
-     */
57
-    protected $_dt_frmt;
58
-
59
-
60
-
61
-    /**
62
-     * time format
63
-     * pattern or format for displaying time
64
-     *
65
-     * @var string $_tm_frmt
66
-     */
67
-    protected $_tm_frmt;
68
-
69
-
70
-
71
-    /**
72
-     * This property is for holding a cached array of object properties indexed by property name as the key.
73
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
74
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
-     *
77
-     * @var array
78
-     */
79
-    protected $_cached_properties = array();
80
-
81
-    /**
82
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
83
-     * single
84
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
-     * all others have an array)
87
-     *
88
-     * @var array
89
-     */
90
-    protected $_model_relations = array();
91
-
92
-    /**
93
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_fields = array();
99
-
100
-    /**
101
-     * @var boolean indicating whether or not this model object is intended to ever be saved
102
-     * For example, we might create model objects intended to only be used for the duration
103
-     * of this request and to be thrown away, and if they were accidentally saved
104
-     * it would be a bug.
105
-     */
106
-    protected $_allow_persist = true;
107
-
108
-    /**
109
-     * @var boolean indicating whether or not this model object's properties have changed since construction
110
-     */
111
-    protected $_has_changes = false;
112
-
113
-    /**
114
-     * @var EEM_Base
115
-     */
116
-    protected $_model;
117
-
118
-
119
-    /**
120
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
121
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
122
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
123
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
124
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
125
-     * array as:
126
-     * array(
127
-     *  'Registration_Count' => 24
128
-     * );
129
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
130
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
131
-     * info)
132
-     *
133
-     * @var array
134
-     */
135
-    protected $custom_selection_results = array();
136
-
137
-
138
-
139
-    /**
140
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
141
-     * play nice
142
-     *
143
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
144
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
145
-     *                                                         TXN_amount, QST_name, etc) and values are their values
146
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
147
-     *                                                         corresponding db model or not.
148
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
149
-     *                                                         be in when instantiating a EE_Base_Class object.
150
-     * @param array   $date_formats                            An array of date formats to set on construct where first
151
-     *                                                         value is the date_format and second value is the time
152
-     *                                                         format.
153
-     * @throws EE_Error
154
-     */
155
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
156
-    {
157
-        $className = get_class($this);
158
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
159
-        $model = $this->get_model();
160
-        $model_fields = $model->field_settings(false);
161
-        // ensure $fieldValues is an array
162
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
163
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
164
-        // verify client code has not passed any invalid field names
165
-        foreach ($fieldValues as $field_name => $field_value) {
166
-            if ( ! isset($model_fields[$field_name])) {
167
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
168
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
169
-            }
170
-        }
171
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
172
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
173
-        if ( ! empty($date_formats) && is_array($date_formats)) {
174
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
175
-        } else {
176
-            //set default formats for date and time
177
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
178
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
179
-        }
180
-        //if db model is instantiating
181
-        if ($bydb) {
182
-            //client code has indicated these field values are from the database
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
185
-            }
186
-        } else {
187
-            //we're constructing a brand
188
-            //new instance of the model object. Generally, this means we'll need to do more field validation
189
-            foreach ($model_fields as $fieldName => $field) {
190
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
191
-            }
192
-        }
193
-        //remember what values were passed to this constructor
194
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
195
-        //remember in entity mapper
196
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
197
-            $model->add_to_entity_map($this);
198
-        }
199
-        //setup all the relations
200
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
201
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
202
-                $this->_model_relations[$relation_name] = null;
203
-            } else {
204
-                $this->_model_relations[$relation_name] = array();
205
-            }
206
-        }
207
-        /**
208
-         * Action done at the end of each model object construction
209
-         *
210
-         * @param EE_Base_Class $this the model object just created
211
-         */
212
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
213
-    }
214
-
215
-
216
-
217
-    /**
218
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
219
-     *
220
-     * @return boolean
221
-     */
222
-    public function allow_persist()
223
-    {
224
-        return $this->_allow_persist;
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * Sets whether or not this model object should be allowed to be saved to the DB.
231
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
232
-     * you got new information that somehow made you change your mind.
233
-     *
234
-     * @param boolean $allow_persist
235
-     * @return boolean
236
-     */
237
-    public function set_allow_persist($allow_persist)
238
-    {
239
-        return $this->_allow_persist = $allow_persist;
240
-    }
241
-
242
-
243
-
244
-    /**
245
-     * Gets the field's original value when this object was constructed during this request.
246
-     * This can be helpful when determining if a model object has changed or not
247
-     *
248
-     * @param string $field_name
249
-     * @return mixed|null
250
-     * @throws \EE_Error
251
-     */
252
-    public function get_original($field_name)
253
-    {
254
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258
-        } else {
259
-            return null;
260
-        }
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     * @param EE_Base_Class $obj
267
-     * @return string
268
-     */
269
-    public function get_class($obj)
270
-    {
271
-        return get_class($obj);
272
-    }
273
-
274
-
275
-
276
-    /**
277
-     * Overrides parent because parent expects old models.
278
-     * This also doesn't do any validation, and won't work for serialized arrays
279
-     *
280
-     * @param    string $field_name
281
-     * @param    mixed  $field_value
282
-     * @param bool      $use_default
283
-     * @throws \EE_Error
284
-     */
285
-    public function set($field_name, $field_value, $use_default = false)
286
-    {
287
-        // if not using default and nothing has changed, and object has already been setup (has ID),
288
-        // then don't do anything
289
-        if (
290
-            ! $use_default
291
-            && $this->_fields[$field_name] === $field_value
292
-            && $this->ID()
293
-        ) {
294
-            return;
295
-        }
296
-        $model = $this->get_model();
297
-        $this->_has_changes = true;
298
-        $field_obj = $model->field_settings_for($field_name);
299
-        if ($field_obj instanceof EE_Model_Field_Base) {
300
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
301
-            if ($field_obj instanceof EE_Datetime_Field) {
302
-                $field_obj->set_timezone($this->_timezone);
303
-                $field_obj->set_date_format($this->_dt_frmt);
304
-                $field_obj->set_time_format($this->_tm_frmt);
305
-            }
306
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
307
-            //should the value be null?
308
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
309
-                $this->_fields[$field_name] = $field_obj->get_default_value();
310
-                /**
311
-                 * To save having to refactor all the models, if a default value is used for a
312
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
313
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
314
-                 * object.
315
-                 *
316
-                 * @since 4.6.10+
317
-                 */
318
-                if (
319
-                    $field_obj instanceof EE_Datetime_Field
320
-                    && $this->_fields[$field_name] !== null
321
-                    && ! $this->_fields[$field_name] instanceof DateTime
322
-                ) {
323
-                    empty($this->_fields[$field_name])
324
-                        ? $this->set($field_name, time())
325
-                        : $this->set($field_name, $this->_fields[$field_name]);
326
-                }
327
-            } else {
328
-                $this->_fields[$field_name] = $holder_of_value;
329
-            }
330
-            //if we're not in the constructor...
331
-            //now check if what we set was a primary key
332
-            if (
333
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
334
-                $this->_props_n_values_provided_in_constructor
335
-                && $field_value
336
-                && $field_name === $model->primary_key_name()
337
-            ) {
338
-                //if so, we want all this object's fields to be filled either with
339
-                //what we've explicitly set on this model
340
-                //or what we have in the db
341
-                // echo "setting primary key!";
342
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
343
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
344
-                foreach ($fields_on_model as $field_obj) {
345
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
346
-                         && $field_obj->get_name() !== $field_name
347
-                    ) {
348
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
349
-                    }
350
-                }
351
-                //oh this model object has an ID? well make sure its in the entity mapper
352
-                $model->add_to_entity_map($this);
353
-            }
354
-            //let's unset any cache for this field_name from the $_cached_properties property.
355
-            $this->_clear_cached_property($field_name);
356
-        } else {
357
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
358
-                "event_espresso"), $field_name));
359
-        }
360
-    }
361
-
362
-
363
-    /**
364
-     * Set custom select values for model.
365
-     * @param array $custom_select_values
366
-     */
367
-    public function setCustomSelectsValues(array $custom_select_values)
368
-    {
369
-        $this->custom_selection_results = $custom_select_values;
370
-    }
371
-
372
-
373
-    /**
374
-     * Returns the custom select value for the provided alias if its set.
375
-     * If not set, returns null.
376
-     * @param string $alias
377
-     * @return string|int|float|null
378
-     */
379
-    public function getForCustomSelectAlias($alias)
380
-    {
381
-        return isset($this->custom_selection_results[$alias])
382
-            ? $this->custom_selection_results[$alias]
383
-            : null;
384
-    }
385
-
386
-
387
-
388
-    /**
389
-     * This sets the field value on the db column if it exists for the given $column_name or
390
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
391
-     *
392
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
393
-     * @param string $field_name  Must be the exact column name.
394
-     * @param mixed  $field_value The value to set.
395
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
396
-     * @throws \EE_Error
397
-     */
398
-    public function set_field_or_extra_meta($field_name, $field_value)
399
-    {
400
-        if ($this->get_model()->has_field($field_name)) {
401
-            $this->set($field_name, $field_value);
402
-            return true;
403
-        } else {
404
-            //ensure this object is saved first so that extra meta can be properly related.
405
-            $this->save();
406
-            return $this->update_extra_meta($field_name, $field_value);
407
-        }
408
-    }
409
-
410
-
411
-
412
-    /**
413
-     * This retrieves the value of the db column set on this class or if that's not present
414
-     * it will attempt to retrieve from extra_meta if found.
415
-     * Example Usage:
416
-     * Via EE_Message child class:
417
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
418
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
419
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
420
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
421
-     * value for those extra fields dynamically via the EE_message object.
422
-     *
423
-     * @param  string $field_name expecting the fully qualified field name.
424
-     * @return mixed|null  value for the field if found.  null if not found.
425
-     * @throws \EE_Error
426
-     */
427
-    public function get_field_or_extra_meta($field_name)
428
-    {
429
-        if ($this->get_model()->has_field($field_name)) {
430
-            $column_value = $this->get($field_name);
431
-        } else {
432
-            //This isn't a column in the main table, let's see if it is in the extra meta.
433
-            $column_value = $this->get_extra_meta($field_name, true, null);
434
-        }
435
-        return $column_value;
436
-    }
437
-
438
-
439
-
440
-    /**
441
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
442
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
443
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
444
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
445
-     *
446
-     * @access public
447
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
448
-     * @return void
449
-     * @throws \EE_Error
450
-     */
451
-    public function set_timezone($timezone = '')
452
-    {
453
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
454
-        //make sure we clear all cached properties because they won't be relevant now
455
-        $this->_clear_cached_properties();
456
-        //make sure we update field settings and the date for all EE_Datetime_Fields
457
-        $model_fields = $this->get_model()->field_settings(false);
458
-        foreach ($model_fields as $field_name => $field_obj) {
459
-            if ($field_obj instanceof EE_Datetime_Field) {
460
-                $field_obj->set_timezone($this->_timezone);
461
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
462
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
463
-                }
464
-            }
465
-        }
466
-    }
467
-
468
-
469
-
470
-    /**
471
-     * This just returns whatever is set for the current timezone.
472
-     *
473
-     * @access public
474
-     * @return string timezone string
475
-     */
476
-    public function get_timezone()
477
-    {
478
-        return $this->_timezone;
479
-    }
480
-
481
-
482
-
483
-    /**
484
-     * This sets the internal date format to what is sent in to be used as the new default for the class
485
-     * internally instead of wp set date format options
486
-     *
487
-     * @since 4.6
488
-     * @param string $format should be a format recognizable by PHP date() functions.
489
-     */
490
-    public function set_date_format($format)
491
-    {
492
-        $this->_dt_frmt = $format;
493
-        //clear cached_properties because they won't be relevant now.
494
-        $this->_clear_cached_properties();
495
-    }
496
-
497
-
498
-
499
-    /**
500
-     * This sets the internal time format string to what is sent in to be used as the new default for the
501
-     * class internally instead of wp set time format options.
502
-     *
503
-     * @since 4.6
504
-     * @param string $format should be a format recognizable by PHP date() functions.
505
-     */
506
-    public function set_time_format($format)
507
-    {
508
-        $this->_tm_frmt = $format;
509
-        //clear cached_properties because they won't be relevant now.
510
-        $this->_clear_cached_properties();
511
-    }
512
-
513
-
514
-
515
-    /**
516
-     * This returns the current internal set format for the date and time formats.
517
-     *
518
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
519
-     *                             where the first value is the date format and the second value is the time format.
520
-     * @return mixed string|array
521
-     */
522
-    public function get_format($full = true)
523
-    {
524
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
525
-    }
526
-
527
-
528
-
529
-    /**
530
-     * cache
531
-     * stores the passed model object on the current model object.
532
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
533
-     *
534
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
535
-     *                                       'Registration' associated with this model object
536
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
537
-     *                                       that could be a payment or a registration)
538
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
539
-     *                                       items which will be stored in an array on this object
540
-     * @throws EE_Error
541
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
542
-     *                  related thing, no array)
543
-     */
544
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
545
-    {
546
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
547
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
548
-            return false;
549
-        }
550
-        // also get "how" the object is related, or throw an error
551
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
552
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
553
-                $relationName, get_class($this)));
554
-        }
555
-        // how many things are related ?
556
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
557
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
558
-            // so for these model objects just set it to be cached
559
-            $this->_model_relations[$relationName] = $object_to_cache;
560
-            $return = true;
561
-        } else {
562
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
563
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
564
-            if ( ! is_array($this->_model_relations[$relationName])) {
565
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
566
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
567
-                    ? array($this->_model_relations[$relationName]) : array();
568
-            }
569
-            // first check for a cache_id which is normally empty
570
-            if ( ! empty($cache_id)) {
571
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
572
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
573
-                $return = $cache_id;
574
-            } elseif ($object_to_cache->ID()) {
575
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
576
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
577
-                $return = $object_to_cache->ID();
578
-            } else {
579
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
580
-                $this->_model_relations[$relationName][] = $object_to_cache;
581
-                // move the internal pointer to the end of the array
582
-                end($this->_model_relations[$relationName]);
583
-                // and grab the key so that we can return it
584
-                $return = key($this->_model_relations[$relationName]);
585
-            }
586
-        }
587
-        return $return;
588
-    }
589
-
590
-
591
-
592
-    /**
593
-     * For adding an item to the cached_properties property.
594
-     *
595
-     * @access protected
596
-     * @param string      $fieldname the property item the corresponding value is for.
597
-     * @param mixed       $value     The value we are caching.
598
-     * @param string|null $cache_type
599
-     * @return void
600
-     * @throws \EE_Error
601
-     */
602
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
603
-    {
604
-        //first make sure this property exists
605
-        $this->get_model()->field_settings_for($fieldname);
606
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
607
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
608
-    }
609
-
610
-
611
-
612
-    /**
613
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
614
-     * This also SETS the cache if we return the actual property!
615
-     *
616
-     * @param string $fieldname        the name of the property we're trying to retrieve
617
-     * @param bool   $pretty
618
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
619
-     *                                 (in cases where the same property may be used for different outputs
620
-     *                                 - i.e. datetime, money etc.)
621
-     *                                 It can also accept certain pre-defined "schema" strings
622
-     *                                 to define how to output the property.
623
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
624
-     * @return mixed                   whatever the value for the property is we're retrieving
625
-     * @throws \EE_Error
626
-     */
627
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
628
-    {
629
-        //verify the field exists
630
-        $model = $this->get_model();
631
-        $model->field_settings_for($fieldname);
632
-        $cache_type = $pretty ? 'pretty' : 'standard';
633
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
634
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
635
-            return $this->_cached_properties[$fieldname][$cache_type];
636
-        }
637
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
638
-        $this->_set_cached_property($fieldname, $value, $cache_type);
639
-        return $value;
640
-    }
641
-
642
-
643
-
644
-    /**
645
-     * If the cache didn't fetch the needed item, this fetches it.
646
-     * @param string $fieldname
647
-     * @param bool $pretty
648
-     * @param string $extra_cache_ref
649
-     * @return mixed
650
-     */
651
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
652
-    {
653
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
654
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
655
-        if ($field_obj instanceof EE_Datetime_Field) {
656
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
657
-        }
658
-        if ( ! isset($this->_fields[$fieldname])) {
659
-            $this->_fields[$fieldname] = null;
660
-        }
661
-        $value = $pretty
662
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
663
-            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
664
-        return $value;
665
-    }
666
-
667
-
668
-
669
-    /**
670
-     * set timezone, formats, and output for EE_Datetime_Field objects
671
-     *
672
-     * @param \EE_Datetime_Field $datetime_field
673
-     * @param bool               $pretty
674
-     * @param null $date_or_time
675
-     * @return void
676
-     * @throws \EE_Error
677
-     */
678
-    protected function _prepare_datetime_field(
679
-        EE_Datetime_Field $datetime_field,
680
-        $pretty = false,
681
-        $date_or_time = null
682
-    ) {
683
-        $datetime_field->set_timezone($this->_timezone);
684
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
685
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
686
-        //set the output returned
687
-        switch ($date_or_time) {
688
-            case 'D' :
689
-                $datetime_field->set_date_time_output('date');
690
-                break;
691
-            case 'T' :
692
-                $datetime_field->set_date_time_output('time');
693
-                break;
694
-            default :
695
-                $datetime_field->set_date_time_output();
696
-        }
697
-    }
698
-
699
-
700
-
701
-    /**
702
-     * This just takes care of clearing out the cached_properties
703
-     *
704
-     * @return void
705
-     */
706
-    protected function _clear_cached_properties()
707
-    {
708
-        $this->_cached_properties = array();
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     * This just clears out ONE property if it exists in the cache
715
-     *
716
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
717
-     * @return void
718
-     */
719
-    protected function _clear_cached_property($property_name)
720
-    {
721
-        if (isset($this->_cached_properties[$property_name])) {
722
-            unset($this->_cached_properties[$property_name]);
723
-        }
724
-    }
725
-
726
-
727
-
728
-    /**
729
-     * Ensures that this related thing is a model object.
730
-     *
731
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
732
-     * @param string $model_name   name of the related thing, eg 'Attendee',
733
-     * @return EE_Base_Class
734
-     * @throws \EE_Error
735
-     */
736
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
737
-    {
738
-        $other_model_instance = self::_get_model_instance_with_name(
739
-            self::_get_model_classname($model_name),
740
-            $this->_timezone
741
-        );
742
-        return $other_model_instance->ensure_is_obj($object_or_id);
743
-    }
744
-
745
-
746
-
747
-    /**
748
-     * Forgets the cached model of the given relation Name. So the next time we request it,
749
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
750
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
751
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
752
-     *
753
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
754
-     *                                                     Eg 'Registration'
755
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
756
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
757
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
758
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
759
-     *                                                     this is HasMany or HABTM.
760
-     * @throws EE_Error
761
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
762
-     *                       relation from all
763
-     */
764
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
765
-    {
766
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
767
-        $index_in_cache = '';
768
-        if ( ! $relationship_to_model) {
769
-            throw new EE_Error(
770
-                sprintf(
771
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
772
-                    $relationName,
773
-                    get_class($this)
774
-                )
775
-            );
776
-        }
777
-        if ($clear_all) {
778
-            $obj_removed = true;
779
-            $this->_model_relations[$relationName] = null;
780
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
781
-            $obj_removed = $this->_model_relations[$relationName];
782
-            $this->_model_relations[$relationName] = null;
783
-        } else {
784
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
785
-                && $object_to_remove_or_index_into_array->ID()
786
-            ) {
787
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
788
-                if (is_array($this->_model_relations[$relationName])
789
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
790
-                ) {
791
-                    $index_found_at = null;
792
-                    //find this object in the array even though it has a different key
793
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
794
-                        if (
795
-                            $obj instanceof EE_Base_Class
796
-                            && (
797
-                                $obj == $object_to_remove_or_index_into_array
798
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
799
-                            )
800
-                        ) {
801
-                            $index_found_at = $index;
802
-                            break;
803
-                        }
804
-                    }
805
-                    if ($index_found_at) {
806
-                        $index_in_cache = $index_found_at;
807
-                    } else {
808
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
809
-                        //if it wasn't in it to begin with. So we're done
810
-                        return $object_to_remove_or_index_into_array;
811
-                    }
812
-                }
813
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
814
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
815
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
816
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
817
-                        $index_in_cache = $index;
818
-                    }
819
-                }
820
-            } else {
821
-                $index_in_cache = $object_to_remove_or_index_into_array;
822
-            }
823
-            //supposedly we've found it. But it could just be that the client code
824
-            //provided a bad index/object
825
-            if (
826
-            isset(
827
-                $this->_model_relations[$relationName],
828
-                $this->_model_relations[$relationName][$index_in_cache]
829
-            )
830
-            ) {
831
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
832
-                unset($this->_model_relations[$relationName][$index_in_cache]);
833
-            } else {
834
-                //that thing was never cached anyways.
835
-                $obj_removed = null;
836
-            }
837
-        }
838
-        return $obj_removed;
839
-    }
840
-
841
-
842
-
843
-    /**
844
-     * update_cache_after_object_save
845
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
846
-     * obtained after being saved to the db
847
-     *
848
-     * @param string         $relationName       - the type of object that is cached
849
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
850
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
851
-     * @return boolean TRUE on success, FALSE on fail
852
-     * @throws \EE_Error
853
-     */
854
-    public function update_cache_after_object_save(
855
-        $relationName,
856
-        EE_Base_Class $newly_saved_object,
857
-        $current_cache_id = ''
858
-    ) {
859
-        // verify that incoming object is of the correct type
860
-        $obj_class = 'EE_' . $relationName;
861
-        if ($newly_saved_object instanceof $obj_class) {
862
-            /* @type EE_Base_Class $newly_saved_object */
863
-            // now get the type of relation
864
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
865
-            // if this is a 1:1 relationship
866
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
867
-                // then just replace the cached object with the newly saved object
868
-                $this->_model_relations[$relationName] = $newly_saved_object;
869
-                return true;
870
-                // or if it's some kind of sordid feral polyamorous relationship...
871
-            } elseif (is_array($this->_model_relations[$relationName])
872
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
873
-            ) {
874
-                // then remove the current cached item
875
-                unset($this->_model_relations[$relationName][$current_cache_id]);
876
-                // and cache the newly saved object using it's new ID
877
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
878
-                return true;
879
-            }
880
-        }
881
-        return false;
882
-    }
883
-
884
-
885
-
886
-    /**
887
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
888
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
889
-     *
890
-     * @param string $relationName
891
-     * @return EE_Base_Class
892
-     */
893
-    public function get_one_from_cache($relationName)
894
-    {
895
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
896
-            : null;
897
-        if (is_array($cached_array_or_object)) {
898
-            return array_shift($cached_array_or_object);
899
-        } else {
900
-            return $cached_array_or_object;
901
-        }
902
-    }
903
-
904
-
905
-
906
-    /**
907
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
908
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
909
-     *
910
-     * @param string $relationName
911
-     * @throws \EE_Error
912
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
913
-     */
914
-    public function get_all_from_cache($relationName)
915
-    {
916
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
917
-        // if the result is not an array, but exists, make it an array
918
-        $objects = is_array($objects) ? $objects : array($objects);
919
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
920
-        //basically, if this model object was stored in the session, and these cached model objects
921
-        //already have IDs, let's make sure they're in their model's entity mapper
922
-        //otherwise we will have duplicates next time we call
923
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
924
-        $model = EE_Registry::instance()->load_model($relationName);
925
-        foreach ($objects as $model_object) {
926
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
927
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
928
-                if ($model_object->ID()) {
929
-                    $model->add_to_entity_map($model_object);
930
-                }
931
-            } else {
932
-                throw new EE_Error(
933
-                    sprintf(
934
-                        __(
935
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
936
-                            'event_espresso'
937
-                        ),
938
-                        $relationName,
939
-                        gettype($model_object)
940
-                    )
941
-                );
942
-            }
943
-        }
944
-        return $objects;
945
-    }
946
-
947
-
948
-
949
-    /**
950
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
951
-     * matching the given query conditions.
952
-     *
953
-     * @param null  $field_to_order_by  What field is being used as the reference point.
954
-     * @param int   $limit              How many objects to return.
955
-     * @param array $query_params       Any additional conditions on the query.
956
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
957
-     *                                  you can indicate just the columns you want returned
958
-     * @return array|EE_Base_Class[]
959
-     * @throws \EE_Error
960
-     */
961
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
962
-    {
963
-        $model = $this->get_model();
964
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
965
-            ? $model->get_primary_key_field()->get_name()
966
-            : $field_to_order_by;
967
-        $current_value = ! empty($field) ? $this->get($field) : null;
968
-        if (empty($field) || empty($current_value)) {
969
-            return array();
970
-        }
971
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
972
-    }
973
-
974
-
975
-
976
-    /**
977
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
978
-     * matching the given query conditions.
979
-     *
980
-     * @param null  $field_to_order_by  What field is being used as the reference point.
981
-     * @param int   $limit              How many objects to return.
982
-     * @param array $query_params       Any additional conditions on the query.
983
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
984
-     *                                  you can indicate just the columns you want returned
985
-     * @return array|EE_Base_Class[]
986
-     * @throws \EE_Error
987
-     */
988
-    public function previous_x(
989
-        $field_to_order_by = null,
990
-        $limit = 1,
991
-        $query_params = array(),
992
-        $columns_to_select = null
993
-    ) {
994
-        $model = $this->get_model();
995
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
996
-            ? $model->get_primary_key_field()->get_name()
997
-            : $field_to_order_by;
998
-        $current_value = ! empty($field) ? $this->get($field) : null;
999
-        if (empty($field) || empty($current_value)) {
1000
-            return array();
1001
-        }
1002
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1003
-    }
1004
-
1005
-
1006
-
1007
-    /**
1008
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1009
-     * matching the given query conditions.
1010
-     *
1011
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1012
-     * @param array $query_params       Any additional conditions on the query.
1013
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1014
-     *                                  you can indicate just the columns you want returned
1015
-     * @return array|EE_Base_Class
1016
-     * @throws \EE_Error
1017
-     */
1018
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1019
-    {
1020
-        $model = $this->get_model();
1021
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1022
-            ? $model->get_primary_key_field()->get_name()
1023
-            : $field_to_order_by;
1024
-        $current_value = ! empty($field) ? $this->get($field) : null;
1025
-        if (empty($field) || empty($current_value)) {
1026
-            return array();
1027
-        }
1028
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1029
-    }
1030
-
1031
-
1032
-
1033
-    /**
1034
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1035
-     * matching the given query conditions.
1036
-     *
1037
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1038
-     * @param array $query_params       Any additional conditions on the query.
1039
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1040
-     *                                  you can indicate just the column you want returned
1041
-     * @return array|EE_Base_Class
1042
-     * @throws \EE_Error
1043
-     */
1044
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1045
-    {
1046
-        $model = $this->get_model();
1047
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1048
-            ? $model->get_primary_key_field()->get_name()
1049
-            : $field_to_order_by;
1050
-        $current_value = ! empty($field) ? $this->get($field) : null;
1051
-        if (empty($field) || empty($current_value)) {
1052
-            return array();
1053
-        }
1054
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1055
-    }
1056
-
1057
-
1058
-
1059
-    /**
1060
-     * Overrides parent because parent expects old models.
1061
-     * This also doesn't do any validation, and won't work for serialized arrays
1062
-     *
1063
-     * @param string $field_name
1064
-     * @param mixed  $field_value_from_db
1065
-     * @throws \EE_Error
1066
-     */
1067
-    public function set_from_db($field_name, $field_value_from_db)
1068
-    {
1069
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1070
-        if ($field_obj instanceof EE_Model_Field_Base) {
1071
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
1072
-            //eg, a CPT model object could have an entry in the posts table, but no
1073
-            //entry in the meta table. Meaning that all its columns in the meta table
1074
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
1075
-            if ($field_value_from_db === null) {
1076
-                if ($field_obj->is_nullable()) {
1077
-                    //if the field allows nulls, then let it be null
1078
-                    $field_value = null;
1079
-                } else {
1080
-                    $field_value = $field_obj->get_default_value();
1081
-                }
1082
-            } else {
1083
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1084
-            }
1085
-            $this->_fields[$field_name] = $field_value;
1086
-            $this->_clear_cached_property($field_name);
1087
-        }
1088
-    }
1089
-
1090
-
1091
-
1092
-    /**
1093
-     * verifies that the specified field is of the correct type
1094
-     *
1095
-     * @param string $field_name
1096
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1097
-     *                                (in cases where the same property may be used for different outputs
1098
-     *                                - i.e. datetime, money etc.)
1099
-     * @return mixed
1100
-     * @throws \EE_Error
1101
-     */
1102
-    public function get($field_name, $extra_cache_ref = null)
1103
-    {
1104
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1105
-    }
1106
-
1107
-
1108
-
1109
-    /**
1110
-     * This method simply returns the RAW unprocessed value for the given property in this class
1111
-     *
1112
-     * @param  string $field_name A valid fieldname
1113
-     * @return mixed              Whatever the raw value stored on the property is.
1114
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1115
-     */
1116
-    public function get_raw($field_name)
1117
-    {
1118
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1119
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1120
-            ? $this->_fields[$field_name]->format('U')
1121
-            : $this->_fields[$field_name];
1122
-    }
1123
-
1124
-
1125
-
1126
-    /**
1127
-     * This is used to return the internal DateTime object used for a field that is a
1128
-     * EE_Datetime_Field.
1129
-     *
1130
-     * @param string $field_name               The field name retrieving the DateTime object.
1131
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1132
-     * @throws \EE_Error
1133
-     *                                         an error is set and false returned.  If the field IS an
1134
-     *                                         EE_Datetime_Field and but the field value is null, then
1135
-     *                                         just null is returned (because that indicates that likely
1136
-     *                                         this field is nullable).
1137
-     */
1138
-    public function get_DateTime_object($field_name)
1139
-    {
1140
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1141
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1142
-            EE_Error::add_error(
1143
-                sprintf(
1144
-                    __(
1145
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1146
-                        'event_espresso'
1147
-                    ),
1148
-                    $field_name
1149
-                ),
1150
-                __FILE__,
1151
-                __FUNCTION__,
1152
-                __LINE__
1153
-            );
1154
-            return false;
1155
-        }
1156
-        return $this->_fields[$field_name];
1157
-    }
1158
-
1159
-
1160
-
1161
-    /**
1162
-     * To be used in template to immediately echo out the value, and format it for output.
1163
-     * Eg, should call stripslashes and whatnot before echoing
1164
-     *
1165
-     * @param string $field_name      the name of the field as it appears in the DB
1166
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
-     *                                (in cases where the same property may be used for different outputs
1168
-     *                                - i.e. datetime, money etc.)
1169
-     * @return void
1170
-     * @throws \EE_Error
1171
-     */
1172
-    public function e($field_name, $extra_cache_ref = null)
1173
-    {
1174
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1175
-    }
1176
-
1177
-
1178
-
1179
-    /**
1180
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1181
-     * can be easily used as the value of form input.
1182
-     *
1183
-     * @param string $field_name
1184
-     * @return void
1185
-     * @throws \EE_Error
1186
-     */
1187
-    public function f($field_name)
1188
-    {
1189
-        $this->e($field_name, 'form_input');
1190
-    }
1191
-
1192
-    /**
1193
-     * Same as `f()` but just returns the value instead of echoing it
1194
-     * @param string $field_name
1195
-     * @return string
1196
-     */
1197
-    public function get_f($field_name)
1198
-    {
1199
-        return (string)$this->get_pretty($field_name,'form_input');
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1206
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1207
-     * to see what options are available.
1208
-     * @param string $field_name
1209
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1210
-     *                                (in cases where the same property may be used for different outputs
1211
-     *                                - i.e. datetime, money etc.)
1212
-     * @return mixed
1213
-     * @throws \EE_Error
1214
-     */
1215
-    public function get_pretty($field_name, $extra_cache_ref = null)
1216
-    {
1217
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1218
-    }
1219
-
1220
-
1221
-
1222
-    /**
1223
-     * This simply returns the datetime for the given field name
1224
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1225
-     * (and the equivalent e_date, e_time, e_datetime).
1226
-     *
1227
-     * @access   protected
1228
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1229
-     * @param string   $dt_frmt      valid datetime format used for date
1230
-     *                               (if '' then we just use the default on the field,
1231
-     *                               if NULL we use the last-used format)
1232
-     * @param string   $tm_frmt      Same as above except this is for time format
1233
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1234
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1235
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1236
-     *                               if field is not a valid dtt field, or void if echoing
1237
-     * @throws \EE_Error
1238
-     */
1239
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1240
-    {
1241
-        // clear cached property
1242
-        $this->_clear_cached_property($field_name);
1243
-        //reset format properties because they are used in get()
1244
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1245
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1246
-        if ($echo) {
1247
-            $this->e($field_name, $date_or_time);
1248
-            return '';
1249
-        }
1250
-        return $this->get($field_name, $date_or_time);
1251
-    }
1252
-
1253
-
1254
-
1255
-    /**
1256
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1257
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1258
-     * other echoes the pretty value for dtt)
1259
-     *
1260
-     * @param  string $field_name name of model object datetime field holding the value
1261
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1262
-     * @return string            datetime value formatted
1263
-     * @throws \EE_Error
1264
-     */
1265
-    public function get_date($field_name, $format = '')
1266
-    {
1267
-        return $this->_get_datetime($field_name, $format, null, 'D');
1268
-    }
1269
-
1270
-
1271
-
1272
-    /**
1273
-     * @param      $field_name
1274
-     * @param string $format
1275
-     * @throws \EE_Error
1276
-     */
1277
-    public function e_date($field_name, $format = '')
1278
-    {
1279
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1280
-    }
1281
-
1282
-
1283
-
1284
-    /**
1285
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1286
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1287
-     * other echoes the pretty value for dtt)
1288
-     *
1289
-     * @param  string $field_name name of model object datetime field holding the value
1290
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1291
-     * @return string             datetime value formatted
1292
-     * @throws \EE_Error
1293
-     */
1294
-    public function get_time($field_name, $format = '')
1295
-    {
1296
-        return $this->_get_datetime($field_name, null, $format, 'T');
1297
-    }
1298
-
1299
-
1300
-
1301
-    /**
1302
-     * @param      $field_name
1303
-     * @param string $format
1304
-     * @throws \EE_Error
1305
-     */
1306
-    public function e_time($field_name, $format = '')
1307
-    {
1308
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1309
-    }
1310
-
1311
-
1312
-
1313
-    /**
1314
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1315
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1316
-     * other echoes the pretty value for dtt)
1317
-     *
1318
-     * @param  string $field_name name of model object datetime field holding the value
1319
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1320
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1321
-     * @return string             datetime value formatted
1322
-     * @throws \EE_Error
1323
-     */
1324
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1325
-    {
1326
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * @param string $field_name
1333
-     * @param string $dt_frmt
1334
-     * @param string $tm_frmt
1335
-     * @throws \EE_Error
1336
-     */
1337
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1338
-    {
1339
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1340
-    }
1341
-
1342
-
1343
-
1344
-    /**
1345
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1346
-     *
1347
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1348
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1349
-     *                           on the object will be used.
1350
-     * @return string Date and time string in set locale or false if no field exists for the given
1351
-     * @throws \EE_Error
1352
-     *                           field name.
1353
-     */
1354
-    public function get_i18n_datetime($field_name, $format = '')
1355
-    {
1356
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1357
-        return date_i18n(
1358
-            $format,
1359
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1360
-        );
1361
-    }
1362
-
1363
-
1364
-
1365
-    /**
1366
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1367
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1368
-     * thrown.
1369
-     *
1370
-     * @param  string $field_name The field name being checked
1371
-     * @throws EE_Error
1372
-     * @return EE_Datetime_Field
1373
-     */
1374
-    protected function _get_dtt_field_settings($field_name)
1375
-    {
1376
-        $field = $this->get_model()->field_settings_for($field_name);
1377
-        //check if field is dtt
1378
-        if ($field instanceof EE_Datetime_Field) {
1379
-            return $field;
1380
-        } else {
1381
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1382
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1383
-        }
1384
-    }
1385
-
1386
-
1387
-
1388
-
1389
-    /**
1390
-     * NOTE ABOUT BELOW:
1391
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1392
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1393
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1394
-     * method and make sure you send the entire datetime value for setting.
1395
-     */
1396
-    /**
1397
-     * sets the time on a datetime property
1398
-     *
1399
-     * @access protected
1400
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1401
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1402
-     * @throws \EE_Error
1403
-     */
1404
-    protected function _set_time_for($time, $fieldname)
1405
-    {
1406
-        $this->_set_date_time('T', $time, $fieldname);
1407
-    }
1408
-
1409
-
1410
-
1411
-    /**
1412
-     * sets the date on a datetime property
1413
-     *
1414
-     * @access protected
1415
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1416
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1417
-     * @throws \EE_Error
1418
-     */
1419
-    protected function _set_date_for($date, $fieldname)
1420
-    {
1421
-        $this->_set_date_time('D', $date, $fieldname);
1422
-    }
1423
-
1424
-
1425
-
1426
-    /**
1427
-     * This takes care of setting a date or time independently on a given model object property. This method also
1428
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1429
-     *
1430
-     * @access protected
1431
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1432
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1433
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1434
-     *                                        EE_Datetime_Field property)
1435
-     * @throws \EE_Error
1436
-     */
1437
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1438
-    {
1439
-        $field = $this->_get_dtt_field_settings($fieldname);
1440
-        $field->set_timezone($this->_timezone);
1441
-        $field->set_date_format($this->_dt_frmt);
1442
-        $field->set_time_format($this->_tm_frmt);
1443
-        switch ($what) {
1444
-            case 'T' :
1445
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1446
-                    $datetime_value,
1447
-                    $this->_fields[$fieldname]
1448
-                );
1449
-                break;
1450
-            case 'D' :
1451
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1452
-                    $datetime_value,
1453
-                    $this->_fields[$fieldname]
1454
-                );
1455
-                break;
1456
-            case 'B' :
1457
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1458
-                break;
1459
-        }
1460
-        $this->_clear_cached_property($fieldname);
1461
-    }
1462
-
1463
-
1464
-
1465
-    /**
1466
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1467
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1468
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1469
-     * that could lead to some unexpected results!
1470
-     *
1471
-     * @access public
1472
-     * @param string               $field_name This is the name of the field on the object that contains the date/time
1473
-     *                                         value being returned.
1474
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1475
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1476
-     * @param string               $prepend    You can include something to prepend on the timestamp
1477
-     * @param string               $append     You can include something to append on the timestamp
1478
-     * @throws EE_Error
1479
-     * @return string timestamp
1480
-     */
1481
-    public function display_in_my_timezone(
1482
-        $field_name,
1483
-        $callback = 'get_datetime',
1484
-        $args = null,
1485
-        $prepend = '',
1486
-        $append = ''
1487
-    ) {
1488
-        $timezone = EEH_DTT_Helper::get_timezone();
1489
-        if ($timezone === $this->_timezone) {
1490
-            return '';
1491
-        }
1492
-        $original_timezone = $this->_timezone;
1493
-        $this->set_timezone($timezone);
1494
-        $fn = (array)$field_name;
1495
-        $args = array_merge($fn, (array)$args);
1496
-        if ( ! method_exists($this, $callback)) {
1497
-            throw new EE_Error(
1498
-                sprintf(
1499
-                    __(
1500
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1501
-                        'event_espresso'
1502
-                    ),
1503
-                    $callback
1504
-                )
1505
-            );
1506
-        }
1507
-        $args = (array)$args;
1508
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1509
-        $this->set_timezone($original_timezone);
1510
-        return $return;
1511
-    }
1512
-
1513
-
1514
-
1515
-    /**
1516
-     * Deletes this model object.
1517
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1518
-     * override
1519
-     * `EE_Base_Class::_delete` NOT this class.
1520
-     *
1521
-     * @return boolean | int
1522
-     * @throws \EE_Error
1523
-     */
1524
-    public function delete()
1525
-    {
1526
-        /**
1527
-         * Called just before the `EE_Base_Class::_delete` method call.
1528
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1529
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1530
-         * soft deletes (trash) the object and does not permanently delete it.
1531
-         *
1532
-         * @param EE_Base_Class $model_object about to be 'deleted'
1533
-         */
1534
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1535
-        $result = $this->_delete();
1536
-        /**
1537
-         * Called just after the `EE_Base_Class::_delete` method call.
1538
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1539
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1540
-         * soft deletes (trash) the object and does not permanently delete it.
1541
-         *
1542
-         * @param EE_Base_Class $model_object that was just 'deleted'
1543
-         * @param boolean       $result
1544
-         */
1545
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1546
-        return $result;
1547
-    }
1548
-
1549
-
1550
-
1551
-    /**
1552
-     * Calls the specific delete method for the instantiated class.
1553
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1554
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1555
-     * `EE_Base_Class::delete`
1556
-     *
1557
-     * @return bool|int
1558
-     * @throws \EE_Error
1559
-     */
1560
-    protected function _delete()
1561
-    {
1562
-        return $this->delete_permanently();
1563
-    }
1564
-
1565
-
1566
-
1567
-    /**
1568
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1569
-     * error)
1570
-     *
1571
-     * @return bool | int
1572
-     * @throws \EE_Error
1573
-     */
1574
-    public function delete_permanently()
1575
-    {
1576
-        /**
1577
-         * Called just before HARD deleting a model object
1578
-         *
1579
-         * @param EE_Base_Class $model_object about to be 'deleted'
1580
-         */
1581
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1582
-        $model = $this->get_model();
1583
-        $result = $model->delete_permanently_by_ID($this->ID());
1584
-        $this->refresh_cache_of_related_objects();
1585
-        /**
1586
-         * Called just after HARD deleting a model object
1587
-         *
1588
-         * @param EE_Base_Class $model_object that was just 'deleted'
1589
-         * @param boolean       $result
1590
-         */
1591
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1592
-        return $result;
1593
-    }
1594
-
1595
-
1596
-
1597
-    /**
1598
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1599
-     * related model objects
1600
-     *
1601
-     * @throws \EE_Error
1602
-     */
1603
-    public function refresh_cache_of_related_objects()
1604
-    {
1605
-        $model = $this->get_model();
1606
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1607
-            if ( ! empty($this->_model_relations[$relation_name])) {
1608
-                $related_objects = $this->_model_relations[$relation_name];
1609
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1610
-                    //this relation only stores a single model object, not an array
1611
-                    //but let's make it consistent
1612
-                    $related_objects = array($related_objects);
1613
-                }
1614
-                foreach ($related_objects as $related_object) {
1615
-                    //only refresh their cache if they're in memory
1616
-                    if ($related_object instanceof EE_Base_Class) {
1617
-                        $related_object->clear_cache($model->get_this_model_name(), $this);
1618
-                    }
1619
-                }
1620
-            }
1621
-        }
1622
-    }
1623
-
1624
-
1625
-
1626
-    /**
1627
-     *        Saves this object to the database. An array may be supplied to set some values on this
1628
-     * object just before saving.
1629
-     *
1630
-     * @access public
1631
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1632
-     *                                 if provided during the save() method (often client code will change the fields'
1633
-     *                                 values before calling save)
1634
-     * @throws \EE_Error
1635
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1636
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1637
-     */
1638
-    public function save($set_cols_n_values = array())
1639
-    {
1640
-        $model = $this->get_model();
1641
-        /**
1642
-         * Filters the fields we're about to save on the model object
1643
-         *
1644
-         * @param array         $set_cols_n_values
1645
-         * @param EE_Base_Class $model_object
1646
-         */
1647
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1648
-            $this);
1649
-        //set attributes as provided in $set_cols_n_values
1650
-        foreach ($set_cols_n_values as $column => $value) {
1651
-            $this->set($column, $value);
1652
-        }
1653
-        // no changes ? then don't do anything
1654
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1655
-            return 0;
1656
-        }
1657
-        /**
1658
-         * Saving a model object.
1659
-         * Before we perform a save, this action is fired.
1660
-         *
1661
-         * @param EE_Base_Class $model_object the model object about to be saved.
1662
-         */
1663
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1664
-        if ( ! $this->allow_persist()) {
1665
-            return 0;
1666
-        }
1667
-        //now get current attribute values
1668
-        $save_cols_n_values = $this->_fields;
1669
-        //if the object already has an ID, update it. Otherwise, insert it
1670
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1671
-        $old_assumption_concerning_value_preparation = $model
1672
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1673
-        $model->assume_values_already_prepared_by_model_object(true);
1674
-        //does this model have an autoincrement PK?
1675
-        if ($model->has_primary_key_field()) {
1676
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1677
-                //ok check if it's set, if so: update; if not, insert
1678
-                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1679
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1680
-                } else {
1681
-                    unset($save_cols_n_values[$model->primary_key_name()]);
1682
-                    $results = $model->insert($save_cols_n_values);
1683
-                    if ($results) {
1684
-                        //if successful, set the primary key
1685
-                        //but don't use the normal SET method, because it will check if
1686
-                        //an item with the same ID exists in the mapper & db, then
1687
-                        //will find it in the db (because we just added it) and THAT object
1688
-                        //will get added to the mapper before we can add this one!
1689
-                        //but if we just avoid using the SET method, all that headache can be avoided
1690
-                        $pk_field_name = $model->primary_key_name();
1691
-                        $this->_fields[$pk_field_name] = $results;
1692
-                        $this->_clear_cached_property($pk_field_name);
1693
-                        $model->add_to_entity_map($this);
1694
-                        $this->_update_cached_related_model_objs_fks();
1695
-                    }
1696
-                }
1697
-            } else {//PK is NOT auto-increment
1698
-                //so check if one like it already exists in the db
1699
-                if ($model->exists_by_ID($this->ID())) {
1700
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1701
-                        throw new EE_Error(
1702
-                            sprintf(
1703
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1704
-                                    'event_espresso'),
1705
-                                get_class($this),
1706
-                                get_class($model) . '::instance()->add_to_entity_map()',
1707
-                                get_class($model) . '::instance()->get_one_by_ID()',
1708
-                                '<br />'
1709
-                            )
1710
-                        );
1711
-                    }
1712
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1713
-                } else {
1714
-                    $results = $model->insert($save_cols_n_values);
1715
-                    $this->_update_cached_related_model_objs_fks();
1716
-                }
1717
-            }
1718
-        } else {//there is NO primary key
1719
-            $already_in_db = false;
1720
-            foreach ($model->unique_indexes() as $index) {
1721
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1722
-                if ($model->exists(array($uniqueness_where_params))) {
1723
-                    $already_in_db = true;
1724
-                }
1725
-            }
1726
-            if ($already_in_db) {
1727
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1728
-                    $model->get_combined_primary_key_fields());
1729
-                $results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1730
-            } else {
1731
-                $results = $model->insert($save_cols_n_values);
1732
-            }
1733
-        }
1734
-        //restore the old assumption about values being prepared by the model object
1735
-        $model
1736
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1737
-        /**
1738
-         * After saving the model object this action is called
1739
-         *
1740
-         * @param EE_Base_Class $model_object which was just saved
1741
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1742
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1743
-         */
1744
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1745
-        $this->_has_changes = false;
1746
-        return $results;
1747
-    }
1748
-
1749
-
1750
-
1751
-    /**
1752
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1753
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1754
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1755
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1756
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1757
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1758
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1759
-     *
1760
-     * @return void
1761
-     * @throws \EE_Error
1762
-     */
1763
-    protected function _update_cached_related_model_objs_fks()
1764
-    {
1765
-        $model = $this->get_model();
1766
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1767
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1768
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1769
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1770
-                        $model->get_this_model_name()
1771
-                    );
1772
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1773
-                    if ($related_model_obj_in_cache->ID()) {
1774
-                        $related_model_obj_in_cache->save();
1775
-                    }
1776
-                }
1777
-            }
1778
-        }
1779
-    }
1780
-
1781
-
1782
-
1783
-    /**
1784
-     * Saves this model object and its NEW cached relations to the database.
1785
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1786
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1787
-     * because otherwise, there's a potential for infinite looping of saving
1788
-     * Saves the cached related model objects, and ensures the relation between them
1789
-     * and this object and properly setup
1790
-     *
1791
-     * @return int ID of new model object on save; 0 on failure+
1792
-     * @throws \EE_Error
1793
-     */
1794
-    public function save_new_cached_related_model_objs()
1795
-    {
1796
-        //make sure this has been saved
1797
-        if ( ! $this->ID()) {
1798
-            $id = $this->save();
1799
-        } else {
1800
-            $id = $this->ID();
1801
-        }
1802
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1803
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1804
-            if ($this->_model_relations[$relationName]) {
1805
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1806
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1807
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1808
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1809
-                    //but ONLY if it DOES NOT exist in the DB
1810
-                    /* @var $related_model_obj EE_Base_Class */
1811
-                    $related_model_obj = $this->_model_relations[$relationName];
1812
-                    //					if( ! $related_model_obj->ID()){
1813
-                    $this->_add_relation_to($related_model_obj, $relationName);
1814
-                    $related_model_obj->save_new_cached_related_model_objs();
1815
-                    //					}
1816
-                } else {
1817
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1818
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1819
-                        //but ONLY if it DOES NOT exist in the DB
1820
-                        //						if( ! $related_model_obj->ID()){
1821
-                        $this->_add_relation_to($related_model_obj, $relationName);
1822
-                        $related_model_obj->save_new_cached_related_model_objs();
1823
-                        //						}
1824
-                    }
1825
-                }
1826
-            }
1827
-        }
1828
-        return $id;
1829
-    }
1830
-
1831
-
1832
-
1833
-    /**
1834
-     * for getting a model while instantiated.
1835
-     *
1836
-     * @return \EEM_Base | \EEM_CPT_Base
1837
-     */
1838
-    public function get_model()
1839
-    {
1840
-        if( ! $this->_model){
1841
-            $modelName = self::_get_model_classname(get_class($this));
1842
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1843
-        } else {
1844
-            $this->_model->set_timezone($this->_timezone);
1845
-        }
1846
-
1847
-        return $this->_model;
1848
-    }
1849
-
1850
-
1851
-
1852
-    /**
1853
-     * @param $props_n_values
1854
-     * @param $classname
1855
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1856
-     * @throws \EE_Error
1857
-     */
1858
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1859
-    {
1860
-        //TODO: will not work for Term_Relationships because they have no PK!
1861
-        $primary_id_ref = self::_get_primary_key_name($classname);
1862
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1863
-            $id = $props_n_values[$primary_id_ref];
1864
-            return self::_get_model($classname)->get_from_entity_map($id);
1865
-        }
1866
-        return false;
1867
-    }
1868
-
1869
-
1870
-
1871
-    /**
1872
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1873
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1874
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1875
-     * we return false.
1876
-     *
1877
-     * @param  array  $props_n_values   incoming array of properties and their values
1878
-     * @param  string $classname        the classname of the child class
1879
-     * @param null    $timezone
1880
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1881
-     *                                  date_format and the second value is the time format
1882
-     * @return mixed (EE_Base_Class|bool)
1883
-     * @throws \EE_Error
1884
-     */
1885
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1886
-    {
1887
-        $existing = null;
1888
-        $model = self::_get_model($classname, $timezone);
1889
-        if ($model->has_primary_key_field()) {
1890
-            $primary_id_ref = self::_get_primary_key_name($classname);
1891
-            if (array_key_exists($primary_id_ref, $props_n_values)
1892
-                && ! empty($props_n_values[$primary_id_ref])
1893
-            ) {
1894
-                $existing = $model->get_one_by_ID(
1895
-                    $props_n_values[$primary_id_ref]
1896
-                );
1897
-            }
1898
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1899
-            //no primary key on this model, but there's still a matching item in the DB
1900
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1901
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1902
-            );
1903
-        }
1904
-        if ($existing) {
1905
-            //set date formats if present before setting values
1906
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1907
-                $existing->set_date_format($date_formats[0]);
1908
-                $existing->set_time_format($date_formats[1]);
1909
-            } else {
1910
-                //set default formats for date and time
1911
-                $existing->set_date_format(get_option('date_format'));
1912
-                $existing->set_time_format(get_option('time_format'));
1913
-            }
1914
-            foreach ($props_n_values as $property => $field_value) {
1915
-                $existing->set($property, $field_value);
1916
-            }
1917
-            return $existing;
1918
-        } else {
1919
-            return false;
1920
-        }
1921
-    }
1922
-
1923
-
1924
-
1925
-    /**
1926
-     * Gets the EEM_*_Model for this class
1927
-     *
1928
-     * @access public now, as this is more convenient
1929
-     * @param      $classname
1930
-     * @param null $timezone
1931
-     * @throws EE_Error
1932
-     * @return EEM_Base
1933
-     */
1934
-    protected static function _get_model($classname, $timezone = null)
1935
-    {
1936
-        //find model for this class
1937
-        if ( ! $classname) {
1938
-            throw new EE_Error(
1939
-                sprintf(
1940
-                    __(
1941
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1942
-                        "event_espresso"
1943
-                    ),
1944
-                    $classname
1945
-                )
1946
-            );
1947
-        }
1948
-        $modelName = self::_get_model_classname($classname);
1949
-        return self::_get_model_instance_with_name($modelName, $timezone);
1950
-    }
1951
-
1952
-
1953
-
1954
-    /**
1955
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1956
-     *
1957
-     * @param string $model_classname
1958
-     * @param null   $timezone
1959
-     * @return EEM_Base
1960
-     */
1961
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1962
-    {
1963
-        $model_classname = str_replace('EEM_', '', $model_classname);
1964
-        $model = EE_Registry::instance()->load_model($model_classname);
1965
-        $model->set_timezone($timezone);
1966
-        return $model;
1967
-    }
1968
-
1969
-
1970
-
1971
-    /**
1972
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1973
-     * Also works if a model class's classname is provided (eg EE_Registration).
1974
-     *
1975
-     * @param null $model_name
1976
-     * @return string like EEM_Attendee
1977
-     */
1978
-    private static function _get_model_classname($model_name = null)
1979
-    {
1980
-        if (strpos($model_name, "EE_") === 0) {
1981
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1982
-        } else {
1983
-            $model_classname = "EEM_" . $model_name;
1984
-        }
1985
-        return $model_classname;
1986
-    }
1987
-
1988
-
1989
-
1990
-    /**
1991
-     * returns the name of the primary key attribute
1992
-     *
1993
-     * @param null $classname
1994
-     * @throws EE_Error
1995
-     * @return string
1996
-     */
1997
-    protected static function _get_primary_key_name($classname = null)
1998
-    {
1999
-        if ( ! $classname) {
2000
-            throw new EE_Error(
2001
-                sprintf(
2002
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
2003
-                    $classname
2004
-                )
2005
-            );
2006
-        }
2007
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2008
-    }
2009
-
2010
-
2011
-
2012
-    /**
2013
-     * Gets the value of the primary key.
2014
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2015
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2016
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2017
-     *
2018
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2019
-     * @throws \EE_Error
2020
-     */
2021
-    public function ID()
2022
-    {
2023
-        $model = $this->get_model();
2024
-        //now that we know the name of the variable, use a variable variable to get its value and return its
2025
-        if ($model->has_primary_key_field()) {
2026
-            return $this->_fields[$model->primary_key_name()];
2027
-        } else {
2028
-            return $model->get_index_primary_key_string($this->_fields);
2029
-        }
2030
-    }
2031
-
2032
-
2033
-
2034
-    /**
2035
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2036
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2037
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2038
-     *
2039
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2040
-     * @param string $relationName                     eg 'Events','Question',etc.
2041
-     *                                                 an attendee to a group, you also want to specify which role they
2042
-     *                                                 will have in that group. So you would use this parameter to
2043
-     *                                                 specify array('role-column-name'=>'role-id')
2044
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2045
-     *                                                 allow you to further constrict the relation to being added.
2046
-     *                                                 However, keep in mind that the columns (keys) given must match a
2047
-     *                                                 column on the JOIN table and currently only the HABTM models
2048
-     *                                                 accept these additional conditions.  Also remember that if an
2049
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2050
-     *                                                 NEW row is created in the join table.
2051
-     * @param null   $cache_id
2052
-     * @throws EE_Error
2053
-     * @return EE_Base_Class the object the relation was added to
2054
-     */
2055
-    public function _add_relation_to(
2056
-        $otherObjectModelObjectOrID,
2057
-        $relationName,
2058
-        $extra_join_model_fields_n_values = array(),
2059
-        $cache_id = null
2060
-    ) {
2061
-        $model = $this->get_model();
2062
-        //if this thing exists in the DB, save the relation to the DB
2063
-        if ($this->ID()) {
2064
-            $otherObject = $model
2065
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2066
-                                    $extra_join_model_fields_n_values);
2067
-            //clear cache so future get_many_related and get_first_related() return new results.
2068
-            $this->clear_cache($relationName, $otherObject, true);
2069
-            if ($otherObject instanceof EE_Base_Class) {
2070
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2071
-            }
2072
-        } else {
2073
-            //this thing doesn't exist in the DB,  so just cache it
2074
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2075
-                throw new EE_Error(sprintf(
2076
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2077
-                        'event_espresso'),
2078
-                    $otherObjectModelObjectOrID,
2079
-                    get_class($this)
2080
-                ));
2081
-            } else {
2082
-                $otherObject = $otherObjectModelObjectOrID;
2083
-            }
2084
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2085
-        }
2086
-        if ($otherObject instanceof EE_Base_Class) {
2087
-            //fix the reciprocal relation too
2088
-            if ($otherObject->ID()) {
2089
-                //its saved so assumed relations exist in the DB, so we can just
2090
-                //clear the cache so future queries use the updated info in the DB
2091
-                $otherObject->clear_cache($model->get_this_model_name(), null, true);
2092
-            } else {
2093
-                //it's not saved, so it caches relations like this
2094
-                $otherObject->cache($model->get_this_model_name(), $this);
2095
-            }
2096
-        }
2097
-        return $otherObject;
2098
-    }
2099
-
2100
-
2101
-
2102
-    /**
2103
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2104
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2105
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2106
-     * from the cache
2107
-     *
2108
-     * @param mixed  $otherObjectModelObjectOrID
2109
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2110
-     *                to the DB yet
2111
-     * @param string $relationName
2112
-     * @param array  $where_query
2113
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2114
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2115
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2116
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2117
-     *                created in the join table.
2118
-     * @return EE_Base_Class the relation was removed from
2119
-     * @throws \EE_Error
2120
-     */
2121
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2122
-    {
2123
-        if ($this->ID()) {
2124
-            //if this exists in the DB, save the relation change to the DB too
2125
-            $otherObject = $this->get_model()
2126
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2127
-                                    $where_query);
2128
-            $this->clear_cache($relationName, $otherObject);
2129
-        } else {
2130
-            //this doesn't exist in the DB, just remove it from the cache
2131
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2132
-        }
2133
-        if ($otherObject instanceof EE_Base_Class) {
2134
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2135
-        }
2136
-        return $otherObject;
2137
-    }
2138
-
2139
-
2140
-
2141
-    /**
2142
-     * Removes ALL the related things for the $relationName.
2143
-     *
2144
-     * @param string $relationName
2145
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2146
-     * @return EE_Base_Class
2147
-     * @throws \EE_Error
2148
-     */
2149
-    public function _remove_relations($relationName, $where_query_params = array())
2150
-    {
2151
-        if ($this->ID()) {
2152
-            //if this exists in the DB, save the relation change to the DB too
2153
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2154
-            $this->clear_cache($relationName, null, true);
2155
-        } else {
2156
-            //this doesn't exist in the DB, just remove it from the cache
2157
-            $otherObjects = $this->clear_cache($relationName, null, true);
2158
-        }
2159
-        if (is_array($otherObjects)) {
2160
-            foreach ($otherObjects as $otherObject) {
2161
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2162
-            }
2163
-        }
2164
-        return $otherObjects;
2165
-    }
2166
-
2167
-
2168
-
2169
-    /**
2170
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2171
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2172
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2173
-     * because we want to get even deleted items etc.
2174
-     *
2175
-     * @param string $relationName key in the model's _model_relations array
2176
-     * @param array  $query_params like EEM_Base::get_all
2177
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2178
-     * @throws \EE_Error
2179
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2180
-     *                             you want IDs
2181
-     */
2182
-    public function get_many_related($relationName, $query_params = array())
2183
-    {
2184
-        if ($this->ID()) {
2185
-            //this exists in the DB, so get the related things from either the cache or the DB
2186
-            //if there are query parameters, forget about caching the related model objects.
2187
-            if ($query_params) {
2188
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2189
-            } else {
2190
-                //did we already cache the result of this query?
2191
-                $cached_results = $this->get_all_from_cache($relationName);
2192
-                if ( ! $cached_results) {
2193
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2194
-                    //if no query parameters were passed, then we got all the related model objects
2195
-                    //for that relation. We can cache them then.
2196
-                    foreach ($related_model_objects as $related_model_object) {
2197
-                        $this->cache($relationName, $related_model_object);
2198
-                    }
2199
-                } else {
2200
-                    $related_model_objects = $cached_results;
2201
-                }
2202
-            }
2203
-        } else {
2204
-            //this doesn't exist in the DB, so just get the related things from the cache
2205
-            $related_model_objects = $this->get_all_from_cache($relationName);
2206
-        }
2207
-        return $related_model_objects;
2208
-    }
2209
-
2210
-
2211
-
2212
-    /**
2213
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2214
-     * unless otherwise specified in the $query_params
2215
-     *
2216
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2217
-     * @param array  $query_params   like EEM_Base::get_all's
2218
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2219
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2220
-     *                               that by the setting $distinct to TRUE;
2221
-     * @return int
2222
-     */
2223
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2224
-    {
2225
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2226
-    }
2227
-
2228
-
2229
-
2230
-    /**
2231
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2232
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2233
-     *
2234
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2235
-     * @param array  $query_params  like EEM_Base::get_all's
2236
-     * @param string $field_to_sum  name of field to count by.
2237
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2238
-     *                              change it)
2239
-     * @return int
2240
-     */
2241
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2242
-    {
2243
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * Gets the first (ie, one) related model object of the specified type.
2250
-     *
2251
-     * @param string $relationName key in the model's _model_relations array
2252
-     * @param array  $query_params like EEM_Base::get_all
2253
-     * @return EE_Base_Class (not an array, a single object)
2254
-     * @throws \EE_Error
2255
-     */
2256
-    public function get_first_related($relationName, $query_params = array())
2257
-    {
2258
-        $model = $this->get_model();
2259
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2260
-            //if they've provided some query parameters, don't bother trying to cache the result
2261
-            //also make sure we're not caching the result of get_first_related
2262
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2263
-            if ($query_params
2264
-                || ! $model->related_settings_for($relationName)
2265
-                     instanceof
2266
-                     EE_Belongs_To_Relation
2267
-            ) {
2268
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2269
-            } else {
2270
-                //first, check if we've already cached the result of this query
2271
-                $cached_result = $this->get_one_from_cache($relationName);
2272
-                if ( ! $cached_result) {
2273
-                    $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2274
-                    $this->cache($relationName, $related_model_object);
2275
-                } else {
2276
-                    $related_model_object = $cached_result;
2277
-                }
2278
-            }
2279
-        } else {
2280
-            $related_model_object = null;
2281
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2282
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2283
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2284
-            }
2285
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2286
-            if ( ! $related_model_object) {
2287
-                $related_model_object = $this->get_one_from_cache($relationName);
2288
-            }
2289
-        }
2290
-        return $related_model_object;
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Does a delete on all related objects of type $relationName and removes
2297
-     * the current model object's relation to them. If they can't be deleted (because
2298
-     * of blocking related model objects) does nothing. If the related model objects are
2299
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2300
-     * If this model object doesn't exist yet in the DB, just removes its related things
2301
-     *
2302
-     * @param string $relationName
2303
-     * @param array  $query_params like EEM_Base::get_all's
2304
-     * @return int how many deleted
2305
-     * @throws \EE_Error
2306
-     */
2307
-    public function delete_related($relationName, $query_params = array())
2308
-    {
2309
-        if ($this->ID()) {
2310
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2311
-        } else {
2312
-            $count = count($this->get_all_from_cache($relationName));
2313
-            $this->clear_cache($relationName, null, true);
2314
-        }
2315
-        return $count;
2316
-    }
2317
-
2318
-
2319
-
2320
-    /**
2321
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2322
-     * the current model object's relation to them. If they can't be deleted (because
2323
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2324
-     * If the related thing isn't a soft-deletable model object, this function is identical
2325
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2326
-     *
2327
-     * @param string $relationName
2328
-     * @param array  $query_params like EEM_Base::get_all's
2329
-     * @return int how many deleted (including those soft deleted)
2330
-     * @throws \EE_Error
2331
-     */
2332
-    public function delete_related_permanently($relationName, $query_params = array())
2333
-    {
2334
-        if ($this->ID()) {
2335
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2336
-        } else {
2337
-            $count = count($this->get_all_from_cache($relationName));
2338
-        }
2339
-        $this->clear_cache($relationName, null, true);
2340
-        return $count;
2341
-    }
2342
-
2343
-
2344
-
2345
-    /**
2346
-     * is_set
2347
-     * Just a simple utility function children can use for checking if property exists
2348
-     *
2349
-     * @access  public
2350
-     * @param  string $field_name property to check
2351
-     * @return bool                              TRUE if existing,FALSE if not.
2352
-     */
2353
-    public function is_set($field_name)
2354
-    {
2355
-        return isset($this->_fields[$field_name]);
2356
-    }
2357
-
2358
-
2359
-
2360
-    /**
2361
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2362
-     * EE_Error exception if they don't
2363
-     *
2364
-     * @param  mixed (string|array) $properties properties to check
2365
-     * @throws EE_Error
2366
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2367
-     */
2368
-    protected function _property_exists($properties)
2369
-    {
2370
-        foreach ((array)$properties as $property_name) {
2371
-            //first make sure this property exists
2372
-            if ( ! $this->_fields[$property_name]) {
2373
-                throw new EE_Error(
2374
-                    sprintf(
2375
-                        __(
2376
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2377
-                            'event_espresso'
2378
-                        ),
2379
-                        $property_name
2380
-                    )
2381
-                );
2382
-            }
2383
-        }
2384
-        return true;
2385
-    }
2386
-
2387
-
2388
-
2389
-    /**
2390
-     * This simply returns an array of model fields for this object
2391
-     *
2392
-     * @return array
2393
-     * @throws \EE_Error
2394
-     */
2395
-    public function model_field_array()
2396
-    {
2397
-        $fields = $this->get_model()->field_settings(false);
2398
-        $properties = array();
2399
-        //remove prepended underscore
2400
-        foreach ($fields as $field_name => $settings) {
2401
-            $properties[$field_name] = $this->get($field_name);
2402
-        }
2403
-        return $properties;
2404
-    }
2405
-
2406
-
2407
-
2408
-    /**
2409
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2410
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2411
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2412
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2413
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2414
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2415
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2416
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2417
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2418
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2419
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2420
-     *        return $previousReturnValue.$returnString;
2421
-     * }
2422
-     * require('EE_Answer.class.php');
2423
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2424
-     * echo $answer->my_callback('monkeys',100);
2425
-     * //will output "you called my_callback! and passed args:monkeys,100"
2426
-     *
2427
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2428
-     * @param array  $args       array of original arguments passed to the function
2429
-     * @throws EE_Error
2430
-     * @return mixed whatever the plugin which calls add_filter decides
2431
-     */
2432
-    public function __call($methodName, $args)
2433
-    {
2434
-        $className = get_class($this);
2435
-        $tagName = "FHEE__{$className}__{$methodName}";
2436
-        if ( ! has_filter($tagName)) {
2437
-            throw new EE_Error(
2438
-                sprintf(
2439
-                    __(
2440
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2441
-                        "event_espresso"
2442
-                    ),
2443
-                    $methodName,
2444
-                    $className,
2445
-                    $tagName
2446
-                )
2447
-            );
2448
-        }
2449
-        return apply_filters($tagName, null, $this, $args);
2450
-    }
2451
-
2452
-
2453
-
2454
-    /**
2455
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2456
-     * A $previous_value can be specified in case there are many meta rows with the same key
2457
-     *
2458
-     * @param string $meta_key
2459
-     * @param mixed  $meta_value
2460
-     * @param mixed  $previous_value
2461
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2462
-     * @throws \EE_Error
2463
-     * NOTE: if the values haven't changed, returns 0
2464
-     */
2465
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2466
-    {
2467
-        $query_params = array(
2468
-            array(
2469
-                'EXM_key'  => $meta_key,
2470
-                'OBJ_ID'   => $this->ID(),
2471
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2472
-            ),
2473
-        );
2474
-        if ($previous_value !== null) {
2475
-            $query_params[0]['EXM_value'] = $meta_value;
2476
-        }
2477
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2478
-        if ( ! $existing_rows_like_that) {
2479
-            return $this->add_extra_meta($meta_key, $meta_value);
2480
-        }
2481
-        foreach ($existing_rows_like_that as $existing_row) {
2482
-            $existing_row->save(array('EXM_value' => $meta_value));
2483
-        }
2484
-        return count($existing_rows_like_that);
2485
-    }
2486
-
2487
-
2488
-
2489
-    /**
2490
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2491
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2492
-     * extra meta row was entered, false if not
2493
-     *
2494
-     * @param string  $meta_key
2495
-     * @param mixed   $meta_value
2496
-     * @param boolean $unique
2497
-     * @return boolean
2498
-     * @throws \EE_Error
2499
-     */
2500
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2501
-    {
2502
-        if ($unique) {
2503
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2504
-                array(
2505
-                    array(
2506
-                        'EXM_key'  => $meta_key,
2507
-                        'OBJ_ID'   => $this->ID(),
2508
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2509
-                    ),
2510
-                )
2511
-            );
2512
-            if ($existing_extra_meta) {
2513
-                return false;
2514
-            }
2515
-        }
2516
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2517
-            array(
2518
-                'EXM_key'   => $meta_key,
2519
-                'EXM_value' => $meta_value,
2520
-                'OBJ_ID'    => $this->ID(),
2521
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2522
-            )
2523
-        );
2524
-        $new_extra_meta->save();
2525
-        return true;
2526
-    }
2527
-
2528
-
2529
-
2530
-    /**
2531
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2532
-     * is specified, only deletes extra meta records with that value.
2533
-     *
2534
-     * @param string $meta_key
2535
-     * @param mixed  $meta_value
2536
-     * @return int number of extra meta rows deleted
2537
-     * @throws \EE_Error
2538
-     */
2539
-    public function delete_extra_meta($meta_key, $meta_value = null)
2540
-    {
2541
-        $query_params = array(
2542
-            array(
2543
-                'EXM_key'  => $meta_key,
2544
-                'OBJ_ID'   => $this->ID(),
2545
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2546
-            ),
2547
-        );
2548
-        if ($meta_value !== null) {
2549
-            $query_params[0]['EXM_value'] = $meta_value;
2550
-        }
2551
-        return EEM_Extra_Meta::instance()->delete($query_params);
2552
-    }
2553
-
2554
-
2555
-
2556
-    /**
2557
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2558
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2559
-     * You can specify $default is case you haven't found the extra meta
2560
-     *
2561
-     * @param string  $meta_key
2562
-     * @param boolean $single
2563
-     * @param mixed   $default if we don't find anything, what should we return?
2564
-     * @return mixed single value if $single; array if ! $single
2565
-     * @throws \EE_Error
2566
-     */
2567
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2568
-    {
2569
-        if ($single) {
2570
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2571
-            if ($result instanceof EE_Extra_Meta) {
2572
-                return $result->value();
2573
-            }
2574
-        } else {
2575
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2576
-            if ($results) {
2577
-                $values = array();
2578
-                foreach ($results as $result) {
2579
-                    if ($result instanceof EE_Extra_Meta) {
2580
-                        $values[$result->ID()] = $result->value();
2581
-                    }
2582
-                }
2583
-                return $values;
2584
-            }
2585
-        }
2586
-        //if nothing discovered yet return default.
2587
-        return apply_filters(
2588
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2589
-            $default,
2590
-            $meta_key,
2591
-            $single,
2592
-            $this
2593
-            );
2594
-    }
2595
-
2596
-
2597
-
2598
-    /**
2599
-     * Returns a simple array of all the extra meta associated with this model object.
2600
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2601
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2602
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2603
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2604
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2605
-     * finally the extra meta's value as each sub-value. (eg
2606
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2607
-     *
2608
-     * @param boolean $one_of_each_key
2609
-     * @return array
2610
-     * @throws \EE_Error
2611
-     */
2612
-    public function all_extra_meta_array($one_of_each_key = true)
2613
-    {
2614
-        $return_array = array();
2615
-        if ($one_of_each_key) {
2616
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2617
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2618
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2619
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2620
-                }
2621
-            }
2622
-        } else {
2623
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2624
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2625
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2626
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2627
-                        $return_array[$extra_meta_obj->key()] = array();
2628
-                    }
2629
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2630
-                }
2631
-            }
2632
-        }
2633
-        return $return_array;
2634
-    }
2635
-
2636
-
2637
-
2638
-    /**
2639
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2640
-     *
2641
-     * @return string
2642
-     * @throws \EE_Error
2643
-     */
2644
-    public function name()
2645
-    {
2646
-        //find a field that's not a text field
2647
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2648
-        if ($field_we_can_use) {
2649
-            return $this->get($field_we_can_use->get_name());
2650
-        } else {
2651
-            $first_few_properties = $this->model_field_array();
2652
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2653
-            $name_parts = array();
2654
-            foreach ($first_few_properties as $name => $value) {
2655
-                $name_parts[] = "$name:$value";
2656
-            }
2657
-            return implode(",", $name_parts);
2658
-        }
2659
-    }
2660
-
2661
-
2662
-
2663
-    /**
2664
-     * in_entity_map
2665
-     * Checks if this model object has been proven to already be in the entity map
2666
-     *
2667
-     * @return boolean
2668
-     * @throws \EE_Error
2669
-     */
2670
-    public function in_entity_map()
2671
-    {
2672
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2673
-            //well, if we looked, did we find it in the entity map?
2674
-            return true;
2675
-        } else {
2676
-            return false;
2677
-        }
2678
-    }
2679
-
2680
-
2681
-
2682
-    /**
2683
-     * refresh_from_db
2684
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2685
-     *
2686
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2687
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2688
-     */
2689
-    public function refresh_from_db()
2690
-    {
2691
-        if ($this->ID() && $this->in_entity_map()) {
2692
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2693
-        } else {
2694
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2695
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2696
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2697
-            //absolutely nothing in it for this ID
2698
-            if (WP_DEBUG) {
2699
-                throw new EE_Error(
2700
-                    sprintf(
2701
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2702
-                            'event_espresso'),
2703
-                        $this->ID(),
2704
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2705
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2706
-                    )
2707
-                );
2708
-            }
2709
-        }
2710
-    }
2711
-
2712
-
2713
-
2714
-    /**
2715
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2716
-     * (probably a bad assumption they have made, oh well)
2717
-     *
2718
-     * @return string
2719
-     */
2720
-    public function __toString()
2721
-    {
2722
-        try {
2723
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2724
-        } catch (Exception $e) {
2725
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2726
-            return '';
2727
-        }
2728
-    }
2729
-
2730
-
2731
-
2732
-    /**
2733
-     * Clear related model objects if they're already in the DB, because otherwise when we
2734
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2735
-     * This means if we have made changes to those related model objects, and want to unserialize
2736
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2737
-     * Instead, those related model objects should be directly serialized and stored.
2738
-     * Eg, the following won't work:
2739
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2740
-     * $att = $reg->attendee();
2741
-     * $att->set( 'ATT_fname', 'Dirk' );
2742
-     * update_option( 'my_option', serialize( $reg ) );
2743
-     * //END REQUEST
2744
-     * //START NEXT REQUEST
2745
-     * $reg = get_option( 'my_option' );
2746
-     * $reg->attendee()->save();
2747
-     * And would need to be replace with:
2748
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2749
-     * $att = $reg->attendee();
2750
-     * $att->set( 'ATT_fname', 'Dirk' );
2751
-     * update_option( 'my_option', serialize( $reg ) );
2752
-     * //END REQUEST
2753
-     * //START NEXT REQUEST
2754
-     * $att = get_option( 'my_option' );
2755
-     * $att->save();
2756
-     *
2757
-     * @return array
2758
-     * @throws \EE_Error
2759
-     */
2760
-    public function __sleep()
2761
-    {
2762
-        $model = $this->get_model();
2763
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2764
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2765
-                $classname = 'EE_' . $model->get_this_model_name();
2766
-                if (
2767
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2768
-                    && $this->get_one_from_cache($relation_name)->ID()
2769
-                ) {
2770
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2771
-                }
2772
-            }
2773
-        }
2774
-        $this->_props_n_values_provided_in_constructor = array();
2775
-        $properties_to_serialize = get_object_vars($this);
2776
-        //don't serialize the model. It's big and that risks recursion
2777
-        unset($properties_to_serialize['_model']);
2778
-        return array_keys($properties_to_serialize);
2779
-    }
2780
-
2781
-
2782
-
2783
-    /**
2784
-     * restore _props_n_values_provided_in_constructor
2785
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2786
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2787
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2788
-     */
2789
-    public function __wakeup()
2790
-    {
2791
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2792
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
+	 * access to it.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_timezone;
48
+
49
+
50
+
51
+	/**
52
+	 * date format
53
+	 * pattern or format for displaying dates
54
+	 *
55
+	 * @var string $_dt_frmt
56
+	 */
57
+	protected $_dt_frmt;
58
+
59
+
60
+
61
+	/**
62
+	 * time format
63
+	 * pattern or format for displaying time
64
+	 *
65
+	 * @var string $_tm_frmt
66
+	 */
67
+	protected $_tm_frmt;
68
+
69
+
70
+
71
+	/**
72
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
73
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
74
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected $_cached_properties = array();
80
+
81
+	/**
82
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
83
+	 * single
84
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
+	 * all others have an array)
87
+	 *
88
+	 * @var array
89
+	 */
90
+	protected $_model_relations = array();
91
+
92
+	/**
93
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_fields = array();
99
+
100
+	/**
101
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
102
+	 * For example, we might create model objects intended to only be used for the duration
103
+	 * of this request and to be thrown away, and if they were accidentally saved
104
+	 * it would be a bug.
105
+	 */
106
+	protected $_allow_persist = true;
107
+
108
+	/**
109
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
110
+	 */
111
+	protected $_has_changes = false;
112
+
113
+	/**
114
+	 * @var EEM_Base
115
+	 */
116
+	protected $_model;
117
+
118
+
119
+	/**
120
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
121
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
122
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
123
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
124
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
125
+	 * array as:
126
+	 * array(
127
+	 *  'Registration_Count' => 24
128
+	 * );
129
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
130
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
131
+	 * info)
132
+	 *
133
+	 * @var array
134
+	 */
135
+	protected $custom_selection_results = array();
136
+
137
+
138
+
139
+	/**
140
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
141
+	 * play nice
142
+	 *
143
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
144
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
145
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
146
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
147
+	 *                                                         corresponding db model or not.
148
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
149
+	 *                                                         be in when instantiating a EE_Base_Class object.
150
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
151
+	 *                                                         value is the date_format and second value is the time
152
+	 *                                                         format.
153
+	 * @throws EE_Error
154
+	 */
155
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
156
+	{
157
+		$className = get_class($this);
158
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
159
+		$model = $this->get_model();
160
+		$model_fields = $model->field_settings(false);
161
+		// ensure $fieldValues is an array
162
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
163
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
164
+		// verify client code has not passed any invalid field names
165
+		foreach ($fieldValues as $field_name => $field_value) {
166
+			if ( ! isset($model_fields[$field_name])) {
167
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
168
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
169
+			}
170
+		}
171
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
172
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
173
+		if ( ! empty($date_formats) && is_array($date_formats)) {
174
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
175
+		} else {
176
+			//set default formats for date and time
177
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
178
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
179
+		}
180
+		//if db model is instantiating
181
+		if ($bydb) {
182
+			//client code has indicated these field values are from the database
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
185
+			}
186
+		} else {
187
+			//we're constructing a brand
188
+			//new instance of the model object. Generally, this means we'll need to do more field validation
189
+			foreach ($model_fields as $fieldName => $field) {
190
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
191
+			}
192
+		}
193
+		//remember what values were passed to this constructor
194
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
195
+		//remember in entity mapper
196
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
197
+			$model->add_to_entity_map($this);
198
+		}
199
+		//setup all the relations
200
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
201
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
202
+				$this->_model_relations[$relation_name] = null;
203
+			} else {
204
+				$this->_model_relations[$relation_name] = array();
205
+			}
206
+		}
207
+		/**
208
+		 * Action done at the end of each model object construction
209
+		 *
210
+		 * @param EE_Base_Class $this the model object just created
211
+		 */
212
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
213
+	}
214
+
215
+
216
+
217
+	/**
218
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
219
+	 *
220
+	 * @return boolean
221
+	 */
222
+	public function allow_persist()
223
+	{
224
+		return $this->_allow_persist;
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
231
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
232
+	 * you got new information that somehow made you change your mind.
233
+	 *
234
+	 * @param boolean $allow_persist
235
+	 * @return boolean
236
+	 */
237
+	public function set_allow_persist($allow_persist)
238
+	{
239
+		return $this->_allow_persist = $allow_persist;
240
+	}
241
+
242
+
243
+
244
+	/**
245
+	 * Gets the field's original value when this object was constructed during this request.
246
+	 * This can be helpful when determining if a model object has changed or not
247
+	 *
248
+	 * @param string $field_name
249
+	 * @return mixed|null
250
+	 * @throws \EE_Error
251
+	 */
252
+	public function get_original($field_name)
253
+	{
254
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258
+		} else {
259
+			return null;
260
+		}
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 * @param EE_Base_Class $obj
267
+	 * @return string
268
+	 */
269
+	public function get_class($obj)
270
+	{
271
+		return get_class($obj);
272
+	}
273
+
274
+
275
+
276
+	/**
277
+	 * Overrides parent because parent expects old models.
278
+	 * This also doesn't do any validation, and won't work for serialized arrays
279
+	 *
280
+	 * @param    string $field_name
281
+	 * @param    mixed  $field_value
282
+	 * @param bool      $use_default
283
+	 * @throws \EE_Error
284
+	 */
285
+	public function set($field_name, $field_value, $use_default = false)
286
+	{
287
+		// if not using default and nothing has changed, and object has already been setup (has ID),
288
+		// then don't do anything
289
+		if (
290
+			! $use_default
291
+			&& $this->_fields[$field_name] === $field_value
292
+			&& $this->ID()
293
+		) {
294
+			return;
295
+		}
296
+		$model = $this->get_model();
297
+		$this->_has_changes = true;
298
+		$field_obj = $model->field_settings_for($field_name);
299
+		if ($field_obj instanceof EE_Model_Field_Base) {
300
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
301
+			if ($field_obj instanceof EE_Datetime_Field) {
302
+				$field_obj->set_timezone($this->_timezone);
303
+				$field_obj->set_date_format($this->_dt_frmt);
304
+				$field_obj->set_time_format($this->_tm_frmt);
305
+			}
306
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
307
+			//should the value be null?
308
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
309
+				$this->_fields[$field_name] = $field_obj->get_default_value();
310
+				/**
311
+				 * To save having to refactor all the models, if a default value is used for a
312
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
313
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
314
+				 * object.
315
+				 *
316
+				 * @since 4.6.10+
317
+				 */
318
+				if (
319
+					$field_obj instanceof EE_Datetime_Field
320
+					&& $this->_fields[$field_name] !== null
321
+					&& ! $this->_fields[$field_name] instanceof DateTime
322
+				) {
323
+					empty($this->_fields[$field_name])
324
+						? $this->set($field_name, time())
325
+						: $this->set($field_name, $this->_fields[$field_name]);
326
+				}
327
+			} else {
328
+				$this->_fields[$field_name] = $holder_of_value;
329
+			}
330
+			//if we're not in the constructor...
331
+			//now check if what we set was a primary key
332
+			if (
333
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
334
+				$this->_props_n_values_provided_in_constructor
335
+				&& $field_value
336
+				&& $field_name === $model->primary_key_name()
337
+			) {
338
+				//if so, we want all this object's fields to be filled either with
339
+				//what we've explicitly set on this model
340
+				//or what we have in the db
341
+				// echo "setting primary key!";
342
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
343
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
344
+				foreach ($fields_on_model as $field_obj) {
345
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
346
+						 && $field_obj->get_name() !== $field_name
347
+					) {
348
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
349
+					}
350
+				}
351
+				//oh this model object has an ID? well make sure its in the entity mapper
352
+				$model->add_to_entity_map($this);
353
+			}
354
+			//let's unset any cache for this field_name from the $_cached_properties property.
355
+			$this->_clear_cached_property($field_name);
356
+		} else {
357
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
358
+				"event_espresso"), $field_name));
359
+		}
360
+	}
361
+
362
+
363
+	/**
364
+	 * Set custom select values for model.
365
+	 * @param array $custom_select_values
366
+	 */
367
+	public function setCustomSelectsValues(array $custom_select_values)
368
+	{
369
+		$this->custom_selection_results = $custom_select_values;
370
+	}
371
+
372
+
373
+	/**
374
+	 * Returns the custom select value for the provided alias if its set.
375
+	 * If not set, returns null.
376
+	 * @param string $alias
377
+	 * @return string|int|float|null
378
+	 */
379
+	public function getForCustomSelectAlias($alias)
380
+	{
381
+		return isset($this->custom_selection_results[$alias])
382
+			? $this->custom_selection_results[$alias]
383
+			: null;
384
+	}
385
+
386
+
387
+
388
+	/**
389
+	 * This sets the field value on the db column if it exists for the given $column_name or
390
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
391
+	 *
392
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
393
+	 * @param string $field_name  Must be the exact column name.
394
+	 * @param mixed  $field_value The value to set.
395
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
396
+	 * @throws \EE_Error
397
+	 */
398
+	public function set_field_or_extra_meta($field_name, $field_value)
399
+	{
400
+		if ($this->get_model()->has_field($field_name)) {
401
+			$this->set($field_name, $field_value);
402
+			return true;
403
+		} else {
404
+			//ensure this object is saved first so that extra meta can be properly related.
405
+			$this->save();
406
+			return $this->update_extra_meta($field_name, $field_value);
407
+		}
408
+	}
409
+
410
+
411
+
412
+	/**
413
+	 * This retrieves the value of the db column set on this class or if that's not present
414
+	 * it will attempt to retrieve from extra_meta if found.
415
+	 * Example Usage:
416
+	 * Via EE_Message child class:
417
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
418
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
419
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
420
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
421
+	 * value for those extra fields dynamically via the EE_message object.
422
+	 *
423
+	 * @param  string $field_name expecting the fully qualified field name.
424
+	 * @return mixed|null  value for the field if found.  null if not found.
425
+	 * @throws \EE_Error
426
+	 */
427
+	public function get_field_or_extra_meta($field_name)
428
+	{
429
+		if ($this->get_model()->has_field($field_name)) {
430
+			$column_value = $this->get($field_name);
431
+		} else {
432
+			//This isn't a column in the main table, let's see if it is in the extra meta.
433
+			$column_value = $this->get_extra_meta($field_name, true, null);
434
+		}
435
+		return $column_value;
436
+	}
437
+
438
+
439
+
440
+	/**
441
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
442
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
443
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
444
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
445
+	 *
446
+	 * @access public
447
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
448
+	 * @return void
449
+	 * @throws \EE_Error
450
+	 */
451
+	public function set_timezone($timezone = '')
452
+	{
453
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
454
+		//make sure we clear all cached properties because they won't be relevant now
455
+		$this->_clear_cached_properties();
456
+		//make sure we update field settings and the date for all EE_Datetime_Fields
457
+		$model_fields = $this->get_model()->field_settings(false);
458
+		foreach ($model_fields as $field_name => $field_obj) {
459
+			if ($field_obj instanceof EE_Datetime_Field) {
460
+				$field_obj->set_timezone($this->_timezone);
461
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
462
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
463
+				}
464
+			}
465
+		}
466
+	}
467
+
468
+
469
+
470
+	/**
471
+	 * This just returns whatever is set for the current timezone.
472
+	 *
473
+	 * @access public
474
+	 * @return string timezone string
475
+	 */
476
+	public function get_timezone()
477
+	{
478
+		return $this->_timezone;
479
+	}
480
+
481
+
482
+
483
+	/**
484
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
485
+	 * internally instead of wp set date format options
486
+	 *
487
+	 * @since 4.6
488
+	 * @param string $format should be a format recognizable by PHP date() functions.
489
+	 */
490
+	public function set_date_format($format)
491
+	{
492
+		$this->_dt_frmt = $format;
493
+		//clear cached_properties because they won't be relevant now.
494
+		$this->_clear_cached_properties();
495
+	}
496
+
497
+
498
+
499
+	/**
500
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
501
+	 * class internally instead of wp set time format options.
502
+	 *
503
+	 * @since 4.6
504
+	 * @param string $format should be a format recognizable by PHP date() functions.
505
+	 */
506
+	public function set_time_format($format)
507
+	{
508
+		$this->_tm_frmt = $format;
509
+		//clear cached_properties because they won't be relevant now.
510
+		$this->_clear_cached_properties();
511
+	}
512
+
513
+
514
+
515
+	/**
516
+	 * This returns the current internal set format for the date and time formats.
517
+	 *
518
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
519
+	 *                             where the first value is the date format and the second value is the time format.
520
+	 * @return mixed string|array
521
+	 */
522
+	public function get_format($full = true)
523
+	{
524
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
525
+	}
526
+
527
+
528
+
529
+	/**
530
+	 * cache
531
+	 * stores the passed model object on the current model object.
532
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
533
+	 *
534
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
535
+	 *                                       'Registration' associated with this model object
536
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
537
+	 *                                       that could be a payment or a registration)
538
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
539
+	 *                                       items which will be stored in an array on this object
540
+	 * @throws EE_Error
541
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
542
+	 *                  related thing, no array)
543
+	 */
544
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
545
+	{
546
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
547
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
548
+			return false;
549
+		}
550
+		// also get "how" the object is related, or throw an error
551
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
552
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
553
+				$relationName, get_class($this)));
554
+		}
555
+		// how many things are related ?
556
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
557
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
558
+			// so for these model objects just set it to be cached
559
+			$this->_model_relations[$relationName] = $object_to_cache;
560
+			$return = true;
561
+		} else {
562
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
563
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
564
+			if ( ! is_array($this->_model_relations[$relationName])) {
565
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
566
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
567
+					? array($this->_model_relations[$relationName]) : array();
568
+			}
569
+			// first check for a cache_id which is normally empty
570
+			if ( ! empty($cache_id)) {
571
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
572
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
573
+				$return = $cache_id;
574
+			} elseif ($object_to_cache->ID()) {
575
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
576
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
577
+				$return = $object_to_cache->ID();
578
+			} else {
579
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
580
+				$this->_model_relations[$relationName][] = $object_to_cache;
581
+				// move the internal pointer to the end of the array
582
+				end($this->_model_relations[$relationName]);
583
+				// and grab the key so that we can return it
584
+				$return = key($this->_model_relations[$relationName]);
585
+			}
586
+		}
587
+		return $return;
588
+	}
589
+
590
+
591
+
592
+	/**
593
+	 * For adding an item to the cached_properties property.
594
+	 *
595
+	 * @access protected
596
+	 * @param string      $fieldname the property item the corresponding value is for.
597
+	 * @param mixed       $value     The value we are caching.
598
+	 * @param string|null $cache_type
599
+	 * @return void
600
+	 * @throws \EE_Error
601
+	 */
602
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
603
+	{
604
+		//first make sure this property exists
605
+		$this->get_model()->field_settings_for($fieldname);
606
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
607
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
608
+	}
609
+
610
+
611
+
612
+	/**
613
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
614
+	 * This also SETS the cache if we return the actual property!
615
+	 *
616
+	 * @param string $fieldname        the name of the property we're trying to retrieve
617
+	 * @param bool   $pretty
618
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
619
+	 *                                 (in cases where the same property may be used for different outputs
620
+	 *                                 - i.e. datetime, money etc.)
621
+	 *                                 It can also accept certain pre-defined "schema" strings
622
+	 *                                 to define how to output the property.
623
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
624
+	 * @return mixed                   whatever the value for the property is we're retrieving
625
+	 * @throws \EE_Error
626
+	 */
627
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
628
+	{
629
+		//verify the field exists
630
+		$model = $this->get_model();
631
+		$model->field_settings_for($fieldname);
632
+		$cache_type = $pretty ? 'pretty' : 'standard';
633
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
634
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
635
+			return $this->_cached_properties[$fieldname][$cache_type];
636
+		}
637
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
638
+		$this->_set_cached_property($fieldname, $value, $cache_type);
639
+		return $value;
640
+	}
641
+
642
+
643
+
644
+	/**
645
+	 * If the cache didn't fetch the needed item, this fetches it.
646
+	 * @param string $fieldname
647
+	 * @param bool $pretty
648
+	 * @param string $extra_cache_ref
649
+	 * @return mixed
650
+	 */
651
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
652
+	{
653
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
654
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
655
+		if ($field_obj instanceof EE_Datetime_Field) {
656
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
657
+		}
658
+		if ( ! isset($this->_fields[$fieldname])) {
659
+			$this->_fields[$fieldname] = null;
660
+		}
661
+		$value = $pretty
662
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
663
+			: $field_obj->prepare_for_get($this->_fields[$fieldname]);
664
+		return $value;
665
+	}
666
+
667
+
668
+
669
+	/**
670
+	 * set timezone, formats, and output for EE_Datetime_Field objects
671
+	 *
672
+	 * @param \EE_Datetime_Field $datetime_field
673
+	 * @param bool               $pretty
674
+	 * @param null $date_or_time
675
+	 * @return void
676
+	 * @throws \EE_Error
677
+	 */
678
+	protected function _prepare_datetime_field(
679
+		EE_Datetime_Field $datetime_field,
680
+		$pretty = false,
681
+		$date_or_time = null
682
+	) {
683
+		$datetime_field->set_timezone($this->_timezone);
684
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
685
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
686
+		//set the output returned
687
+		switch ($date_or_time) {
688
+			case 'D' :
689
+				$datetime_field->set_date_time_output('date');
690
+				break;
691
+			case 'T' :
692
+				$datetime_field->set_date_time_output('time');
693
+				break;
694
+			default :
695
+				$datetime_field->set_date_time_output();
696
+		}
697
+	}
698
+
699
+
700
+
701
+	/**
702
+	 * This just takes care of clearing out the cached_properties
703
+	 *
704
+	 * @return void
705
+	 */
706
+	protected function _clear_cached_properties()
707
+	{
708
+		$this->_cached_properties = array();
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 * This just clears out ONE property if it exists in the cache
715
+	 *
716
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
717
+	 * @return void
718
+	 */
719
+	protected function _clear_cached_property($property_name)
720
+	{
721
+		if (isset($this->_cached_properties[$property_name])) {
722
+			unset($this->_cached_properties[$property_name]);
723
+		}
724
+	}
725
+
726
+
727
+
728
+	/**
729
+	 * Ensures that this related thing is a model object.
730
+	 *
731
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
732
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
733
+	 * @return EE_Base_Class
734
+	 * @throws \EE_Error
735
+	 */
736
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
737
+	{
738
+		$other_model_instance = self::_get_model_instance_with_name(
739
+			self::_get_model_classname($model_name),
740
+			$this->_timezone
741
+		);
742
+		return $other_model_instance->ensure_is_obj($object_or_id);
743
+	}
744
+
745
+
746
+
747
+	/**
748
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
749
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
750
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
751
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
752
+	 *
753
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
754
+	 *                                                     Eg 'Registration'
755
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
756
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
757
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
758
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
759
+	 *                                                     this is HasMany or HABTM.
760
+	 * @throws EE_Error
761
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
762
+	 *                       relation from all
763
+	 */
764
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
765
+	{
766
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
767
+		$index_in_cache = '';
768
+		if ( ! $relationship_to_model) {
769
+			throw new EE_Error(
770
+				sprintf(
771
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
772
+					$relationName,
773
+					get_class($this)
774
+				)
775
+			);
776
+		}
777
+		if ($clear_all) {
778
+			$obj_removed = true;
779
+			$this->_model_relations[$relationName] = null;
780
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
781
+			$obj_removed = $this->_model_relations[$relationName];
782
+			$this->_model_relations[$relationName] = null;
783
+		} else {
784
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
785
+				&& $object_to_remove_or_index_into_array->ID()
786
+			) {
787
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
788
+				if (is_array($this->_model_relations[$relationName])
789
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
790
+				) {
791
+					$index_found_at = null;
792
+					//find this object in the array even though it has a different key
793
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
794
+						if (
795
+							$obj instanceof EE_Base_Class
796
+							&& (
797
+								$obj == $object_to_remove_or_index_into_array
798
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
799
+							)
800
+						) {
801
+							$index_found_at = $index;
802
+							break;
803
+						}
804
+					}
805
+					if ($index_found_at) {
806
+						$index_in_cache = $index_found_at;
807
+					} else {
808
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
809
+						//if it wasn't in it to begin with. So we're done
810
+						return $object_to_remove_or_index_into_array;
811
+					}
812
+				}
813
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
814
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
815
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
816
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
817
+						$index_in_cache = $index;
818
+					}
819
+				}
820
+			} else {
821
+				$index_in_cache = $object_to_remove_or_index_into_array;
822
+			}
823
+			//supposedly we've found it. But it could just be that the client code
824
+			//provided a bad index/object
825
+			if (
826
+			isset(
827
+				$this->_model_relations[$relationName],
828
+				$this->_model_relations[$relationName][$index_in_cache]
829
+			)
830
+			) {
831
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
832
+				unset($this->_model_relations[$relationName][$index_in_cache]);
833
+			} else {
834
+				//that thing was never cached anyways.
835
+				$obj_removed = null;
836
+			}
837
+		}
838
+		return $obj_removed;
839
+	}
840
+
841
+
842
+
843
+	/**
844
+	 * update_cache_after_object_save
845
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
846
+	 * obtained after being saved to the db
847
+	 *
848
+	 * @param string         $relationName       - the type of object that is cached
849
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
850
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
851
+	 * @return boolean TRUE on success, FALSE on fail
852
+	 * @throws \EE_Error
853
+	 */
854
+	public function update_cache_after_object_save(
855
+		$relationName,
856
+		EE_Base_Class $newly_saved_object,
857
+		$current_cache_id = ''
858
+	) {
859
+		// verify that incoming object is of the correct type
860
+		$obj_class = 'EE_' . $relationName;
861
+		if ($newly_saved_object instanceof $obj_class) {
862
+			/* @type EE_Base_Class $newly_saved_object */
863
+			// now get the type of relation
864
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
865
+			// if this is a 1:1 relationship
866
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
867
+				// then just replace the cached object with the newly saved object
868
+				$this->_model_relations[$relationName] = $newly_saved_object;
869
+				return true;
870
+				// or if it's some kind of sordid feral polyamorous relationship...
871
+			} elseif (is_array($this->_model_relations[$relationName])
872
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
873
+			) {
874
+				// then remove the current cached item
875
+				unset($this->_model_relations[$relationName][$current_cache_id]);
876
+				// and cache the newly saved object using it's new ID
877
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
878
+				return true;
879
+			}
880
+		}
881
+		return false;
882
+	}
883
+
884
+
885
+
886
+	/**
887
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
888
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
889
+	 *
890
+	 * @param string $relationName
891
+	 * @return EE_Base_Class
892
+	 */
893
+	public function get_one_from_cache($relationName)
894
+	{
895
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
896
+			: null;
897
+		if (is_array($cached_array_or_object)) {
898
+			return array_shift($cached_array_or_object);
899
+		} else {
900
+			return $cached_array_or_object;
901
+		}
902
+	}
903
+
904
+
905
+
906
+	/**
907
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
908
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
909
+	 *
910
+	 * @param string $relationName
911
+	 * @throws \EE_Error
912
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
913
+	 */
914
+	public function get_all_from_cache($relationName)
915
+	{
916
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
917
+		// if the result is not an array, but exists, make it an array
918
+		$objects = is_array($objects) ? $objects : array($objects);
919
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
920
+		//basically, if this model object was stored in the session, and these cached model objects
921
+		//already have IDs, let's make sure they're in their model's entity mapper
922
+		//otherwise we will have duplicates next time we call
923
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
924
+		$model = EE_Registry::instance()->load_model($relationName);
925
+		foreach ($objects as $model_object) {
926
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
927
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
928
+				if ($model_object->ID()) {
929
+					$model->add_to_entity_map($model_object);
930
+				}
931
+			} else {
932
+				throw new EE_Error(
933
+					sprintf(
934
+						__(
935
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
936
+							'event_espresso'
937
+						),
938
+						$relationName,
939
+						gettype($model_object)
940
+					)
941
+				);
942
+			}
943
+		}
944
+		return $objects;
945
+	}
946
+
947
+
948
+
949
+	/**
950
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
951
+	 * matching the given query conditions.
952
+	 *
953
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
954
+	 * @param int   $limit              How many objects to return.
955
+	 * @param array $query_params       Any additional conditions on the query.
956
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
957
+	 *                                  you can indicate just the columns you want returned
958
+	 * @return array|EE_Base_Class[]
959
+	 * @throws \EE_Error
960
+	 */
961
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
962
+	{
963
+		$model = $this->get_model();
964
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
965
+			? $model->get_primary_key_field()->get_name()
966
+			: $field_to_order_by;
967
+		$current_value = ! empty($field) ? $this->get($field) : null;
968
+		if (empty($field) || empty($current_value)) {
969
+			return array();
970
+		}
971
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
972
+	}
973
+
974
+
975
+
976
+	/**
977
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
978
+	 * matching the given query conditions.
979
+	 *
980
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
981
+	 * @param int   $limit              How many objects to return.
982
+	 * @param array $query_params       Any additional conditions on the query.
983
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
984
+	 *                                  you can indicate just the columns you want returned
985
+	 * @return array|EE_Base_Class[]
986
+	 * @throws \EE_Error
987
+	 */
988
+	public function previous_x(
989
+		$field_to_order_by = null,
990
+		$limit = 1,
991
+		$query_params = array(),
992
+		$columns_to_select = null
993
+	) {
994
+		$model = $this->get_model();
995
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
996
+			? $model->get_primary_key_field()->get_name()
997
+			: $field_to_order_by;
998
+		$current_value = ! empty($field) ? $this->get($field) : null;
999
+		if (empty($field) || empty($current_value)) {
1000
+			return array();
1001
+		}
1002
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1003
+	}
1004
+
1005
+
1006
+
1007
+	/**
1008
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1009
+	 * matching the given query conditions.
1010
+	 *
1011
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1012
+	 * @param array $query_params       Any additional conditions on the query.
1013
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1014
+	 *                                  you can indicate just the columns you want returned
1015
+	 * @return array|EE_Base_Class
1016
+	 * @throws \EE_Error
1017
+	 */
1018
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1019
+	{
1020
+		$model = $this->get_model();
1021
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1022
+			? $model->get_primary_key_field()->get_name()
1023
+			: $field_to_order_by;
1024
+		$current_value = ! empty($field) ? $this->get($field) : null;
1025
+		if (empty($field) || empty($current_value)) {
1026
+			return array();
1027
+		}
1028
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1029
+	}
1030
+
1031
+
1032
+
1033
+	/**
1034
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1035
+	 * matching the given query conditions.
1036
+	 *
1037
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1038
+	 * @param array $query_params       Any additional conditions on the query.
1039
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1040
+	 *                                  you can indicate just the column you want returned
1041
+	 * @return array|EE_Base_Class
1042
+	 * @throws \EE_Error
1043
+	 */
1044
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1045
+	{
1046
+		$model = $this->get_model();
1047
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1048
+			? $model->get_primary_key_field()->get_name()
1049
+			: $field_to_order_by;
1050
+		$current_value = ! empty($field) ? $this->get($field) : null;
1051
+		if (empty($field) || empty($current_value)) {
1052
+			return array();
1053
+		}
1054
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1055
+	}
1056
+
1057
+
1058
+
1059
+	/**
1060
+	 * Overrides parent because parent expects old models.
1061
+	 * This also doesn't do any validation, and won't work for serialized arrays
1062
+	 *
1063
+	 * @param string $field_name
1064
+	 * @param mixed  $field_value_from_db
1065
+	 * @throws \EE_Error
1066
+	 */
1067
+	public function set_from_db($field_name, $field_value_from_db)
1068
+	{
1069
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1070
+		if ($field_obj instanceof EE_Model_Field_Base) {
1071
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
1072
+			//eg, a CPT model object could have an entry in the posts table, but no
1073
+			//entry in the meta table. Meaning that all its columns in the meta table
1074
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
1075
+			if ($field_value_from_db === null) {
1076
+				if ($field_obj->is_nullable()) {
1077
+					//if the field allows nulls, then let it be null
1078
+					$field_value = null;
1079
+				} else {
1080
+					$field_value = $field_obj->get_default_value();
1081
+				}
1082
+			} else {
1083
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1084
+			}
1085
+			$this->_fields[$field_name] = $field_value;
1086
+			$this->_clear_cached_property($field_name);
1087
+		}
1088
+	}
1089
+
1090
+
1091
+
1092
+	/**
1093
+	 * verifies that the specified field is of the correct type
1094
+	 *
1095
+	 * @param string $field_name
1096
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1097
+	 *                                (in cases where the same property may be used for different outputs
1098
+	 *                                - i.e. datetime, money etc.)
1099
+	 * @return mixed
1100
+	 * @throws \EE_Error
1101
+	 */
1102
+	public function get($field_name, $extra_cache_ref = null)
1103
+	{
1104
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1105
+	}
1106
+
1107
+
1108
+
1109
+	/**
1110
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1111
+	 *
1112
+	 * @param  string $field_name A valid fieldname
1113
+	 * @return mixed              Whatever the raw value stored on the property is.
1114
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1115
+	 */
1116
+	public function get_raw($field_name)
1117
+	{
1118
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1119
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1120
+			? $this->_fields[$field_name]->format('U')
1121
+			: $this->_fields[$field_name];
1122
+	}
1123
+
1124
+
1125
+
1126
+	/**
1127
+	 * This is used to return the internal DateTime object used for a field that is a
1128
+	 * EE_Datetime_Field.
1129
+	 *
1130
+	 * @param string $field_name               The field name retrieving the DateTime object.
1131
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1132
+	 * @throws \EE_Error
1133
+	 *                                         an error is set and false returned.  If the field IS an
1134
+	 *                                         EE_Datetime_Field and but the field value is null, then
1135
+	 *                                         just null is returned (because that indicates that likely
1136
+	 *                                         this field is nullable).
1137
+	 */
1138
+	public function get_DateTime_object($field_name)
1139
+	{
1140
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1141
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1142
+			EE_Error::add_error(
1143
+				sprintf(
1144
+					__(
1145
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1146
+						'event_espresso'
1147
+					),
1148
+					$field_name
1149
+				),
1150
+				__FILE__,
1151
+				__FUNCTION__,
1152
+				__LINE__
1153
+			);
1154
+			return false;
1155
+		}
1156
+		return $this->_fields[$field_name];
1157
+	}
1158
+
1159
+
1160
+
1161
+	/**
1162
+	 * To be used in template to immediately echo out the value, and format it for output.
1163
+	 * Eg, should call stripslashes and whatnot before echoing
1164
+	 *
1165
+	 * @param string $field_name      the name of the field as it appears in the DB
1166
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
+	 *                                (in cases where the same property may be used for different outputs
1168
+	 *                                - i.e. datetime, money etc.)
1169
+	 * @return void
1170
+	 * @throws \EE_Error
1171
+	 */
1172
+	public function e($field_name, $extra_cache_ref = null)
1173
+	{
1174
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1175
+	}
1176
+
1177
+
1178
+
1179
+	/**
1180
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1181
+	 * can be easily used as the value of form input.
1182
+	 *
1183
+	 * @param string $field_name
1184
+	 * @return void
1185
+	 * @throws \EE_Error
1186
+	 */
1187
+	public function f($field_name)
1188
+	{
1189
+		$this->e($field_name, 'form_input');
1190
+	}
1191
+
1192
+	/**
1193
+	 * Same as `f()` but just returns the value instead of echoing it
1194
+	 * @param string $field_name
1195
+	 * @return string
1196
+	 */
1197
+	public function get_f($field_name)
1198
+	{
1199
+		return (string)$this->get_pretty($field_name,'form_input');
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1206
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1207
+	 * to see what options are available.
1208
+	 * @param string $field_name
1209
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1210
+	 *                                (in cases where the same property may be used for different outputs
1211
+	 *                                - i.e. datetime, money etc.)
1212
+	 * @return mixed
1213
+	 * @throws \EE_Error
1214
+	 */
1215
+	public function get_pretty($field_name, $extra_cache_ref = null)
1216
+	{
1217
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1218
+	}
1219
+
1220
+
1221
+
1222
+	/**
1223
+	 * This simply returns the datetime for the given field name
1224
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1225
+	 * (and the equivalent e_date, e_time, e_datetime).
1226
+	 *
1227
+	 * @access   protected
1228
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1229
+	 * @param string   $dt_frmt      valid datetime format used for date
1230
+	 *                               (if '' then we just use the default on the field,
1231
+	 *                               if NULL we use the last-used format)
1232
+	 * @param string   $tm_frmt      Same as above except this is for time format
1233
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1234
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1235
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1236
+	 *                               if field is not a valid dtt field, or void if echoing
1237
+	 * @throws \EE_Error
1238
+	 */
1239
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1240
+	{
1241
+		// clear cached property
1242
+		$this->_clear_cached_property($field_name);
1243
+		//reset format properties because they are used in get()
1244
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1245
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1246
+		if ($echo) {
1247
+			$this->e($field_name, $date_or_time);
1248
+			return '';
1249
+		}
1250
+		return $this->get($field_name, $date_or_time);
1251
+	}
1252
+
1253
+
1254
+
1255
+	/**
1256
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1257
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1258
+	 * other echoes the pretty value for dtt)
1259
+	 *
1260
+	 * @param  string $field_name name of model object datetime field holding the value
1261
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1262
+	 * @return string            datetime value formatted
1263
+	 * @throws \EE_Error
1264
+	 */
1265
+	public function get_date($field_name, $format = '')
1266
+	{
1267
+		return $this->_get_datetime($field_name, $format, null, 'D');
1268
+	}
1269
+
1270
+
1271
+
1272
+	/**
1273
+	 * @param      $field_name
1274
+	 * @param string $format
1275
+	 * @throws \EE_Error
1276
+	 */
1277
+	public function e_date($field_name, $format = '')
1278
+	{
1279
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1280
+	}
1281
+
1282
+
1283
+
1284
+	/**
1285
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1286
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1287
+	 * other echoes the pretty value for dtt)
1288
+	 *
1289
+	 * @param  string $field_name name of model object datetime field holding the value
1290
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1291
+	 * @return string             datetime value formatted
1292
+	 * @throws \EE_Error
1293
+	 */
1294
+	public function get_time($field_name, $format = '')
1295
+	{
1296
+		return $this->_get_datetime($field_name, null, $format, 'T');
1297
+	}
1298
+
1299
+
1300
+
1301
+	/**
1302
+	 * @param      $field_name
1303
+	 * @param string $format
1304
+	 * @throws \EE_Error
1305
+	 */
1306
+	public function e_time($field_name, $format = '')
1307
+	{
1308
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1309
+	}
1310
+
1311
+
1312
+
1313
+	/**
1314
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1315
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1316
+	 * other echoes the pretty value for dtt)
1317
+	 *
1318
+	 * @param  string $field_name name of model object datetime field holding the value
1319
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1320
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1321
+	 * @return string             datetime value formatted
1322
+	 * @throws \EE_Error
1323
+	 */
1324
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1325
+	{
1326
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * @param string $field_name
1333
+	 * @param string $dt_frmt
1334
+	 * @param string $tm_frmt
1335
+	 * @throws \EE_Error
1336
+	 */
1337
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1338
+	{
1339
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1340
+	}
1341
+
1342
+
1343
+
1344
+	/**
1345
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1346
+	 *
1347
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1348
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1349
+	 *                           on the object will be used.
1350
+	 * @return string Date and time string in set locale or false if no field exists for the given
1351
+	 * @throws \EE_Error
1352
+	 *                           field name.
1353
+	 */
1354
+	public function get_i18n_datetime($field_name, $format = '')
1355
+	{
1356
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1357
+		return date_i18n(
1358
+			$format,
1359
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1360
+		);
1361
+	}
1362
+
1363
+
1364
+
1365
+	/**
1366
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1367
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1368
+	 * thrown.
1369
+	 *
1370
+	 * @param  string $field_name The field name being checked
1371
+	 * @throws EE_Error
1372
+	 * @return EE_Datetime_Field
1373
+	 */
1374
+	protected function _get_dtt_field_settings($field_name)
1375
+	{
1376
+		$field = $this->get_model()->field_settings_for($field_name);
1377
+		//check if field is dtt
1378
+		if ($field instanceof EE_Datetime_Field) {
1379
+			return $field;
1380
+		} else {
1381
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1382
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1383
+		}
1384
+	}
1385
+
1386
+
1387
+
1388
+
1389
+	/**
1390
+	 * NOTE ABOUT BELOW:
1391
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1392
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1393
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1394
+	 * method and make sure you send the entire datetime value for setting.
1395
+	 */
1396
+	/**
1397
+	 * sets the time on a datetime property
1398
+	 *
1399
+	 * @access protected
1400
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1401
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1402
+	 * @throws \EE_Error
1403
+	 */
1404
+	protected function _set_time_for($time, $fieldname)
1405
+	{
1406
+		$this->_set_date_time('T', $time, $fieldname);
1407
+	}
1408
+
1409
+
1410
+
1411
+	/**
1412
+	 * sets the date on a datetime property
1413
+	 *
1414
+	 * @access protected
1415
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1416
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1417
+	 * @throws \EE_Error
1418
+	 */
1419
+	protected function _set_date_for($date, $fieldname)
1420
+	{
1421
+		$this->_set_date_time('D', $date, $fieldname);
1422
+	}
1423
+
1424
+
1425
+
1426
+	/**
1427
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1428
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1429
+	 *
1430
+	 * @access protected
1431
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1432
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1433
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1434
+	 *                                        EE_Datetime_Field property)
1435
+	 * @throws \EE_Error
1436
+	 */
1437
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1438
+	{
1439
+		$field = $this->_get_dtt_field_settings($fieldname);
1440
+		$field->set_timezone($this->_timezone);
1441
+		$field->set_date_format($this->_dt_frmt);
1442
+		$field->set_time_format($this->_tm_frmt);
1443
+		switch ($what) {
1444
+			case 'T' :
1445
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1446
+					$datetime_value,
1447
+					$this->_fields[$fieldname]
1448
+				);
1449
+				break;
1450
+			case 'D' :
1451
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1452
+					$datetime_value,
1453
+					$this->_fields[$fieldname]
1454
+				);
1455
+				break;
1456
+			case 'B' :
1457
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1458
+				break;
1459
+		}
1460
+		$this->_clear_cached_property($fieldname);
1461
+	}
1462
+
1463
+
1464
+
1465
+	/**
1466
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1467
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1468
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1469
+	 * that could lead to some unexpected results!
1470
+	 *
1471
+	 * @access public
1472
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time
1473
+	 *                                         value being returned.
1474
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1475
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1476
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1477
+	 * @param string               $append     You can include something to append on the timestamp
1478
+	 * @throws EE_Error
1479
+	 * @return string timestamp
1480
+	 */
1481
+	public function display_in_my_timezone(
1482
+		$field_name,
1483
+		$callback = 'get_datetime',
1484
+		$args = null,
1485
+		$prepend = '',
1486
+		$append = ''
1487
+	) {
1488
+		$timezone = EEH_DTT_Helper::get_timezone();
1489
+		if ($timezone === $this->_timezone) {
1490
+			return '';
1491
+		}
1492
+		$original_timezone = $this->_timezone;
1493
+		$this->set_timezone($timezone);
1494
+		$fn = (array)$field_name;
1495
+		$args = array_merge($fn, (array)$args);
1496
+		if ( ! method_exists($this, $callback)) {
1497
+			throw new EE_Error(
1498
+				sprintf(
1499
+					__(
1500
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1501
+						'event_espresso'
1502
+					),
1503
+					$callback
1504
+				)
1505
+			);
1506
+		}
1507
+		$args = (array)$args;
1508
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1509
+		$this->set_timezone($original_timezone);
1510
+		return $return;
1511
+	}
1512
+
1513
+
1514
+
1515
+	/**
1516
+	 * Deletes this model object.
1517
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1518
+	 * override
1519
+	 * `EE_Base_Class::_delete` NOT this class.
1520
+	 *
1521
+	 * @return boolean | int
1522
+	 * @throws \EE_Error
1523
+	 */
1524
+	public function delete()
1525
+	{
1526
+		/**
1527
+		 * Called just before the `EE_Base_Class::_delete` method call.
1528
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1529
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1530
+		 * soft deletes (trash) the object and does not permanently delete it.
1531
+		 *
1532
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1533
+		 */
1534
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1535
+		$result = $this->_delete();
1536
+		/**
1537
+		 * Called just after the `EE_Base_Class::_delete` method call.
1538
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1539
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1540
+		 * soft deletes (trash) the object and does not permanently delete it.
1541
+		 *
1542
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1543
+		 * @param boolean       $result
1544
+		 */
1545
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1546
+		return $result;
1547
+	}
1548
+
1549
+
1550
+
1551
+	/**
1552
+	 * Calls the specific delete method for the instantiated class.
1553
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1554
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1555
+	 * `EE_Base_Class::delete`
1556
+	 *
1557
+	 * @return bool|int
1558
+	 * @throws \EE_Error
1559
+	 */
1560
+	protected function _delete()
1561
+	{
1562
+		return $this->delete_permanently();
1563
+	}
1564
+
1565
+
1566
+
1567
+	/**
1568
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1569
+	 * error)
1570
+	 *
1571
+	 * @return bool | int
1572
+	 * @throws \EE_Error
1573
+	 */
1574
+	public function delete_permanently()
1575
+	{
1576
+		/**
1577
+		 * Called just before HARD deleting a model object
1578
+		 *
1579
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1580
+		 */
1581
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1582
+		$model = $this->get_model();
1583
+		$result = $model->delete_permanently_by_ID($this->ID());
1584
+		$this->refresh_cache_of_related_objects();
1585
+		/**
1586
+		 * Called just after HARD deleting a model object
1587
+		 *
1588
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1589
+		 * @param boolean       $result
1590
+		 */
1591
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1592
+		return $result;
1593
+	}
1594
+
1595
+
1596
+
1597
+	/**
1598
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1599
+	 * related model objects
1600
+	 *
1601
+	 * @throws \EE_Error
1602
+	 */
1603
+	public function refresh_cache_of_related_objects()
1604
+	{
1605
+		$model = $this->get_model();
1606
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1607
+			if ( ! empty($this->_model_relations[$relation_name])) {
1608
+				$related_objects = $this->_model_relations[$relation_name];
1609
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1610
+					//this relation only stores a single model object, not an array
1611
+					//but let's make it consistent
1612
+					$related_objects = array($related_objects);
1613
+				}
1614
+				foreach ($related_objects as $related_object) {
1615
+					//only refresh their cache if they're in memory
1616
+					if ($related_object instanceof EE_Base_Class) {
1617
+						$related_object->clear_cache($model->get_this_model_name(), $this);
1618
+					}
1619
+				}
1620
+			}
1621
+		}
1622
+	}
1623
+
1624
+
1625
+
1626
+	/**
1627
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1628
+	 * object just before saving.
1629
+	 *
1630
+	 * @access public
1631
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1632
+	 *                                 if provided during the save() method (often client code will change the fields'
1633
+	 *                                 values before calling save)
1634
+	 * @throws \EE_Error
1635
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1636
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1637
+	 */
1638
+	public function save($set_cols_n_values = array())
1639
+	{
1640
+		$model = $this->get_model();
1641
+		/**
1642
+		 * Filters the fields we're about to save on the model object
1643
+		 *
1644
+		 * @param array         $set_cols_n_values
1645
+		 * @param EE_Base_Class $model_object
1646
+		 */
1647
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1648
+			$this);
1649
+		//set attributes as provided in $set_cols_n_values
1650
+		foreach ($set_cols_n_values as $column => $value) {
1651
+			$this->set($column, $value);
1652
+		}
1653
+		// no changes ? then don't do anything
1654
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1655
+			return 0;
1656
+		}
1657
+		/**
1658
+		 * Saving a model object.
1659
+		 * Before we perform a save, this action is fired.
1660
+		 *
1661
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1662
+		 */
1663
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1664
+		if ( ! $this->allow_persist()) {
1665
+			return 0;
1666
+		}
1667
+		//now get current attribute values
1668
+		$save_cols_n_values = $this->_fields;
1669
+		//if the object already has an ID, update it. Otherwise, insert it
1670
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1671
+		$old_assumption_concerning_value_preparation = $model
1672
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1673
+		$model->assume_values_already_prepared_by_model_object(true);
1674
+		//does this model have an autoincrement PK?
1675
+		if ($model->has_primary_key_field()) {
1676
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1677
+				//ok check if it's set, if so: update; if not, insert
1678
+				if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1679
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1680
+				} else {
1681
+					unset($save_cols_n_values[$model->primary_key_name()]);
1682
+					$results = $model->insert($save_cols_n_values);
1683
+					if ($results) {
1684
+						//if successful, set the primary key
1685
+						//but don't use the normal SET method, because it will check if
1686
+						//an item with the same ID exists in the mapper & db, then
1687
+						//will find it in the db (because we just added it) and THAT object
1688
+						//will get added to the mapper before we can add this one!
1689
+						//but if we just avoid using the SET method, all that headache can be avoided
1690
+						$pk_field_name = $model->primary_key_name();
1691
+						$this->_fields[$pk_field_name] = $results;
1692
+						$this->_clear_cached_property($pk_field_name);
1693
+						$model->add_to_entity_map($this);
1694
+						$this->_update_cached_related_model_objs_fks();
1695
+					}
1696
+				}
1697
+			} else {//PK is NOT auto-increment
1698
+				//so check if one like it already exists in the db
1699
+				if ($model->exists_by_ID($this->ID())) {
1700
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1701
+						throw new EE_Error(
1702
+							sprintf(
1703
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1704
+									'event_espresso'),
1705
+								get_class($this),
1706
+								get_class($model) . '::instance()->add_to_entity_map()',
1707
+								get_class($model) . '::instance()->get_one_by_ID()',
1708
+								'<br />'
1709
+							)
1710
+						);
1711
+					}
1712
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1713
+				} else {
1714
+					$results = $model->insert($save_cols_n_values);
1715
+					$this->_update_cached_related_model_objs_fks();
1716
+				}
1717
+			}
1718
+		} else {//there is NO primary key
1719
+			$already_in_db = false;
1720
+			foreach ($model->unique_indexes() as $index) {
1721
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1722
+				if ($model->exists(array($uniqueness_where_params))) {
1723
+					$already_in_db = true;
1724
+				}
1725
+			}
1726
+			if ($already_in_db) {
1727
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1728
+					$model->get_combined_primary_key_fields());
1729
+				$results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1730
+			} else {
1731
+				$results = $model->insert($save_cols_n_values);
1732
+			}
1733
+		}
1734
+		//restore the old assumption about values being prepared by the model object
1735
+		$model
1736
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1737
+		/**
1738
+		 * After saving the model object this action is called
1739
+		 *
1740
+		 * @param EE_Base_Class $model_object which was just saved
1741
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1742
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1743
+		 */
1744
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1745
+		$this->_has_changes = false;
1746
+		return $results;
1747
+	}
1748
+
1749
+
1750
+
1751
+	/**
1752
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1753
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1754
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1755
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1756
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1757
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1758
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1759
+	 *
1760
+	 * @return void
1761
+	 * @throws \EE_Error
1762
+	 */
1763
+	protected function _update_cached_related_model_objs_fks()
1764
+	{
1765
+		$model = $this->get_model();
1766
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1767
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1768
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1769
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1770
+						$model->get_this_model_name()
1771
+					);
1772
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1773
+					if ($related_model_obj_in_cache->ID()) {
1774
+						$related_model_obj_in_cache->save();
1775
+					}
1776
+				}
1777
+			}
1778
+		}
1779
+	}
1780
+
1781
+
1782
+
1783
+	/**
1784
+	 * Saves this model object and its NEW cached relations to the database.
1785
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1786
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1787
+	 * because otherwise, there's a potential for infinite looping of saving
1788
+	 * Saves the cached related model objects, and ensures the relation between them
1789
+	 * and this object and properly setup
1790
+	 *
1791
+	 * @return int ID of new model object on save; 0 on failure+
1792
+	 * @throws \EE_Error
1793
+	 */
1794
+	public function save_new_cached_related_model_objs()
1795
+	{
1796
+		//make sure this has been saved
1797
+		if ( ! $this->ID()) {
1798
+			$id = $this->save();
1799
+		} else {
1800
+			$id = $this->ID();
1801
+		}
1802
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1803
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1804
+			if ($this->_model_relations[$relationName]) {
1805
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1806
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1807
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1808
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1809
+					//but ONLY if it DOES NOT exist in the DB
1810
+					/* @var $related_model_obj EE_Base_Class */
1811
+					$related_model_obj = $this->_model_relations[$relationName];
1812
+					//					if( ! $related_model_obj->ID()){
1813
+					$this->_add_relation_to($related_model_obj, $relationName);
1814
+					$related_model_obj->save_new_cached_related_model_objs();
1815
+					//					}
1816
+				} else {
1817
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1818
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1819
+						//but ONLY if it DOES NOT exist in the DB
1820
+						//						if( ! $related_model_obj->ID()){
1821
+						$this->_add_relation_to($related_model_obj, $relationName);
1822
+						$related_model_obj->save_new_cached_related_model_objs();
1823
+						//						}
1824
+					}
1825
+				}
1826
+			}
1827
+		}
1828
+		return $id;
1829
+	}
1830
+
1831
+
1832
+
1833
+	/**
1834
+	 * for getting a model while instantiated.
1835
+	 *
1836
+	 * @return \EEM_Base | \EEM_CPT_Base
1837
+	 */
1838
+	public function get_model()
1839
+	{
1840
+		if( ! $this->_model){
1841
+			$modelName = self::_get_model_classname(get_class($this));
1842
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1843
+		} else {
1844
+			$this->_model->set_timezone($this->_timezone);
1845
+		}
1846
+
1847
+		return $this->_model;
1848
+	}
1849
+
1850
+
1851
+
1852
+	/**
1853
+	 * @param $props_n_values
1854
+	 * @param $classname
1855
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1856
+	 * @throws \EE_Error
1857
+	 */
1858
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1859
+	{
1860
+		//TODO: will not work for Term_Relationships because they have no PK!
1861
+		$primary_id_ref = self::_get_primary_key_name($classname);
1862
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1863
+			$id = $props_n_values[$primary_id_ref];
1864
+			return self::_get_model($classname)->get_from_entity_map($id);
1865
+		}
1866
+		return false;
1867
+	}
1868
+
1869
+
1870
+
1871
+	/**
1872
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1873
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1874
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1875
+	 * we return false.
1876
+	 *
1877
+	 * @param  array  $props_n_values   incoming array of properties and their values
1878
+	 * @param  string $classname        the classname of the child class
1879
+	 * @param null    $timezone
1880
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1881
+	 *                                  date_format and the second value is the time format
1882
+	 * @return mixed (EE_Base_Class|bool)
1883
+	 * @throws \EE_Error
1884
+	 */
1885
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1886
+	{
1887
+		$existing = null;
1888
+		$model = self::_get_model($classname, $timezone);
1889
+		if ($model->has_primary_key_field()) {
1890
+			$primary_id_ref = self::_get_primary_key_name($classname);
1891
+			if (array_key_exists($primary_id_ref, $props_n_values)
1892
+				&& ! empty($props_n_values[$primary_id_ref])
1893
+			) {
1894
+				$existing = $model->get_one_by_ID(
1895
+					$props_n_values[$primary_id_ref]
1896
+				);
1897
+			}
1898
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1899
+			//no primary key on this model, but there's still a matching item in the DB
1900
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1901
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1902
+			);
1903
+		}
1904
+		if ($existing) {
1905
+			//set date formats if present before setting values
1906
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1907
+				$existing->set_date_format($date_formats[0]);
1908
+				$existing->set_time_format($date_formats[1]);
1909
+			} else {
1910
+				//set default formats for date and time
1911
+				$existing->set_date_format(get_option('date_format'));
1912
+				$existing->set_time_format(get_option('time_format'));
1913
+			}
1914
+			foreach ($props_n_values as $property => $field_value) {
1915
+				$existing->set($property, $field_value);
1916
+			}
1917
+			return $existing;
1918
+		} else {
1919
+			return false;
1920
+		}
1921
+	}
1922
+
1923
+
1924
+
1925
+	/**
1926
+	 * Gets the EEM_*_Model for this class
1927
+	 *
1928
+	 * @access public now, as this is more convenient
1929
+	 * @param      $classname
1930
+	 * @param null $timezone
1931
+	 * @throws EE_Error
1932
+	 * @return EEM_Base
1933
+	 */
1934
+	protected static function _get_model($classname, $timezone = null)
1935
+	{
1936
+		//find model for this class
1937
+		if ( ! $classname) {
1938
+			throw new EE_Error(
1939
+				sprintf(
1940
+					__(
1941
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1942
+						"event_espresso"
1943
+					),
1944
+					$classname
1945
+				)
1946
+			);
1947
+		}
1948
+		$modelName = self::_get_model_classname($classname);
1949
+		return self::_get_model_instance_with_name($modelName, $timezone);
1950
+	}
1951
+
1952
+
1953
+
1954
+	/**
1955
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1956
+	 *
1957
+	 * @param string $model_classname
1958
+	 * @param null   $timezone
1959
+	 * @return EEM_Base
1960
+	 */
1961
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1962
+	{
1963
+		$model_classname = str_replace('EEM_', '', $model_classname);
1964
+		$model = EE_Registry::instance()->load_model($model_classname);
1965
+		$model->set_timezone($timezone);
1966
+		return $model;
1967
+	}
1968
+
1969
+
1970
+
1971
+	/**
1972
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1973
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1974
+	 *
1975
+	 * @param null $model_name
1976
+	 * @return string like EEM_Attendee
1977
+	 */
1978
+	private static function _get_model_classname($model_name = null)
1979
+	{
1980
+		if (strpos($model_name, "EE_") === 0) {
1981
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1982
+		} else {
1983
+			$model_classname = "EEM_" . $model_name;
1984
+		}
1985
+		return $model_classname;
1986
+	}
1987
+
1988
+
1989
+
1990
+	/**
1991
+	 * returns the name of the primary key attribute
1992
+	 *
1993
+	 * @param null $classname
1994
+	 * @throws EE_Error
1995
+	 * @return string
1996
+	 */
1997
+	protected static function _get_primary_key_name($classname = null)
1998
+	{
1999
+		if ( ! $classname) {
2000
+			throw new EE_Error(
2001
+				sprintf(
2002
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
2003
+					$classname
2004
+				)
2005
+			);
2006
+		}
2007
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2008
+	}
2009
+
2010
+
2011
+
2012
+	/**
2013
+	 * Gets the value of the primary key.
2014
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2015
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2016
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2017
+	 *
2018
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2019
+	 * @throws \EE_Error
2020
+	 */
2021
+	public function ID()
2022
+	{
2023
+		$model = $this->get_model();
2024
+		//now that we know the name of the variable, use a variable variable to get its value and return its
2025
+		if ($model->has_primary_key_field()) {
2026
+			return $this->_fields[$model->primary_key_name()];
2027
+		} else {
2028
+			return $model->get_index_primary_key_string($this->_fields);
2029
+		}
2030
+	}
2031
+
2032
+
2033
+
2034
+	/**
2035
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2036
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2037
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2038
+	 *
2039
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2040
+	 * @param string $relationName                     eg 'Events','Question',etc.
2041
+	 *                                                 an attendee to a group, you also want to specify which role they
2042
+	 *                                                 will have in that group. So you would use this parameter to
2043
+	 *                                                 specify array('role-column-name'=>'role-id')
2044
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2045
+	 *                                                 allow you to further constrict the relation to being added.
2046
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2047
+	 *                                                 column on the JOIN table and currently only the HABTM models
2048
+	 *                                                 accept these additional conditions.  Also remember that if an
2049
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2050
+	 *                                                 NEW row is created in the join table.
2051
+	 * @param null   $cache_id
2052
+	 * @throws EE_Error
2053
+	 * @return EE_Base_Class the object the relation was added to
2054
+	 */
2055
+	public function _add_relation_to(
2056
+		$otherObjectModelObjectOrID,
2057
+		$relationName,
2058
+		$extra_join_model_fields_n_values = array(),
2059
+		$cache_id = null
2060
+	) {
2061
+		$model = $this->get_model();
2062
+		//if this thing exists in the DB, save the relation to the DB
2063
+		if ($this->ID()) {
2064
+			$otherObject = $model
2065
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2066
+									$extra_join_model_fields_n_values);
2067
+			//clear cache so future get_many_related and get_first_related() return new results.
2068
+			$this->clear_cache($relationName, $otherObject, true);
2069
+			if ($otherObject instanceof EE_Base_Class) {
2070
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2071
+			}
2072
+		} else {
2073
+			//this thing doesn't exist in the DB,  so just cache it
2074
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2075
+				throw new EE_Error(sprintf(
2076
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2077
+						'event_espresso'),
2078
+					$otherObjectModelObjectOrID,
2079
+					get_class($this)
2080
+				));
2081
+			} else {
2082
+				$otherObject = $otherObjectModelObjectOrID;
2083
+			}
2084
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2085
+		}
2086
+		if ($otherObject instanceof EE_Base_Class) {
2087
+			//fix the reciprocal relation too
2088
+			if ($otherObject->ID()) {
2089
+				//its saved so assumed relations exist in the DB, so we can just
2090
+				//clear the cache so future queries use the updated info in the DB
2091
+				$otherObject->clear_cache($model->get_this_model_name(), null, true);
2092
+			} else {
2093
+				//it's not saved, so it caches relations like this
2094
+				$otherObject->cache($model->get_this_model_name(), $this);
2095
+			}
2096
+		}
2097
+		return $otherObject;
2098
+	}
2099
+
2100
+
2101
+
2102
+	/**
2103
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2104
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2105
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2106
+	 * from the cache
2107
+	 *
2108
+	 * @param mixed  $otherObjectModelObjectOrID
2109
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2110
+	 *                to the DB yet
2111
+	 * @param string $relationName
2112
+	 * @param array  $where_query
2113
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2114
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2115
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2116
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2117
+	 *                created in the join table.
2118
+	 * @return EE_Base_Class the relation was removed from
2119
+	 * @throws \EE_Error
2120
+	 */
2121
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2122
+	{
2123
+		if ($this->ID()) {
2124
+			//if this exists in the DB, save the relation change to the DB too
2125
+			$otherObject = $this->get_model()
2126
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2127
+									$where_query);
2128
+			$this->clear_cache($relationName, $otherObject);
2129
+		} else {
2130
+			//this doesn't exist in the DB, just remove it from the cache
2131
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2132
+		}
2133
+		if ($otherObject instanceof EE_Base_Class) {
2134
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2135
+		}
2136
+		return $otherObject;
2137
+	}
2138
+
2139
+
2140
+
2141
+	/**
2142
+	 * Removes ALL the related things for the $relationName.
2143
+	 *
2144
+	 * @param string $relationName
2145
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2146
+	 * @return EE_Base_Class
2147
+	 * @throws \EE_Error
2148
+	 */
2149
+	public function _remove_relations($relationName, $where_query_params = array())
2150
+	{
2151
+		if ($this->ID()) {
2152
+			//if this exists in the DB, save the relation change to the DB too
2153
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2154
+			$this->clear_cache($relationName, null, true);
2155
+		} else {
2156
+			//this doesn't exist in the DB, just remove it from the cache
2157
+			$otherObjects = $this->clear_cache($relationName, null, true);
2158
+		}
2159
+		if (is_array($otherObjects)) {
2160
+			foreach ($otherObjects as $otherObject) {
2161
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2162
+			}
2163
+		}
2164
+		return $otherObjects;
2165
+	}
2166
+
2167
+
2168
+
2169
+	/**
2170
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2171
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2172
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2173
+	 * because we want to get even deleted items etc.
2174
+	 *
2175
+	 * @param string $relationName key in the model's _model_relations array
2176
+	 * @param array  $query_params like EEM_Base::get_all
2177
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2178
+	 * @throws \EE_Error
2179
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2180
+	 *                             you want IDs
2181
+	 */
2182
+	public function get_many_related($relationName, $query_params = array())
2183
+	{
2184
+		if ($this->ID()) {
2185
+			//this exists in the DB, so get the related things from either the cache or the DB
2186
+			//if there are query parameters, forget about caching the related model objects.
2187
+			if ($query_params) {
2188
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2189
+			} else {
2190
+				//did we already cache the result of this query?
2191
+				$cached_results = $this->get_all_from_cache($relationName);
2192
+				if ( ! $cached_results) {
2193
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2194
+					//if no query parameters were passed, then we got all the related model objects
2195
+					//for that relation. We can cache them then.
2196
+					foreach ($related_model_objects as $related_model_object) {
2197
+						$this->cache($relationName, $related_model_object);
2198
+					}
2199
+				} else {
2200
+					$related_model_objects = $cached_results;
2201
+				}
2202
+			}
2203
+		} else {
2204
+			//this doesn't exist in the DB, so just get the related things from the cache
2205
+			$related_model_objects = $this->get_all_from_cache($relationName);
2206
+		}
2207
+		return $related_model_objects;
2208
+	}
2209
+
2210
+
2211
+
2212
+	/**
2213
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2214
+	 * unless otherwise specified in the $query_params
2215
+	 *
2216
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2217
+	 * @param array  $query_params   like EEM_Base::get_all's
2218
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2219
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2220
+	 *                               that by the setting $distinct to TRUE;
2221
+	 * @return int
2222
+	 */
2223
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2224
+	{
2225
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2226
+	}
2227
+
2228
+
2229
+
2230
+	/**
2231
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2232
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2233
+	 *
2234
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2235
+	 * @param array  $query_params  like EEM_Base::get_all's
2236
+	 * @param string $field_to_sum  name of field to count by.
2237
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2238
+	 *                              change it)
2239
+	 * @return int
2240
+	 */
2241
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2242
+	{
2243
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * Gets the first (ie, one) related model object of the specified type.
2250
+	 *
2251
+	 * @param string $relationName key in the model's _model_relations array
2252
+	 * @param array  $query_params like EEM_Base::get_all
2253
+	 * @return EE_Base_Class (not an array, a single object)
2254
+	 * @throws \EE_Error
2255
+	 */
2256
+	public function get_first_related($relationName, $query_params = array())
2257
+	{
2258
+		$model = $this->get_model();
2259
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2260
+			//if they've provided some query parameters, don't bother trying to cache the result
2261
+			//also make sure we're not caching the result of get_first_related
2262
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2263
+			if ($query_params
2264
+				|| ! $model->related_settings_for($relationName)
2265
+					 instanceof
2266
+					 EE_Belongs_To_Relation
2267
+			) {
2268
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2269
+			} else {
2270
+				//first, check if we've already cached the result of this query
2271
+				$cached_result = $this->get_one_from_cache($relationName);
2272
+				if ( ! $cached_result) {
2273
+					$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2274
+					$this->cache($relationName, $related_model_object);
2275
+				} else {
2276
+					$related_model_object = $cached_result;
2277
+				}
2278
+			}
2279
+		} else {
2280
+			$related_model_object = null;
2281
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2282
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2283
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2284
+			}
2285
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2286
+			if ( ! $related_model_object) {
2287
+				$related_model_object = $this->get_one_from_cache($relationName);
2288
+			}
2289
+		}
2290
+		return $related_model_object;
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Does a delete on all related objects of type $relationName and removes
2297
+	 * the current model object's relation to them. If they can't be deleted (because
2298
+	 * of blocking related model objects) does nothing. If the related model objects are
2299
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2300
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2301
+	 *
2302
+	 * @param string $relationName
2303
+	 * @param array  $query_params like EEM_Base::get_all's
2304
+	 * @return int how many deleted
2305
+	 * @throws \EE_Error
2306
+	 */
2307
+	public function delete_related($relationName, $query_params = array())
2308
+	{
2309
+		if ($this->ID()) {
2310
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2311
+		} else {
2312
+			$count = count($this->get_all_from_cache($relationName));
2313
+			$this->clear_cache($relationName, null, true);
2314
+		}
2315
+		return $count;
2316
+	}
2317
+
2318
+
2319
+
2320
+	/**
2321
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2322
+	 * the current model object's relation to them. If they can't be deleted (because
2323
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2324
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2325
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2326
+	 *
2327
+	 * @param string $relationName
2328
+	 * @param array  $query_params like EEM_Base::get_all's
2329
+	 * @return int how many deleted (including those soft deleted)
2330
+	 * @throws \EE_Error
2331
+	 */
2332
+	public function delete_related_permanently($relationName, $query_params = array())
2333
+	{
2334
+		if ($this->ID()) {
2335
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2336
+		} else {
2337
+			$count = count($this->get_all_from_cache($relationName));
2338
+		}
2339
+		$this->clear_cache($relationName, null, true);
2340
+		return $count;
2341
+	}
2342
+
2343
+
2344
+
2345
+	/**
2346
+	 * is_set
2347
+	 * Just a simple utility function children can use for checking if property exists
2348
+	 *
2349
+	 * @access  public
2350
+	 * @param  string $field_name property to check
2351
+	 * @return bool                              TRUE if existing,FALSE if not.
2352
+	 */
2353
+	public function is_set($field_name)
2354
+	{
2355
+		return isset($this->_fields[$field_name]);
2356
+	}
2357
+
2358
+
2359
+
2360
+	/**
2361
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2362
+	 * EE_Error exception if they don't
2363
+	 *
2364
+	 * @param  mixed (string|array) $properties properties to check
2365
+	 * @throws EE_Error
2366
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2367
+	 */
2368
+	protected function _property_exists($properties)
2369
+	{
2370
+		foreach ((array)$properties as $property_name) {
2371
+			//first make sure this property exists
2372
+			if ( ! $this->_fields[$property_name]) {
2373
+				throw new EE_Error(
2374
+					sprintf(
2375
+						__(
2376
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2377
+							'event_espresso'
2378
+						),
2379
+						$property_name
2380
+					)
2381
+				);
2382
+			}
2383
+		}
2384
+		return true;
2385
+	}
2386
+
2387
+
2388
+
2389
+	/**
2390
+	 * This simply returns an array of model fields for this object
2391
+	 *
2392
+	 * @return array
2393
+	 * @throws \EE_Error
2394
+	 */
2395
+	public function model_field_array()
2396
+	{
2397
+		$fields = $this->get_model()->field_settings(false);
2398
+		$properties = array();
2399
+		//remove prepended underscore
2400
+		foreach ($fields as $field_name => $settings) {
2401
+			$properties[$field_name] = $this->get($field_name);
2402
+		}
2403
+		return $properties;
2404
+	}
2405
+
2406
+
2407
+
2408
+	/**
2409
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2410
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2411
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2412
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2413
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2414
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2415
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2416
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2417
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2418
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2419
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2420
+	 *        return $previousReturnValue.$returnString;
2421
+	 * }
2422
+	 * require('EE_Answer.class.php');
2423
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2424
+	 * echo $answer->my_callback('monkeys',100);
2425
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2426
+	 *
2427
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2428
+	 * @param array  $args       array of original arguments passed to the function
2429
+	 * @throws EE_Error
2430
+	 * @return mixed whatever the plugin which calls add_filter decides
2431
+	 */
2432
+	public function __call($methodName, $args)
2433
+	{
2434
+		$className = get_class($this);
2435
+		$tagName = "FHEE__{$className}__{$methodName}";
2436
+		if ( ! has_filter($tagName)) {
2437
+			throw new EE_Error(
2438
+				sprintf(
2439
+					__(
2440
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2441
+						"event_espresso"
2442
+					),
2443
+					$methodName,
2444
+					$className,
2445
+					$tagName
2446
+				)
2447
+			);
2448
+		}
2449
+		return apply_filters($tagName, null, $this, $args);
2450
+	}
2451
+
2452
+
2453
+
2454
+	/**
2455
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2456
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2457
+	 *
2458
+	 * @param string $meta_key
2459
+	 * @param mixed  $meta_value
2460
+	 * @param mixed  $previous_value
2461
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2462
+	 * @throws \EE_Error
2463
+	 * NOTE: if the values haven't changed, returns 0
2464
+	 */
2465
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2466
+	{
2467
+		$query_params = array(
2468
+			array(
2469
+				'EXM_key'  => $meta_key,
2470
+				'OBJ_ID'   => $this->ID(),
2471
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2472
+			),
2473
+		);
2474
+		if ($previous_value !== null) {
2475
+			$query_params[0]['EXM_value'] = $meta_value;
2476
+		}
2477
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2478
+		if ( ! $existing_rows_like_that) {
2479
+			return $this->add_extra_meta($meta_key, $meta_value);
2480
+		}
2481
+		foreach ($existing_rows_like_that as $existing_row) {
2482
+			$existing_row->save(array('EXM_value' => $meta_value));
2483
+		}
2484
+		return count($existing_rows_like_that);
2485
+	}
2486
+
2487
+
2488
+
2489
+	/**
2490
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2491
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2492
+	 * extra meta row was entered, false if not
2493
+	 *
2494
+	 * @param string  $meta_key
2495
+	 * @param mixed   $meta_value
2496
+	 * @param boolean $unique
2497
+	 * @return boolean
2498
+	 * @throws \EE_Error
2499
+	 */
2500
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2501
+	{
2502
+		if ($unique) {
2503
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2504
+				array(
2505
+					array(
2506
+						'EXM_key'  => $meta_key,
2507
+						'OBJ_ID'   => $this->ID(),
2508
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2509
+					),
2510
+				)
2511
+			);
2512
+			if ($existing_extra_meta) {
2513
+				return false;
2514
+			}
2515
+		}
2516
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2517
+			array(
2518
+				'EXM_key'   => $meta_key,
2519
+				'EXM_value' => $meta_value,
2520
+				'OBJ_ID'    => $this->ID(),
2521
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2522
+			)
2523
+		);
2524
+		$new_extra_meta->save();
2525
+		return true;
2526
+	}
2527
+
2528
+
2529
+
2530
+	/**
2531
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2532
+	 * is specified, only deletes extra meta records with that value.
2533
+	 *
2534
+	 * @param string $meta_key
2535
+	 * @param mixed  $meta_value
2536
+	 * @return int number of extra meta rows deleted
2537
+	 * @throws \EE_Error
2538
+	 */
2539
+	public function delete_extra_meta($meta_key, $meta_value = null)
2540
+	{
2541
+		$query_params = array(
2542
+			array(
2543
+				'EXM_key'  => $meta_key,
2544
+				'OBJ_ID'   => $this->ID(),
2545
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2546
+			),
2547
+		);
2548
+		if ($meta_value !== null) {
2549
+			$query_params[0]['EXM_value'] = $meta_value;
2550
+		}
2551
+		return EEM_Extra_Meta::instance()->delete($query_params);
2552
+	}
2553
+
2554
+
2555
+
2556
+	/**
2557
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2558
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2559
+	 * You can specify $default is case you haven't found the extra meta
2560
+	 *
2561
+	 * @param string  $meta_key
2562
+	 * @param boolean $single
2563
+	 * @param mixed   $default if we don't find anything, what should we return?
2564
+	 * @return mixed single value if $single; array if ! $single
2565
+	 * @throws \EE_Error
2566
+	 */
2567
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2568
+	{
2569
+		if ($single) {
2570
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2571
+			if ($result instanceof EE_Extra_Meta) {
2572
+				return $result->value();
2573
+			}
2574
+		} else {
2575
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2576
+			if ($results) {
2577
+				$values = array();
2578
+				foreach ($results as $result) {
2579
+					if ($result instanceof EE_Extra_Meta) {
2580
+						$values[$result->ID()] = $result->value();
2581
+					}
2582
+				}
2583
+				return $values;
2584
+			}
2585
+		}
2586
+		//if nothing discovered yet return default.
2587
+		return apply_filters(
2588
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2589
+			$default,
2590
+			$meta_key,
2591
+			$single,
2592
+			$this
2593
+			);
2594
+	}
2595
+
2596
+
2597
+
2598
+	/**
2599
+	 * Returns a simple array of all the extra meta associated with this model object.
2600
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2601
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2602
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2603
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2604
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2605
+	 * finally the extra meta's value as each sub-value. (eg
2606
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2607
+	 *
2608
+	 * @param boolean $one_of_each_key
2609
+	 * @return array
2610
+	 * @throws \EE_Error
2611
+	 */
2612
+	public function all_extra_meta_array($one_of_each_key = true)
2613
+	{
2614
+		$return_array = array();
2615
+		if ($one_of_each_key) {
2616
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2617
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2618
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2619
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2620
+				}
2621
+			}
2622
+		} else {
2623
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2624
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2625
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2626
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2627
+						$return_array[$extra_meta_obj->key()] = array();
2628
+					}
2629
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2630
+				}
2631
+			}
2632
+		}
2633
+		return $return_array;
2634
+	}
2635
+
2636
+
2637
+
2638
+	/**
2639
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2640
+	 *
2641
+	 * @return string
2642
+	 * @throws \EE_Error
2643
+	 */
2644
+	public function name()
2645
+	{
2646
+		//find a field that's not a text field
2647
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2648
+		if ($field_we_can_use) {
2649
+			return $this->get($field_we_can_use->get_name());
2650
+		} else {
2651
+			$first_few_properties = $this->model_field_array();
2652
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2653
+			$name_parts = array();
2654
+			foreach ($first_few_properties as $name => $value) {
2655
+				$name_parts[] = "$name:$value";
2656
+			}
2657
+			return implode(",", $name_parts);
2658
+		}
2659
+	}
2660
+
2661
+
2662
+
2663
+	/**
2664
+	 * in_entity_map
2665
+	 * Checks if this model object has been proven to already be in the entity map
2666
+	 *
2667
+	 * @return boolean
2668
+	 * @throws \EE_Error
2669
+	 */
2670
+	public function in_entity_map()
2671
+	{
2672
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2673
+			//well, if we looked, did we find it in the entity map?
2674
+			return true;
2675
+		} else {
2676
+			return false;
2677
+		}
2678
+	}
2679
+
2680
+
2681
+
2682
+	/**
2683
+	 * refresh_from_db
2684
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2685
+	 *
2686
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2687
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2688
+	 */
2689
+	public function refresh_from_db()
2690
+	{
2691
+		if ($this->ID() && $this->in_entity_map()) {
2692
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2693
+		} else {
2694
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2695
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2696
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2697
+			//absolutely nothing in it for this ID
2698
+			if (WP_DEBUG) {
2699
+				throw new EE_Error(
2700
+					sprintf(
2701
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2702
+							'event_espresso'),
2703
+						$this->ID(),
2704
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2705
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2706
+					)
2707
+				);
2708
+			}
2709
+		}
2710
+	}
2711
+
2712
+
2713
+
2714
+	/**
2715
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2716
+	 * (probably a bad assumption they have made, oh well)
2717
+	 *
2718
+	 * @return string
2719
+	 */
2720
+	public function __toString()
2721
+	{
2722
+		try {
2723
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2724
+		} catch (Exception $e) {
2725
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2726
+			return '';
2727
+		}
2728
+	}
2729
+
2730
+
2731
+
2732
+	/**
2733
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2734
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2735
+	 * This means if we have made changes to those related model objects, and want to unserialize
2736
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2737
+	 * Instead, those related model objects should be directly serialized and stored.
2738
+	 * Eg, the following won't work:
2739
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2740
+	 * $att = $reg->attendee();
2741
+	 * $att->set( 'ATT_fname', 'Dirk' );
2742
+	 * update_option( 'my_option', serialize( $reg ) );
2743
+	 * //END REQUEST
2744
+	 * //START NEXT REQUEST
2745
+	 * $reg = get_option( 'my_option' );
2746
+	 * $reg->attendee()->save();
2747
+	 * And would need to be replace with:
2748
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2749
+	 * $att = $reg->attendee();
2750
+	 * $att->set( 'ATT_fname', 'Dirk' );
2751
+	 * update_option( 'my_option', serialize( $reg ) );
2752
+	 * //END REQUEST
2753
+	 * //START NEXT REQUEST
2754
+	 * $att = get_option( 'my_option' );
2755
+	 * $att->save();
2756
+	 *
2757
+	 * @return array
2758
+	 * @throws \EE_Error
2759
+	 */
2760
+	public function __sleep()
2761
+	{
2762
+		$model = $this->get_model();
2763
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2764
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2765
+				$classname = 'EE_' . $model->get_this_model_name();
2766
+				if (
2767
+					$this->get_one_from_cache($relation_name) instanceof $classname
2768
+					&& $this->get_one_from_cache($relation_name)->ID()
2769
+				) {
2770
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2771
+				}
2772
+			}
2773
+		}
2774
+		$this->_props_n_values_provided_in_constructor = array();
2775
+		$properties_to_serialize = get_object_vars($this);
2776
+		//don't serialize the model. It's big and that risks recursion
2777
+		unset($properties_to_serialize['_model']);
2778
+		return array_keys($properties_to_serialize);
2779
+	}
2780
+
2781
+
2782
+
2783
+	/**
2784
+	 * restore _props_n_values_provided_in_constructor
2785
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2786
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2787
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2788
+	 */
2789
+	public function __wakeup()
2790
+	{
2791
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2792
+	}
2793 2793
 
2794 2794
 
2795 2795
 
Please login to merge, or discard this patch.
core/domain/values/model/CustomSelects.php 2 patches
Indentation   +322 added lines, -322 removed lines patch added patch discarded remove patch
@@ -14,326 +14,326 @@
 block discarded – undo
14 14
  */
15 15
 class CustomSelects
16 16
 {
17
-    const TYPE_SIMPLE = 'simple';
18
-    const TYPE_COMPLEX = 'complex';
19
-    const TYPE_STRUCTURED = 'structured';
20
-
21
-    private $valid_operators = array('COUNT', 'SUM');
22
-
23
-
24
-    /**
25
-     * Original incoming select array
26
-     * @var array
27
-     */
28
-    private $original_selects;
29
-
30
-    /**
31
-     * Select string that can be added to the query
32
-     * @var string
33
-     */
34
-    private $columns_to_select_expression;
35
-
36
-
37
-    /**
38
-     * An array of aliases for the columns included in the incoming select array.
39
-     * @var array
40
-     */
41
-    private $column_aliases_in_select;
42
-
43
-
44
-    /**
45
-     * Enum representation of the "type" of array coming into this value object.
46
-     * @var string
47
-     *
48
-     */
49
-    private $type = '';
50
-
51
-
52
-    /**
53
-     * CustomSelects constructor.
54
-     * Incoming selects can be in one of the following formats:
55
-     * ---- self::TYPE_SIMPLE array ----
56
-     * This is considered the "simple" type. In this case the array is an numerically indexed array with single or
57
-     * multiple columns to select as the values.
58
-     * eg. array( 'ATT_ID', 'REG_ID' )
59
-     * eg. array( '*' )
60
-     * If you want to use the columns in any WHERE, GROUP BY, or HAVING clauses, you must instead use the "complex" or
61
-     * "structured" method.
62
-     * ---- self::TYPE_COMPLEX array ----
63
-     * This is considered the "complex" type.  In this case the array is indexed by arbitrary strings that serve as
64
-     * column alias, and the value is an numerically indexed array where there are two values.  The first value (0) is
65
-     * the selection and the second value (1) is the data type.  Data types must be one of the types defined in
66
-     * EEM_Base::$_valid_wpdb_data_types.
67
-     * eg. array( 'count' => array('count(REG_ID)', '%d') )
68
-     * Complex array configuration allows for using the column alias in any WHERE, GROUP BY, or HAVING clauses.
69
-     * ---- self::TYPE_STRUCTURED array ---
70
-     * This is considered the "structured" type. This type is similar to the complex type except that the array attached
71
-     * to the column alias contains three values.  The first value is the qualified column name (which can include
72
-     * join syntax for models).  The second value is the operator performed on the column (i.e. 'COUNT', 'SUM' etc).,
73
-     * the third value is the data type.  Note, if the select does not have an operator, you can use an empty string for
74
-     * the second value.
75
-     * Note: for now SUM is only for simple single column expressions (i.e. SUM(Transaction.TXN_total))
76
-     * eg. array( 'registration_count' => array('Registration.REG_ID', 'count', '%d') );
77
-     *
78
-     * NOTE: mixing array types in the incoming $select will cause errors.
79
-     *
80
-     * @param array $selects
81
-     * @throws InvalidArgumentException
82
-     */
83
-    public function __construct(array $selects)
84
-    {
85
-        $this->original_selects = $selects;
86
-        $this->deriveType($selects);
87
-        $this->deriveParts($selects);
88
-    }
89
-
90
-
91
-    /**
92
-     * Derives what type of custom select has been sent in.
93
-     * @param array $selects
94
-     * @throws InvalidArgumentException
95
-     */
96
-    private function deriveType(array $selects)
97
-    {
98
-        //first if the first key for this array is an integer then its coming in as a simple format, so we'll also
99
-        // ensure all elements of the array are simple.
100
-        if (is_int(key($selects))) {
101
-            //let's ensure all keys are ints
102
-            $invalid_keys = array_filter(
103
-                array_keys($selects),
104
-                function ($value) {
105
-                    return ! is_int($value);
106
-                }
107
-            );
108
-            if (! empty($invalid_keys)) {
109
-                throw new InvalidArgumentException(
110
-                    sprintf(
111
-                        esc_html__(
112
-                            'Incoming array looks like its formatted for "%1$s" type selects, however it has elements that are not indexed numerically',
113
-                            'event_espresso'
114
-                        ),
115
-                        self::TYPE_SIMPLE
116
-                    )
117
-                );
118
-            }
119
-            $this->type = self::TYPE_SIMPLE;
120
-            return;
121
-        }
122
-        //made it here so that means we've got either complex or structured selects.  Let's find out which by popping
123
-        //the first array element off.
124
-        $first_element = reset($selects);
125
-
126
-        if (! is_array($first_element)) {
127
-            throw new InvalidArgumentException(
128
-                sprintf(
129
-                    esc_html__(
130
-                        'Incoming array looks like its formatted as a "%1$s" or "%2$%s" type.  However, the values in the array must be arrays themselves and they are not.',
131
-                        'event_espresso'
132
-                    ),
133
-                    self::TYPE_COMPLEX,
134
-                    self::TYPE_STRUCTURED
135
-                )
136
-            );
137
-        }
138
-        $this->type = count($first_element) === 2
139
-            ? self::TYPE_COMPLEX
140
-            : self::TYPE_STRUCTURED;
141
-    }
142
-
143
-
144
-    /**
145
-     * Sets up the various properties for the vo depending on type.
146
-     * @param array $selects
147
-     * @throws InvalidArgumentException
148
-     */
149
-    private function deriveParts(array $selects)
150
-    {
151
-        $column_parts = array();
152
-        switch ($this->type) {
153
-            case self::TYPE_SIMPLE:
154
-                $column_parts = $selects;
155
-                $this->column_aliases_in_select = $selects;
156
-                break;
157
-            case self::TYPE_COMPLEX:
158
-                foreach ($selects as $alias => $parts) {
159
-                    $this->validateSelectValueForType($parts, $alias);
160
-                    $column_parts[] = "{$parts[0]} AS {$alias}";
161
-                    $this->column_aliases_in_select[] = $alias;
162
-                }
163
-                break;
164
-            case self::TYPE_STRUCTURED:
165
-                foreach ($selects as $alias => $parts) {
166
-                    $this->validateSelectValueForType($parts, $alias);
167
-                    $column_parts[] = $parts[1] !== ''
168
-                        ? $this->assembleSelectStringWithOperator($parts, $alias)
169
-                        : "{$parts[0]} AS {$alias}";
170
-                    $this->column_aliases_in_select[] = $alias;
171
-                }
172
-                break;
173
-        }
174
-        $this->columns_to_select_expression = implode(', ', $column_parts);
175
-    }
176
-
177
-
178
-    /**
179
-     * Validates self::TYPE_COMPLEX and self::TYPE_STRUCTURED select statement parts.
180
-     * @param array $select_parts
181
-     * @param string      $alias
182
-     * @throws InvalidArgumentException
183
-     */
184
-    private function validateSelectValueForType(array $select_parts, $alias)
185
-    {
186
-        $valid_data_types = array('%d', '%s', '%f');
187
-        if (count($select_parts) !== $this->expectedSelectPartCountForType()) {
188
-            throw new InvalidArgumentException(
189
-                sprintf(
190
-                    esc_html__(
191
-                        'The provided select part array for the %1$s column is expected to have a count of %2$d because the incoming select array is of type %3$s.  However the count was %4$d.',
192
-                        'event_espresso'
193
-                    ),
194
-                    $alias,
195
-                    $this->expectedSelectPartCountForType(),
196
-                    $this->type,
197
-                    count($select_parts)
198
-                )
199
-            );
200
-        }
201
-        //validate data type.
202
-        $data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
203
-        $data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
204
-
205
-        if (! in_array($data_type, $valid_data_types, true)) {
206
-            throw new InvalidArgumentException(
207
-                sprintf(
208
-                    esc_html__(
209
-                        'Datatype %1$s (for selection "%2$s" and alias "%3$s") is not a valid wpdb datatype (eg %%s)',
210
-                        'event_espresso'
211
-                    ),
212
-                    $data_type,
213
-                    $select_parts[0],
214
-                    $alias,
215
-                    implode(', ', $valid_data_types)
216
-                )
217
-            );
218
-        }
219
-    }
220
-
221
-
222
-    /**
223
-     * Each type will have an expected count of array elements, this returns what that expected count is.
224
-     * @param string $type
225
-     * @return int
226
-     */
227
-    private function expectedSelectPartCountForType($type = '') {
228
-        $type = $type === '' ? $this->type : $type;
229
-        $types_count_map = array(
230
-            self::TYPE_COMPLEX => 2,
231
-            self::TYPE_STRUCTURED => 3
232
-        );
233
-        return isset($types_count_map[$type]) ? $types_count_map[$type] : 0;
234
-    }
235
-
236
-
237
-    /**
238
-     * Prepares the select statement part for for structured type selects.
239
-     * @param array  $select_parts
240
-     * @param string $alias
241
-     * @return string
242
-     * @throws InvalidArgumentException
243
-     */
244
-    private function assembleSelectStringWithOperator(array $select_parts, $alias)
245
-    {
246
-        $operator = strtoupper($select_parts[1]);
247
-        //validate operator
248
-        if (! in_array($operator, $this->valid_operators, true)) {
249
-            throw new InvalidArgumentException(
250
-                sprintf(
251
-                    esc_html__(
252
-                        'An invalid operator has been provided (%1$s) for the column %2$s.  Valid operators must be one of the following: %3$s.',
253
-                        'event_espresso'
254
-                    ),
255
-                    $operator,
256
-                    $alias,
257
-                    implode(', ', $this->valid_operators)
258
-                )
259
-            );
260
-        }
261
-        return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
262
-    }
263
-
264
-
265
-    /**
266
-     * Return the datatype from the given select part.
267
-     * Remember the select_part has already been validated on object instantiation.
268
-     * @param array $select_part
269
-     * @return string
270
-     */
271
-    private function getDataTypeForSelectType(array $select_part)
272
-    {
273
-        switch ($this->type) {
274
-            case self::TYPE_COMPLEX:
275
-                return $select_part[1];
276
-            case self::TYPE_STRUCTURED:
277
-                return $select_part[2];
278
-            default:
279
-                return '';
280
-        }
281
-    }
282
-
283
-
284
-    /**
285
-     * Returns the original select array sent into the VO.
286
-     * @return array
287
-     */
288
-    public function originalSelects()
289
-    {
290
-        return $this->original_selects;
291
-    }
292
-
293
-
294
-    /**
295
-     * Returns the final assembled select expression derived from the incoming select array.
296
-     * @return string
297
-     */
298
-    public function columnsToSelectExpression()
299
-    {
300
-        return $this->columns_to_select_expression;
301
-    }
302
-
303
-
304
-    /**
305
-     * Returns all the column aliases derived from the incoming select array.
306
-     * @return array
307
-     */
308
-    public function columnAliases()
309
-    {
310
-        return $this->column_aliases_in_select;
311
-    }
312
-
313
-
314
-    /**
315
-     * Returns the enum type for the incoming select array.
316
-     * @return string
317
-     */
318
-    public function type()
319
-    {
320
-        return $this->type;
321
-    }
322
-
323
-
324
-
325
-    /**
326
-     * Return the datatype for the given column_alias
327
-     * @param string $column_alias
328
-     * @return string  (if there's no data type we return string as the default).
329
-     */
330
-    public function getDataTypeForAlias($column_alias)
331
-    {
332
-        if (isset($this->original_selects[$column_alias])
333
-            && in_array($column_alias, $this->columnAliases(), true)
334
-        ) {
335
-            return $this->getDataTypeForSelectType($this->original_selects[$column_alias]);
336
-        }
337
-        return '%s';
338
-    }
17
+	const TYPE_SIMPLE = 'simple';
18
+	const TYPE_COMPLEX = 'complex';
19
+	const TYPE_STRUCTURED = 'structured';
20
+
21
+	private $valid_operators = array('COUNT', 'SUM');
22
+
23
+
24
+	/**
25
+	 * Original incoming select array
26
+	 * @var array
27
+	 */
28
+	private $original_selects;
29
+
30
+	/**
31
+	 * Select string that can be added to the query
32
+	 * @var string
33
+	 */
34
+	private $columns_to_select_expression;
35
+
36
+
37
+	/**
38
+	 * An array of aliases for the columns included in the incoming select array.
39
+	 * @var array
40
+	 */
41
+	private $column_aliases_in_select;
42
+
43
+
44
+	/**
45
+	 * Enum representation of the "type" of array coming into this value object.
46
+	 * @var string
47
+	 *
48
+	 */
49
+	private $type = '';
50
+
51
+
52
+	/**
53
+	 * CustomSelects constructor.
54
+	 * Incoming selects can be in one of the following formats:
55
+	 * ---- self::TYPE_SIMPLE array ----
56
+	 * This is considered the "simple" type. In this case the array is an numerically indexed array with single or
57
+	 * multiple columns to select as the values.
58
+	 * eg. array( 'ATT_ID', 'REG_ID' )
59
+	 * eg. array( '*' )
60
+	 * If you want to use the columns in any WHERE, GROUP BY, or HAVING clauses, you must instead use the "complex" or
61
+	 * "structured" method.
62
+	 * ---- self::TYPE_COMPLEX array ----
63
+	 * This is considered the "complex" type.  In this case the array is indexed by arbitrary strings that serve as
64
+	 * column alias, and the value is an numerically indexed array where there are two values.  The first value (0) is
65
+	 * the selection and the second value (1) is the data type.  Data types must be one of the types defined in
66
+	 * EEM_Base::$_valid_wpdb_data_types.
67
+	 * eg. array( 'count' => array('count(REG_ID)', '%d') )
68
+	 * Complex array configuration allows for using the column alias in any WHERE, GROUP BY, or HAVING clauses.
69
+	 * ---- self::TYPE_STRUCTURED array ---
70
+	 * This is considered the "structured" type. This type is similar to the complex type except that the array attached
71
+	 * to the column alias contains three values.  The first value is the qualified column name (which can include
72
+	 * join syntax for models).  The second value is the operator performed on the column (i.e. 'COUNT', 'SUM' etc).,
73
+	 * the third value is the data type.  Note, if the select does not have an operator, you can use an empty string for
74
+	 * the second value.
75
+	 * Note: for now SUM is only for simple single column expressions (i.e. SUM(Transaction.TXN_total))
76
+	 * eg. array( 'registration_count' => array('Registration.REG_ID', 'count', '%d') );
77
+	 *
78
+	 * NOTE: mixing array types in the incoming $select will cause errors.
79
+	 *
80
+	 * @param array $selects
81
+	 * @throws InvalidArgumentException
82
+	 */
83
+	public function __construct(array $selects)
84
+	{
85
+		$this->original_selects = $selects;
86
+		$this->deriveType($selects);
87
+		$this->deriveParts($selects);
88
+	}
89
+
90
+
91
+	/**
92
+	 * Derives what type of custom select has been sent in.
93
+	 * @param array $selects
94
+	 * @throws InvalidArgumentException
95
+	 */
96
+	private function deriveType(array $selects)
97
+	{
98
+		//first if the first key for this array is an integer then its coming in as a simple format, so we'll also
99
+		// ensure all elements of the array are simple.
100
+		if (is_int(key($selects))) {
101
+			//let's ensure all keys are ints
102
+			$invalid_keys = array_filter(
103
+				array_keys($selects),
104
+				function ($value) {
105
+					return ! is_int($value);
106
+				}
107
+			);
108
+			if (! empty($invalid_keys)) {
109
+				throw new InvalidArgumentException(
110
+					sprintf(
111
+						esc_html__(
112
+							'Incoming array looks like its formatted for "%1$s" type selects, however it has elements that are not indexed numerically',
113
+							'event_espresso'
114
+						),
115
+						self::TYPE_SIMPLE
116
+					)
117
+				);
118
+			}
119
+			$this->type = self::TYPE_SIMPLE;
120
+			return;
121
+		}
122
+		//made it here so that means we've got either complex or structured selects.  Let's find out which by popping
123
+		//the first array element off.
124
+		$first_element = reset($selects);
125
+
126
+		if (! is_array($first_element)) {
127
+			throw new InvalidArgumentException(
128
+				sprintf(
129
+					esc_html__(
130
+						'Incoming array looks like its formatted as a "%1$s" or "%2$%s" type.  However, the values in the array must be arrays themselves and they are not.',
131
+						'event_espresso'
132
+					),
133
+					self::TYPE_COMPLEX,
134
+					self::TYPE_STRUCTURED
135
+				)
136
+			);
137
+		}
138
+		$this->type = count($first_element) === 2
139
+			? self::TYPE_COMPLEX
140
+			: self::TYPE_STRUCTURED;
141
+	}
142
+
143
+
144
+	/**
145
+	 * Sets up the various properties for the vo depending on type.
146
+	 * @param array $selects
147
+	 * @throws InvalidArgumentException
148
+	 */
149
+	private function deriveParts(array $selects)
150
+	{
151
+		$column_parts = array();
152
+		switch ($this->type) {
153
+			case self::TYPE_SIMPLE:
154
+				$column_parts = $selects;
155
+				$this->column_aliases_in_select = $selects;
156
+				break;
157
+			case self::TYPE_COMPLEX:
158
+				foreach ($selects as $alias => $parts) {
159
+					$this->validateSelectValueForType($parts, $alias);
160
+					$column_parts[] = "{$parts[0]} AS {$alias}";
161
+					$this->column_aliases_in_select[] = $alias;
162
+				}
163
+				break;
164
+			case self::TYPE_STRUCTURED:
165
+				foreach ($selects as $alias => $parts) {
166
+					$this->validateSelectValueForType($parts, $alias);
167
+					$column_parts[] = $parts[1] !== ''
168
+						? $this->assembleSelectStringWithOperator($parts, $alias)
169
+						: "{$parts[0]} AS {$alias}";
170
+					$this->column_aliases_in_select[] = $alias;
171
+				}
172
+				break;
173
+		}
174
+		$this->columns_to_select_expression = implode(', ', $column_parts);
175
+	}
176
+
177
+
178
+	/**
179
+	 * Validates self::TYPE_COMPLEX and self::TYPE_STRUCTURED select statement parts.
180
+	 * @param array $select_parts
181
+	 * @param string      $alias
182
+	 * @throws InvalidArgumentException
183
+	 */
184
+	private function validateSelectValueForType(array $select_parts, $alias)
185
+	{
186
+		$valid_data_types = array('%d', '%s', '%f');
187
+		if (count($select_parts) !== $this->expectedSelectPartCountForType()) {
188
+			throw new InvalidArgumentException(
189
+				sprintf(
190
+					esc_html__(
191
+						'The provided select part array for the %1$s column is expected to have a count of %2$d because the incoming select array is of type %3$s.  However the count was %4$d.',
192
+						'event_espresso'
193
+					),
194
+					$alias,
195
+					$this->expectedSelectPartCountForType(),
196
+					$this->type,
197
+					count($select_parts)
198
+				)
199
+			);
200
+		}
201
+		//validate data type.
202
+		$data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
203
+		$data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
204
+
205
+		if (! in_array($data_type, $valid_data_types, true)) {
206
+			throw new InvalidArgumentException(
207
+				sprintf(
208
+					esc_html__(
209
+						'Datatype %1$s (for selection "%2$s" and alias "%3$s") is not a valid wpdb datatype (eg %%s)',
210
+						'event_espresso'
211
+					),
212
+					$data_type,
213
+					$select_parts[0],
214
+					$alias,
215
+					implode(', ', $valid_data_types)
216
+				)
217
+			);
218
+		}
219
+	}
220
+
221
+
222
+	/**
223
+	 * Each type will have an expected count of array elements, this returns what that expected count is.
224
+	 * @param string $type
225
+	 * @return int
226
+	 */
227
+	private function expectedSelectPartCountForType($type = '') {
228
+		$type = $type === '' ? $this->type : $type;
229
+		$types_count_map = array(
230
+			self::TYPE_COMPLEX => 2,
231
+			self::TYPE_STRUCTURED => 3
232
+		);
233
+		return isset($types_count_map[$type]) ? $types_count_map[$type] : 0;
234
+	}
235
+
236
+
237
+	/**
238
+	 * Prepares the select statement part for for structured type selects.
239
+	 * @param array  $select_parts
240
+	 * @param string $alias
241
+	 * @return string
242
+	 * @throws InvalidArgumentException
243
+	 */
244
+	private function assembleSelectStringWithOperator(array $select_parts, $alias)
245
+	{
246
+		$operator = strtoupper($select_parts[1]);
247
+		//validate operator
248
+		if (! in_array($operator, $this->valid_operators, true)) {
249
+			throw new InvalidArgumentException(
250
+				sprintf(
251
+					esc_html__(
252
+						'An invalid operator has been provided (%1$s) for the column %2$s.  Valid operators must be one of the following: %3$s.',
253
+						'event_espresso'
254
+					),
255
+					$operator,
256
+					$alias,
257
+					implode(', ', $this->valid_operators)
258
+				)
259
+			);
260
+		}
261
+		return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
262
+	}
263
+
264
+
265
+	/**
266
+	 * Return the datatype from the given select part.
267
+	 * Remember the select_part has already been validated on object instantiation.
268
+	 * @param array $select_part
269
+	 * @return string
270
+	 */
271
+	private function getDataTypeForSelectType(array $select_part)
272
+	{
273
+		switch ($this->type) {
274
+			case self::TYPE_COMPLEX:
275
+				return $select_part[1];
276
+			case self::TYPE_STRUCTURED:
277
+				return $select_part[2];
278
+			default:
279
+				return '';
280
+		}
281
+	}
282
+
283
+
284
+	/**
285
+	 * Returns the original select array sent into the VO.
286
+	 * @return array
287
+	 */
288
+	public function originalSelects()
289
+	{
290
+		return $this->original_selects;
291
+	}
292
+
293
+
294
+	/**
295
+	 * Returns the final assembled select expression derived from the incoming select array.
296
+	 * @return string
297
+	 */
298
+	public function columnsToSelectExpression()
299
+	{
300
+		return $this->columns_to_select_expression;
301
+	}
302
+
303
+
304
+	/**
305
+	 * Returns all the column aliases derived from the incoming select array.
306
+	 * @return array
307
+	 */
308
+	public function columnAliases()
309
+	{
310
+		return $this->column_aliases_in_select;
311
+	}
312
+
313
+
314
+	/**
315
+	 * Returns the enum type for the incoming select array.
316
+	 * @return string
317
+	 */
318
+	public function type()
319
+	{
320
+		return $this->type;
321
+	}
322
+
323
+
324
+
325
+	/**
326
+	 * Return the datatype for the given column_alias
327
+	 * @param string $column_alias
328
+	 * @return string  (if there's no data type we return string as the default).
329
+	 */
330
+	public function getDataTypeForAlias($column_alias)
331
+	{
332
+		if (isset($this->original_selects[$column_alias])
333
+			&& in_array($column_alias, $this->columnAliases(), true)
334
+		) {
335
+			return $this->getDataTypeForSelectType($this->original_selects[$column_alias]);
336
+		}
337
+		return '%s';
338
+	}
339 339
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -101,11 +101,11 @@  discard block
 block discarded – undo
101 101
             //let's ensure all keys are ints
102 102
             $invalid_keys = array_filter(
103 103
                 array_keys($selects),
104
-                function ($value) {
104
+                function($value) {
105 105
                     return ! is_int($value);
106 106
                 }
107 107
             );
108
-            if (! empty($invalid_keys)) {
108
+            if ( ! empty($invalid_keys)) {
109 109
                 throw new InvalidArgumentException(
110 110
                     sprintf(
111 111
                         esc_html__(
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
         //the first array element off.
124 124
         $first_element = reset($selects);
125 125
 
126
-        if (! is_array($first_element)) {
126
+        if ( ! is_array($first_element)) {
127 127
             throw new InvalidArgumentException(
128 128
                 sprintf(
129 129
                     esc_html__(
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
         $data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
203 203
         $data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
204 204
 
205
-        if (! in_array($data_type, $valid_data_types, true)) {
205
+        if ( ! in_array($data_type, $valid_data_types, true)) {
206 206
             throw new InvalidArgumentException(
207 207
                 sprintf(
208 208
                     esc_html__(
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
     {
246 246
         $operator = strtoupper($select_parts[1]);
247 247
         //validate operator
248
-        if (! in_array($operator, $this->valid_operators, true)) {
248
+        if ( ! in_array($operator, $this->valid_operators, true)) {
249 249
             throw new InvalidArgumentException(
250 250
                 sprintf(
251 251
                     esc_html__(
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
                 )
259 259
             );
260 260
         }
261
-        return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
261
+        return $operator.'('.$select_parts[0].') AS '.$alias;
262 262
     }
263 263
 
264 264
 
Please login to merge, or discard this patch.