Completed
Branch FET-8385-datetime-ticket-selec... (304b56)
by
unknown
51:42 queued 39:36
created
core/EE_Cart.core.php 2 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
      * @access  public
261 261
      * @param EE_Ticket $ticket
262 262
      * @param int       $qty
263
-     * @return TRUE on success, FALSE on fail
263
+     * @return boolean on success, FALSE on fail
264 264
      * @throws \EE_Error
265 265
      */
266 266
     public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
      * @save   cart to session
386 386
      * @access public
387 387
      * @param bool $apply_taxes
388
-     * @return TRUE on success, FALSE on fail
388
+     * @return boolean on success, FALSE on fail
389 389
      * @throws \EE_Error
390 390
      */
391 391
     public function save_cart($apply_taxes = true)
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 
420 420
 
421 421
     /**
422
-     * @return array
422
+     * @return string[]
423 423
      */
424 424
     public function __sleep()
425 425
     {
Please login to merge, or discard this patch.
Indentation   +410 added lines, -410 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__, __FUNCTION__, '');
5 5
 
@@ -19,415 +19,415 @@  discard block
 block discarded – undo
19 19
 class EE_Cart
20 20
 {
21 21
 
22
-    /**
23
-     * instance of the EE_Cart object
24
-     *
25
-     * @access    private
26
-     * @var EE_Cart $_instance
27
-     */
28
-    private static $_instance;
29
-
30
-    /**
31
-     * instance of the EE_Session object
32
-     *
33
-     * @access    protected
34
-     * @var EE_Session $_session
35
-     */
36
-    protected $_session;
37
-
38
-    /**
39
-     * The total Line item which comprises all the children line-item subtotals,
40
-     * which in turn each have their line items.
41
-     * Typically, the line item structure will look like:
42
-     * grand total
43
-     * -tickets-sub-total
44
-     * --ticket1
45
-     * --ticket2
46
-     * --...
47
-     * -taxes-sub-total
48
-     * --tax1
49
-     * --tax2
50
-     *
51
-     * @var EE_Line_Item
52
-     */
53
-    private $_grand_total;
54
-
55
-
56
-
57
-    /**
58
-     * @singleton method used to instantiate class object
59
-     * @access    public
60
-     * @param EE_Line_Item $grand_total
61
-     * @param EE_Session   $session
62
-     * @return \EE_Cart
63
-     * @throws \EE_Error
64
-     */
65
-    public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
66
-    {
67
-        if ( ! empty($grand_total)) {
68
-            self::$_instance = new self($grand_total, $session);
69
-        }
70
-        // or maybe retrieve an existing one ?
71
-        if ( ! self::$_instance instanceof EE_Cart) {
72
-            // try getting the cart out of the session
73
-            $saved_cart = $session instanceof EE_Session ? $session->cart() : null;
74
-            self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
75
-            unset($saved_cart);
76
-        }
77
-        // verify that cart is ok and grand total line item exists
78
-        if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
79
-            self::$_instance = new self($grand_total, $session);
80
-        }
81
-        self::$_instance->get_grand_total();
82
-        // once everything is all said and done, save the cart to the EE_Session
83
-        add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
84
-        return self::$_instance;
85
-    }
86
-
87
-
88
-
89
-    /**
90
-     * private constructor to prevent direct creation
91
-     *
92
-     * @Constructor
93
-     * @access private
94
-     * @param EE_Line_Item $grand_total
95
-     * @param EE_Session   $session
96
-     */
97
-    private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
98
-    {
99
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
100
-        $this->set_session($session);
101
-        if ($grand_total instanceof EE_Line_Item) {
102
-            $this->set_grand_total_line_item($grand_total);
103
-        }
104
-    }
105
-
106
-
107
-
108
-    /**
109
-     * Resets the cart completely (whereas empty_cart
110
-     *
111
-     * @param EE_Line_Item $grand_total
112
-     * @param EE_Session   $session
113
-     * @return EE_Cart
114
-     * @throws \EE_Error
115
-     */
116
-    public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
117
-    {
118
-        remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
119
-        if ($session instanceof EE_Session) {
120
-            $session->reset_cart();
121
-        }
122
-        self::$_instance = null;
123
-        return self::instance($grand_total, $session);
124
-    }
125
-
126
-
127
-
128
-    /**
129
-     * @return \EE_Session
130
-     */
131
-    public function session()
132
-    {
133
-        if ( ! $this->_session instanceof EE_Session) {
134
-            $this->set_session();
135
-        }
136
-        return $this->_session;
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * @param EE_Session $session
143
-     */
144
-    public function set_session(EE_Session $session = null)
145
-    {
146
-        $this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * Sets the cart to match the line item. Especially handy for loading an old cart where you
153
-     *  know the grand total line item on it
154
-     *
155
-     * @param EE_Line_Item $line_item
156
-     */
157
-    public function set_grand_total_line_item(EE_Line_Item $line_item)
158
-    {
159
-        $this->_grand_total = $line_item;
160
-    }
161
-
162
-
163
-
164
-    /**
165
-     * get_cart_from_reg_url_link
166
-     *
167
-     * @access public
168
-     * @param EE_Transaction $transaction
169
-     * @param EE_Session     $session
170
-     * @return \EE_Cart
171
-     * @throws \EE_Error
172
-     */
173
-    public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
174
-    {
175
-        $grand_total = $transaction->total_line_item();
176
-        $grand_total->get_items();
177
-        $grand_total->tax_descendants();
178
-        return EE_Cart::instance($grand_total, $session);
179
-    }
180
-
181
-
182
-
183
-    /**
184
-     * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
185
-     *
186
-     * @return EE_Line_Item
187
-     * @throws \EE_Error
188
-     */
189
-    private function _create_grand_total()
190
-    {
191
-        $this->_grand_total = EEH_Line_Item::create_total_line_item();
192
-        return $this->_grand_total;
193
-    }
194
-
195
-
196
-
197
-    /**
198
-     * Gets all the line items of object type Ticket
199
-     *
200
-     * @access public
201
-     * @return \EE_Line_Item[]
202
-     */
203
-    public function get_tickets()
204
-    {
205
-        return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
206
-    }
207
-
208
-
209
-
210
-    /**
211
-     * returns the total quantity of tickets in the cart
212
-     *
213
-     * @access public
214
-     * @return int
215
-     * @throws \EE_Error
216
-     */
217
-    public function all_ticket_quantity_count()
218
-    {
219
-        $tickets = $this->get_tickets();
220
-        if (empty($tickets)) {
221
-            return 0;
222
-        }
223
-        $count = 0;
224
-        foreach ($tickets as $ticket) {
225
-            $count += $ticket->get('LIN_quantity');
226
-        }
227
-        return $count;
228
-    }
229
-
230
-
231
-
232
-    /**
233
-     * Gets all the tax line items
234
-     *
235
-     * @return \EE_Line_Item[]
236
-     * @throws \EE_Error
237
-     */
238
-    public function get_taxes()
239
-    {
240
-        return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
241
-    }
242
-
243
-
244
-
245
-    /**
246
-     * Gets the total line item (which is a parent of all other line items) on this cart
247
-     *
248
-     * @return EE_Line_Item
249
-     * @throws \EE_Error
250
-     */
251
-    public function get_grand_total()
252
-    {
253
-        return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
254
-    }
255
-
256
-
257
-
258
-    /**
259
-     * @process items for adding to cart
260
-     * @access  public
261
-     * @param EE_Ticket $ticket
262
-     * @param int       $qty
263
-     * @return TRUE on success, FALSE on fail
264
-     * @throws \EE_Error
265
-     */
266
-    public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
267
-    {
268
-        EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
269
-        return $this->save_cart() ? true : false;
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * get_cart_total_before_tax
276
-     *
277
-     * @access public
278
-     * @return float
279
-     * @throws \EE_Error
280
-     */
281
-    public function get_cart_total_before_tax()
282
-    {
283
-        return $this->get_grand_total()->recalculate_pre_tax_total();
284
-    }
285
-
286
-
287
-
288
-    /**
289
-     * gets the total amount of tax paid for items in this cart
290
-     *
291
-     * @access public
292
-     * @return float
293
-     * @throws \EE_Error
294
-     */
295
-    public function get_applied_taxes()
296
-    {
297
-        return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
298
-    }
299
-
300
-
301
-
302
-    /**
303
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
304
-     *
305
-     * @access public
306
-     * @return float
307
-     * @throws \EE_Error
308
-     */
309
-    public function get_cart_grand_total()
310
-    {
311
-        EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
312
-        return $this->get_grand_total()->total();
313
-    }
314
-
315
-
316
-
317
-    /**
318
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
319
-     *
320
-     * @access public
321
-     * @return float
322
-     * @throws \EE_Error
323
-     */
324
-    public function recalculate_all_cart_totals()
325
-    {
326
-        $pre_tax_total = $this->get_cart_total_before_tax();
327
-        $taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
328
-        $this->_grand_total->set_total($pre_tax_total + $taxes_total);
329
-        $this->_grand_total->save_this_and_descendants_to_txn();
330
-        return $this->get_grand_total()->total();
331
-    }
332
-
333
-
334
-
335
-    /**
336
-     * deletes an item from the cart
337
-     *
338
-     * @access public
339
-     * @param array|bool|string $line_item_codes
340
-     * @return int on success, FALSE on fail
341
-     * @throws \EE_Error
342
-     */
343
-    public function delete_items($line_item_codes = false)
344
-    {
345
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
346
-        return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
347
-    }
348
-
349
-
350
-
351
-    /**
352
-     * @remove ALL items from cart and zero ALL totals
353
-     * @access public
354
-     * @return bool
355
-     * @throws \EE_Error
356
-     */
357
-    public function empty_cart()
358
-    {
359
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
360
-        $this->_grand_total = $this->_create_grand_total();
361
-        return $this->save_cart(true);
362
-    }
363
-
364
-
365
-
366
-    /**
367
-     * @remove ALL items from cart and delete total as well
368
-     * @access public
369
-     * @return bool
370
-     * @throws \EE_Error
371
-     */
372
-    public function delete_cart()
373
-    {
374
-        $deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
375
-        if ($deleted) {
376
-            $deleted += $this->_grand_total->delete();
377
-            $this->_grand_total = null;
378
-        }
379
-        return $deleted;
380
-    }
381
-
382
-
383
-
384
-    /**
385
-     * @save   cart to session
386
-     * @access public
387
-     * @param bool $apply_taxes
388
-     * @return TRUE on success, FALSE on fail
389
-     * @throws \EE_Error
390
-     */
391
-    public function save_cart($apply_taxes = true)
392
-    {
393
-        if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
394
-            EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
395
-            //make sure we don't cache the transaction because it can get stale
396
-            if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
397
-                && $this->_grand_total->get_one_from_cache('Transaction')->ID()
398
-            ) {
399
-                $this->_grand_total->clear_cache('Transaction', null, true);
400
-            }
401
-        }
402
-        if ($this->session() instanceof EE_Session) {
403
-            return $this->session()->set_cart($this);
404
-        } else {
405
-            return false;
406
-        }
407
-    }
408
-
409
-
410
-
411
-    public function __wakeup()
412
-    {
413
-        if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
414
-            // $this->_grand_total is actually just an ID, so use it to get the object from the db
415
-            $this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
416
-        }
417
-    }
418
-
419
-
420
-
421
-    /**
422
-     * @return array
423
-     */
424
-    public function __sleep()
425
-    {
426
-        if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
427
-            $this->_grand_total = $this->_grand_total->ID();
428
-        }
429
-        return array('_grand_total');
430
-    }
22
+	/**
23
+	 * instance of the EE_Cart object
24
+	 *
25
+	 * @access    private
26
+	 * @var EE_Cart $_instance
27
+	 */
28
+	private static $_instance;
29
+
30
+	/**
31
+	 * instance of the EE_Session object
32
+	 *
33
+	 * @access    protected
34
+	 * @var EE_Session $_session
35
+	 */
36
+	protected $_session;
37
+
38
+	/**
39
+	 * The total Line item which comprises all the children line-item subtotals,
40
+	 * which in turn each have their line items.
41
+	 * Typically, the line item structure will look like:
42
+	 * grand total
43
+	 * -tickets-sub-total
44
+	 * --ticket1
45
+	 * --ticket2
46
+	 * --...
47
+	 * -taxes-sub-total
48
+	 * --tax1
49
+	 * --tax2
50
+	 *
51
+	 * @var EE_Line_Item
52
+	 */
53
+	private $_grand_total;
54
+
55
+
56
+
57
+	/**
58
+	 * @singleton method used to instantiate class object
59
+	 * @access    public
60
+	 * @param EE_Line_Item $grand_total
61
+	 * @param EE_Session   $session
62
+	 * @return \EE_Cart
63
+	 * @throws \EE_Error
64
+	 */
65
+	public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
66
+	{
67
+		if ( ! empty($grand_total)) {
68
+			self::$_instance = new self($grand_total, $session);
69
+		}
70
+		// or maybe retrieve an existing one ?
71
+		if ( ! self::$_instance instanceof EE_Cart) {
72
+			// try getting the cart out of the session
73
+			$saved_cart = $session instanceof EE_Session ? $session->cart() : null;
74
+			self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
75
+			unset($saved_cart);
76
+		}
77
+		// verify that cart is ok and grand total line item exists
78
+		if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
79
+			self::$_instance = new self($grand_total, $session);
80
+		}
81
+		self::$_instance->get_grand_total();
82
+		// once everything is all said and done, save the cart to the EE_Session
83
+		add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
84
+		return self::$_instance;
85
+	}
86
+
87
+
88
+
89
+	/**
90
+	 * private constructor to prevent direct creation
91
+	 *
92
+	 * @Constructor
93
+	 * @access private
94
+	 * @param EE_Line_Item $grand_total
95
+	 * @param EE_Session   $session
96
+	 */
97
+	private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
98
+	{
99
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
100
+		$this->set_session($session);
101
+		if ($grand_total instanceof EE_Line_Item) {
102
+			$this->set_grand_total_line_item($grand_total);
103
+		}
104
+	}
105
+
106
+
107
+
108
+	/**
109
+	 * Resets the cart completely (whereas empty_cart
110
+	 *
111
+	 * @param EE_Line_Item $grand_total
112
+	 * @param EE_Session   $session
113
+	 * @return EE_Cart
114
+	 * @throws \EE_Error
115
+	 */
116
+	public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
117
+	{
118
+		remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
119
+		if ($session instanceof EE_Session) {
120
+			$session->reset_cart();
121
+		}
122
+		self::$_instance = null;
123
+		return self::instance($grand_total, $session);
124
+	}
125
+
126
+
127
+
128
+	/**
129
+	 * @return \EE_Session
130
+	 */
131
+	public function session()
132
+	{
133
+		if ( ! $this->_session instanceof EE_Session) {
134
+			$this->set_session();
135
+		}
136
+		return $this->_session;
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * @param EE_Session $session
143
+	 */
144
+	public function set_session(EE_Session $session = null)
145
+	{
146
+		$this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * Sets the cart to match the line item. Especially handy for loading an old cart where you
153
+	 *  know the grand total line item on it
154
+	 *
155
+	 * @param EE_Line_Item $line_item
156
+	 */
157
+	public function set_grand_total_line_item(EE_Line_Item $line_item)
158
+	{
159
+		$this->_grand_total = $line_item;
160
+	}
161
+
162
+
163
+
164
+	/**
165
+	 * get_cart_from_reg_url_link
166
+	 *
167
+	 * @access public
168
+	 * @param EE_Transaction $transaction
169
+	 * @param EE_Session     $session
170
+	 * @return \EE_Cart
171
+	 * @throws \EE_Error
172
+	 */
173
+	public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
174
+	{
175
+		$grand_total = $transaction->total_line_item();
176
+		$grand_total->get_items();
177
+		$grand_total->tax_descendants();
178
+		return EE_Cart::instance($grand_total, $session);
179
+	}
180
+
181
+
182
+
183
+	/**
184
+	 * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
185
+	 *
186
+	 * @return EE_Line_Item
187
+	 * @throws \EE_Error
188
+	 */
189
+	private function _create_grand_total()
190
+	{
191
+		$this->_grand_total = EEH_Line_Item::create_total_line_item();
192
+		return $this->_grand_total;
193
+	}
194
+
195
+
196
+
197
+	/**
198
+	 * Gets all the line items of object type Ticket
199
+	 *
200
+	 * @access public
201
+	 * @return \EE_Line_Item[]
202
+	 */
203
+	public function get_tickets()
204
+	{
205
+		return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
206
+	}
207
+
208
+
209
+
210
+	/**
211
+	 * returns the total quantity of tickets in the cart
212
+	 *
213
+	 * @access public
214
+	 * @return int
215
+	 * @throws \EE_Error
216
+	 */
217
+	public function all_ticket_quantity_count()
218
+	{
219
+		$tickets = $this->get_tickets();
220
+		if (empty($tickets)) {
221
+			return 0;
222
+		}
223
+		$count = 0;
224
+		foreach ($tickets as $ticket) {
225
+			$count += $ticket->get('LIN_quantity');
226
+		}
227
+		return $count;
228
+	}
229
+
230
+
231
+
232
+	/**
233
+	 * Gets all the tax line items
234
+	 *
235
+	 * @return \EE_Line_Item[]
236
+	 * @throws \EE_Error
237
+	 */
238
+	public function get_taxes()
239
+	{
240
+		return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
241
+	}
242
+
243
+
244
+
245
+	/**
246
+	 * Gets the total line item (which is a parent of all other line items) on this cart
247
+	 *
248
+	 * @return EE_Line_Item
249
+	 * @throws \EE_Error
250
+	 */
251
+	public function get_grand_total()
252
+	{
253
+		return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
254
+	}
255
+
256
+
257
+
258
+	/**
259
+	 * @process items for adding to cart
260
+	 * @access  public
261
+	 * @param EE_Ticket $ticket
262
+	 * @param int       $qty
263
+	 * @return TRUE on success, FALSE on fail
264
+	 * @throws \EE_Error
265
+	 */
266
+	public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
267
+	{
268
+		EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
269
+		return $this->save_cart() ? true : false;
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * get_cart_total_before_tax
276
+	 *
277
+	 * @access public
278
+	 * @return float
279
+	 * @throws \EE_Error
280
+	 */
281
+	public function get_cart_total_before_tax()
282
+	{
283
+		return $this->get_grand_total()->recalculate_pre_tax_total();
284
+	}
285
+
286
+
287
+
288
+	/**
289
+	 * gets the total amount of tax paid for items in this cart
290
+	 *
291
+	 * @access public
292
+	 * @return float
293
+	 * @throws \EE_Error
294
+	 */
295
+	public function get_applied_taxes()
296
+	{
297
+		return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
298
+	}
299
+
300
+
301
+
302
+	/**
303
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
304
+	 *
305
+	 * @access public
306
+	 * @return float
307
+	 * @throws \EE_Error
308
+	 */
309
+	public function get_cart_grand_total()
310
+	{
311
+		EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
312
+		return $this->get_grand_total()->total();
313
+	}
314
+
315
+
316
+
317
+	/**
318
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
319
+	 *
320
+	 * @access public
321
+	 * @return float
322
+	 * @throws \EE_Error
323
+	 */
324
+	public function recalculate_all_cart_totals()
325
+	{
326
+		$pre_tax_total = $this->get_cart_total_before_tax();
327
+		$taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
328
+		$this->_grand_total->set_total($pre_tax_total + $taxes_total);
329
+		$this->_grand_total->save_this_and_descendants_to_txn();
330
+		return $this->get_grand_total()->total();
331
+	}
332
+
333
+
334
+
335
+	/**
336
+	 * deletes an item from the cart
337
+	 *
338
+	 * @access public
339
+	 * @param array|bool|string $line_item_codes
340
+	 * @return int on success, FALSE on fail
341
+	 * @throws \EE_Error
342
+	 */
343
+	public function delete_items($line_item_codes = false)
344
+	{
345
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
346
+		return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
347
+	}
348
+
349
+
350
+
351
+	/**
352
+	 * @remove ALL items from cart and zero ALL totals
353
+	 * @access public
354
+	 * @return bool
355
+	 * @throws \EE_Error
356
+	 */
357
+	public function empty_cart()
358
+	{
359
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
360
+		$this->_grand_total = $this->_create_grand_total();
361
+		return $this->save_cart(true);
362
+	}
363
+
364
+
365
+
366
+	/**
367
+	 * @remove ALL items from cart and delete total as well
368
+	 * @access public
369
+	 * @return bool
370
+	 * @throws \EE_Error
371
+	 */
372
+	public function delete_cart()
373
+	{
374
+		$deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
375
+		if ($deleted) {
376
+			$deleted += $this->_grand_total->delete();
377
+			$this->_grand_total = null;
378
+		}
379
+		return $deleted;
380
+	}
381
+
382
+
383
+
384
+	/**
385
+	 * @save   cart to session
386
+	 * @access public
387
+	 * @param bool $apply_taxes
388
+	 * @return TRUE on success, FALSE on fail
389
+	 * @throws \EE_Error
390
+	 */
391
+	public function save_cart($apply_taxes = true)
392
+	{
393
+		if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
394
+			EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
395
+			//make sure we don't cache the transaction because it can get stale
396
+			if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
397
+				&& $this->_grand_total->get_one_from_cache('Transaction')->ID()
398
+			) {
399
+				$this->_grand_total->clear_cache('Transaction', null, true);
400
+			}
401
+		}
402
+		if ($this->session() instanceof EE_Session) {
403
+			return $this->session()->set_cart($this);
404
+		} else {
405
+			return false;
406
+		}
407
+	}
408
+
409
+
410
+
411
+	public function __wakeup()
412
+	{
413
+		if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
414
+			// $this->_grand_total is actually just an ID, so use it to get the object from the db
415
+			$this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
416
+		}
417
+	}
418
+
419
+
420
+
421
+	/**
422
+	 * @return array
423
+	 */
424
+	public function __sleep()
425
+	{
426
+		if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
427
+			$this->_grand_total = $this->_grand_total->ID();
428
+		}
429
+		return array('_grand_total');
430
+	}
431 431
 
432 432
 
433 433
 }
Please login to merge, or discard this patch.
core/EE_Registry.core.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -298,6 +298,7 @@
 block discarded – undo
298 298
 
299 299
     /**
300 300
      * @param mixed string | EED_Module $module
301
+     * @param string $module
301 302
      */
302 303
     public function add_module($module)
303 304
     {
Please login to merge, or discard this patch.
Indentation   +1326 added lines, -1326 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -15,1361 +15,1361 @@  discard block
 block discarded – undo
15 15
 class EE_Registry
16 16
 {
17 17
 
18
-    /**
19
-     *    EE_Registry Object
20
-     *
21
-     * @var EE_Registry $_instance
22
-     * @access    private
23
-     */
24
-    private static $_instance = null;
25
-
26
-    /**
27
-     * @var EE_Dependency_Map $_dependency_map
28
-     * @access    protected
29
-     */
30
-    protected $_dependency_map = null;
31
-
32
-    /**
33
-     * @var array $_class_abbreviations
34
-     * @access    protected
35
-     */
36
-    protected $_class_abbreviations = array();
37
-
38
-    /**
39
-     * @access public
40
-     * @var \EventEspresso\core\services\commands\CommandBusInterface $BUS
41
-     */
42
-    public $BUS;
43
-
44
-    /**
45
-     *    EE_Cart Object
46
-     *
47
-     * @access    public
48
-     * @var    EE_Cart $CART
49
-     */
50
-    public $CART = null;
51
-
52
-    /**
53
-     *    EE_Config Object
54
-     *
55
-     * @access    public
56
-     * @var    EE_Config $CFG
57
-     */
58
-    public $CFG = null;
59
-
60
-    /**
61
-     * EE_Network_Config Object
62
-     *
63
-     * @access public
64
-     * @var EE_Network_Config $NET_CFG
65
-     */
66
-    public $NET_CFG = null;
67
-
68
-    /**
69
-     *    StdClass object for storing library classes in
70
-     *
71
-     * @public LIB
72
-     * @var StdClass $LIB
73
-     */
74
-    public $LIB = null;
75
-
76
-    /**
77
-     *    EE_Request_Handler Object
78
-     *
79
-     * @access    public
80
-     * @var    EE_Request_Handler $REQ
81
-     */
82
-    public $REQ = null;
83
-
84
-    /**
85
-     *    EE_Session Object
86
-     *
87
-     * @access    public
88
-     * @var    EE_Session $SSN
89
-     */
90
-    public $SSN = null;
91
-
92
-    /**
93
-     * holds the ee capabilities object.
94
-     *
95
-     * @since 4.5.0
96
-     * @var EE_Capabilities
97
-     */
98
-    public $CAP = null;
99
-
100
-    /**
101
-     * holds the EE_Message_Resource_Manager object.
102
-     *
103
-     * @since 4.9.0
104
-     * @var EE_Message_Resource_Manager
105
-     */
106
-    public $MRM = null;
107
-
108
-    /**
109
-     *    $addons - StdClass object for holding addons which have registered themselves to work with EE core
110
-     *
111
-     * @access    public
112
-     * @var    EE_Addon[]
113
-     */
114
-    public $addons = null;
115
-
116
-    /**
117
-     *    $models
118
-     * @access    public
119
-     * @var    EEM_Base[] $models keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
120
-     */
121
-    public $models = array();
122
-
123
-    /**
124
-     *    $modules
125
-     * @access    public
126
-     * @var    EED_Module[] $modules
127
-     */
128
-    public $modules = null;
129
-
130
-    /**
131
-     *    $shortcodes
132
-     * @access    public
133
-     * @var    EES_Shortcode[] $shortcodes
134
-     */
135
-    public $shortcodes = null;
136
-
137
-    /**
138
-     *    $widgets
139
-     * @access    public
140
-     * @var    WP_Widget[] $widgets
141
-     */
142
-    public $widgets = null;
143
-
144
-    /**
145
-     * $non_abstract_db_models
146
-     * @access public
147
-     * @var array this is an array of all implemented model names (i.e. not the parent abstract models, or models
148
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
149
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
150
-     * classnames (eg "EEM_Event")
151
-     */
152
-    public $non_abstract_db_models = array();
153
-
154
-    /**
155
-     *    $i18n_js_strings - internationalization for JS strings
156
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = __( 'string to translate.', 'event_espresso' );
157
-     *    in js file:  var translatedString = eei18n.string_key;
158
-     *
159
-     * @access    public
160
-     * @var    array
161
-     */
162
-    public static $i18n_js_strings = array();
163
-
164
-    /**
165
-     *    $main_file - path to espresso.php
166
-     *
167
-     * @access    public
168
-     * @var    array
169
-     */
170
-    public $main_file;
171
-
172
-    /**
173
-     * array of ReflectionClass objects where the key is the class name
174
-     *
175
-     * @access    public
176
-     * @var ReflectionClass[]
177
-     */
178
-    public $_reflectors;
179
-
180
-    /**
181
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
182
-     *
183
-     * @access    protected
184
-     * @var boolean $_cache_on
185
-     */
186
-    protected $_cache_on = true;
187
-
188
-
189
-
190
-    /**
191
-     * @singleton method used to instantiate class object
192
-     * @access    public
193
-     * @param  \EE_Dependency_Map $dependency_map
194
-     * @return \EE_Registry instance
195
-     */
196
-    public static function instance(\EE_Dependency_Map $dependency_map = null)
197
-    {
198
-        // check if class object is instantiated
199
-        if ( ! self::$_instance instanceof EE_Registry) {
200
-            self::$_instance = new EE_Registry($dependency_map);
201
-        }
202
-        return self::$_instance;
203
-    }
204
-
205
-
206
-
207
-    /**
208
-     *protected constructor to prevent direct creation
209
-     *
210
-     * @Constructor
211
-     * @access protected
212
-     * @param  \EE_Dependency_Map $dependency_map
213
-     * @return \EE_Registry
214
-     */
215
-    protected function __construct(\EE_Dependency_Map $dependency_map)
216
-    {
217
-        $this->_dependency_map = $dependency_map;
218
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
219
-    }
220
-
221
-
222
-
223
-    /**
224
-     * initialize
225
-     */
226
-    public function initialize()
227
-    {
228
-        $this->_class_abbreviations = apply_filters(
229
-            'FHEE__EE_Registry____construct___class_abbreviations',
230
-            array(
231
-                'EE_Config'                                       => 'CFG',
232
-                'EE_Session'                                      => 'SSN',
233
-                'EE_Capabilities'                                 => 'CAP',
234
-                'EE_Cart'                                         => 'CART',
235
-                'EE_Network_Config'                               => 'NET_CFG',
236
-                'EE_Request_Handler'                              => 'REQ',
237
-                'EE_Message_Resource_Manager'                     => 'MRM',
238
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
239
-            )
240
-        );
241
-        // class library
242
-        $this->LIB = new stdClass();
243
-        $this->addons = new stdClass();
244
-        $this->modules = new stdClass();
245
-        $this->shortcodes = new stdClass();
246
-        $this->widgets = new stdClass();
247
-        $this->load_core('Base', array(), true);
248
-        // add our request and response objects to the cache
249
-        $request_loader = $this->_dependency_map->class_loader('EE_Request');
250
-        $this->_set_cached_class(
251
-            $request_loader(),
252
-            'EE_Request'
253
-        );
254
-        $response_loader = $this->_dependency_map->class_loader('EE_Response');
255
-        $this->_set_cached_class(
256
-            $response_loader(),
257
-            'EE_Response'
258
-        );
259
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
260
-    }
261
-
262
-
263
-
264
-    /**
265
-     *    init
266
-     *
267
-     * @access    public
268
-     * @return    void
269
-     */
270
-    public function init()
271
-    {
272
-        // Get current page protocol
273
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
274
-        // Output admin-ajax.php URL with same protocol as current page
275
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
276
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * localize_i18n_js_strings
283
-     *
284
-     * @return string
285
-     */
286
-    public static function localize_i18n_js_strings()
287
-    {
288
-        $i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
289
-        foreach ($i18n_js_strings as $key => $value) {
290
-            if (is_scalar($value)) {
291
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
292
-            }
293
-        }
294
-        return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
295
-    }
296
-
297
-
298
-
299
-    /**
300
-     * @param mixed string | EED_Module $module
301
-     */
302
-    public function add_module($module)
303
-    {
304
-        if ($module instanceof EED_Module) {
305
-            $module_class = get_class($module);
306
-            $this->modules->{$module_class} = $module;
307
-        } else {
308
-            if ( ! class_exists('EE_Module_Request_Router')) {
309
-                $this->load_core('Module_Request_Router');
310
-            }
311
-            $this->modules->{$module} = EE_Module_Request_Router::module_factory($module);
312
-        }
313
-    }
314
-
315
-
316
-
317
-    /**
318
-     * @param string $module_name
319
-     * @return mixed EED_Module | NULL
320
-     */
321
-    public function get_module($module_name = '')
322
-    {
323
-        return isset($this->modules->{$module_name}) ? $this->modules->{$module_name} : null;
324
-    }
325
-
326
-
327
-
328
-    /**
329
-     *    loads core classes - must be singletons
330
-     *
331
-     * @access    public
332
-     * @param string $class_name - simple class name ie: session
333
-     * @param mixed  $arguments
334
-     * @param bool   $load_only
335
-     * @return mixed
336
-     */
337
-    public function load_core($class_name, $arguments = array(), $load_only = false)
338
-    {
339
-        $core_paths = apply_filters(
340
-            'FHEE__EE_Registry__load_core__core_paths',
341
-            array(
342
-                EE_CORE,
343
-                EE_ADMIN,
344
-                EE_CPTS,
345
-                EE_CORE . 'data_migration_scripts' . DS,
346
-                EE_CORE . 'request_stack' . DS,
347
-                EE_CORE . 'middleware' . DS,
348
-            )
349
-        );
350
-        // retrieve instantiated class
351
-        return $this->_load($core_paths, 'EE_', $class_name, 'core', $arguments, false, true, $load_only);
352
-    }
353
-
354
-
355
-
356
-    /**
357
-     *    loads service classes
358
-     *
359
-     * @access    public
360
-     * @param string $class_name - simple class name ie: session
361
-     * @param mixed  $arguments
362
-     * @param bool   $load_only
363
-     * @return mixed
364
-     */
365
-    public function load_service($class_name, $arguments = array(), $load_only = false)
366
-    {
367
-        $service_paths = apply_filters(
368
-            'FHEE__EE_Registry__load_service__service_paths',
369
-            array(
370
-                EE_CORE . 'services' . DS,
371
-            )
372
-        );
373
-        // retrieve instantiated class
374
-        return $this->_load($service_paths, 'EE_', $class_name, 'class', $arguments, false, true, $load_only);
375
-    }
376
-
377
-
378
-
379
-    /**
380
-     *    loads data_migration_scripts
381
-     *
382
-     * @access    public
383
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
384
-     * @param mixed  $arguments
385
-     * @return EE_Data_Migration_Script_Base|mixed
386
-     */
387
-    public function load_dms($class_name, $arguments = array())
388
-    {
389
-        // retrieve instantiated class
390
-        return $this->_load(EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(), 'EE_DMS_', $class_name, 'dms', $arguments, false, false, false);
391
-    }
392
-
393
-
394
-
395
-    /**
396
-     *    loads object creating classes - must be singletons
397
-     *
398
-     * @param string $class_name - simple class name ie: attendee
399
-     * @param mixed  $arguments  - an array of arguments to pass to the class
400
-     * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to instantiate
401
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then set this to FALSE (ie. when instantiating model objects from client in a loop)
402
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate (default)
403
-     * @return EE_Base_Class | bool
404
-     */
405
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
406
-    {
407
-        $paths = apply_filters('FHEE__EE_Registry__load_class__paths', array(
408
-            EE_CORE,
409
-            EE_CLASSES,
410
-            EE_BUSINESS,
411
-        ));
412
-        // retrieve instantiated class
413
-        return $this->_load($paths, 'EE_', $class_name, 'class', $arguments, $from_db, $cache, $load_only);
414
-    }
415
-
416
-
417
-
418
-    /**
419
-     *    loads helper classes - must be singletons
420
-     *
421
-     * @param string $class_name - simple class name ie: price
422
-     * @param mixed  $arguments
423
-     * @param bool   $load_only
424
-     * @return EEH_Base | bool
425
-     */
426
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
427
-    {
428
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
429
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
430
-        // retrieve instantiated class
431
-        return $this->_load($helper_paths, 'EEH_', $class_name, 'helper', $arguments, false, true, $load_only);
432
-    }
433
-
434
-
435
-
436
-    /**
437
-     *    loads core classes - must be singletons
438
-     *
439
-     * @access    public
440
-     * @param string $class_name - simple class name ie: session
441
-     * @param mixed  $arguments
442
-     * @param bool   $load_only
443
-     * @param bool   $cache      whether to cache the object or not.
444
-     * @return mixed
445
-     */
446
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
447
-    {
448
-        $paths = array(
449
-            EE_LIBRARIES,
450
-            EE_LIBRARIES . 'messages' . DS,
451
-            EE_LIBRARIES . 'shortcodes' . DS,
452
-            EE_LIBRARIES . 'qtips' . DS,
453
-            EE_LIBRARIES . 'payment_methods' . DS,
454
-        );
455
-        // retrieve instantiated class
456
-        return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, false, $cache, $load_only);
457
-    }
458
-
459
-
460
-
461
-    /**
462
-     *    loads model classes - must be singletons
463
-     *
464
-     * @param string $class_name - simple class name ie: price
465
-     * @param mixed  $arguments
466
-     * @param bool   $load_only
467
-     * @return EEM_Base | bool
468
-     */
469
-    public function load_model($class_name, $arguments = array(), $load_only = false)
470
-    {
471
-        $paths = apply_filters('FHEE__EE_Registry__load_model__paths', array(
472
-            EE_MODELS,
473
-            EE_CORE,
474
-        ));
475
-        // retrieve instantiated class
476
-        return $this->_load($paths, 'EEM_', $class_name, 'model', $arguments, false, true, $load_only);
477
-    }
478
-
479
-
480
-
481
-    /**
482
-     *    loads model classes - must be singletons
483
-     *
484
-     * @param string $class_name - simple class name ie: price
485
-     * @param mixed  $arguments
486
-     * @param bool   $load_only
487
-     * @return mixed | bool
488
-     */
489
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
490
-    {
491
-        $paths = array(
492
-            EE_MODELS . 'fields' . DS,
493
-            EE_MODELS . 'helpers' . DS,
494
-            EE_MODELS . 'relations' . DS,
495
-            EE_MODELS . 'strategies' . DS,
496
-        );
497
-        // retrieve instantiated class
498
-        return $this->_load($paths, 'EE_', $class_name, '', $arguments, false, true, $load_only);
499
-    }
500
-
501
-
502
-
503
-    /**
504
-     * Determines if $model_name is the name of an actual EE model.
505
-     *
506
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
507
-     * @return boolean
508
-     */
509
-    public function is_model_name($model_name)
510
-    {
511
-        return isset($this->models[$model_name]) ? true : false;
512
-    }
513
-
514
-
515
-
516
-    /**
517
-     *    generic class loader
518
-     *
519
-     * @param string $path_to_file - directory path to file location, not including filename
520
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
521
-     * @param string $type         - file type - core? class? helper? model?
522
-     * @param mixed  $arguments
523
-     * @param bool   $load_only
524
-     * @return mixed
525
-     */
526
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
527
-    {
528
-        // retrieve instantiated class
529
-        return $this->_load($path_to_file, '', $file_name, $type, $arguments, false, true, $load_only);
530
-    }
531
-
532
-
533
-
534
-    /**
535
-     *    load_addon
536
-     *
537
-     * @param string $path_to_file - directory path to file location, not including filename
538
-     * @param string $class_name   - full class name  ie:  My_Class
539
-     * @param string $type         - file type - core? class? helper? model?
540
-     * @param mixed  $arguments
541
-     * @param bool   $load_only
542
-     * @return EE_Addon
543
-     */
544
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
545
-    {
546
-        // retrieve instantiated class
547
-        return $this->_load($path_to_file, 'addon', $class_name, $type, $arguments, false, true, $load_only);
548
-    }
549
-
550
-
551
-
552
-    /**
553
-     * instantiates, caches, and automatically resolves dependencies
554
-     * for classes that use a Fully Qualified Class Name.
555
-     * if the class is not capable of being loaded using PSR-4 autoloading,
556
-     * then you need to use one of the existing load_*() methods
557
-     * which can resolve the classname and filepath from the passed arguments
558
-     *
559
-     * @param bool|string $class_name   Fully Qualified Class Name
560
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
561
-     * @param bool        $cache        whether to cache the instantiated object for reuse
562
-     * @param bool        $from_db      some classes are instantiated from the db
563
-     *                                  and thus call a different method to instantiate
564
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
565
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
566
-     * @return mixed                    null = failure to load or instantiate class object.
567
-     *                                  object = class loaded and instantiated successfully.
568
-     *                                  bool = fail or success when $load_only is true
569
-     */
570
-    public function create(
571
-        $class_name = false,
572
-        $arguments = array(),
573
-        $cache = false,
574
-        $from_db = false,
575
-        $load_only = false,
576
-        $addon = false
577
-    ) {
578
-        $class_name = $this->_dependency_map->get_alias($class_name);
579
-        if ( ! class_exists($class_name)) {
580
-            // maybe the class is registered with a preceding \
581
-            $class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
582
-            // still doesn't exist ?
583
-            if ( ! class_exists($class_name)) {
584
-                return null;
585
-            }
586
-        }
587
-        // if we're only loading the class and it already exists, then let's just return true immediately
588
-        if ($load_only) {
589
-            return true;
590
-        }
591
-        $addon = $addon ? 'addon' : '';
592
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
593
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
594
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
595
-        if ($this->_cache_on && $cache && ! $load_only) {
596
-            // return object if it's already cached
597
-            $cached_class = $this->_get_cached_class($class_name, $addon);
598
-            if ($cached_class !== null) {
599
-                return $cached_class;
600
-            }
601
-        }
602
-        // instantiate the requested object
603
-        $class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
604
-        if ($this->_cache_on && $cache) {
605
-            // save it for later... kinda like gum  { : $
606
-            $this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
607
-        }
608
-        $this->_cache_on = true;
609
-        return $class_obj;
610
-    }
611
-
612
-
613
-
614
-    /**
615
-     * instantiates, caches, and injects dependencies for classes
616
-     *
617
-     * @param array       $file_paths   an array of paths to folders to look in
618
-     * @param string      $class_prefix EE  or EEM or... ???
619
-     * @param bool|string $class_name   $class name
620
-     * @param string      $type         file type - core? class? helper? model?
621
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
622
-     * @param bool        $from_db      some classes are instantiated from the db
623
-     *                                  and thus call a different method to instantiate
624
-     * @param bool        $cache        whether to cache the instantiated object for reuse
625
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
626
-     * @return null|object|bool         null = failure to load or instantiate class object.
627
-     *                                  object = class loaded and instantiated successfully.
628
-     *                                  bool = fail or success when $load_only is true
629
-     */
630
-    protected function _load(
631
-        $file_paths = array(),
632
-        $class_prefix = 'EE_',
633
-        $class_name = false,
634
-        $type = 'class',
635
-        $arguments = array(),
636
-        $from_db = false,
637
-        $cache = true,
638
-        $load_only = false
639
-    ) {
640
-        // strip php file extension
641
-        $class_name = str_replace('.php', '', trim($class_name));
642
-        // does the class have a prefix ?
643
-        if ( ! empty($class_prefix) && $class_prefix != 'addon') {
644
-            // make sure $class_prefix is uppercase
645
-            $class_prefix = strtoupper(trim($class_prefix));
646
-            // add class prefix ONCE!!!
647
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
648
-        }
649
-        $class_name = $this->_dependency_map->get_alias($class_name);
650
-        $class_exists = class_exists($class_name);
651
-        // if we're only loading the class and it already exists, then let's just return true immediately
652
-        if ($load_only && $class_exists) {
653
-            return true;
654
-        }
655
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
656
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
657
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
658
-        if ($this->_cache_on && $cache && ! $load_only) {
659
-            // return object if it's already cached
660
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix);
661
-            if ($cached_class !== null) {
662
-                return $cached_class;
663
-            }
664
-        }
665
-        // if the class doesn't already exist.. then we need to try and find the file and load it
666
-        if ( ! $class_exists) {
667
-            // get full path to file
668
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
669
-            // load the file
670
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
671
-            // if loading failed, or we are only loading a file but NOT instantiating an object
672
-            if ( ! $loaded || $load_only) {
673
-                // return boolean if only loading, or null if an object was expected
674
-                return $load_only ? $loaded : null;
675
-            }
676
-        }
677
-        // instantiate the requested object
678
-        $class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
679
-        if ($this->_cache_on && $cache) {
680
-            // save it for later... kinda like gum  { : $
681
-            $this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
682
-        }
683
-        $this->_cache_on = true;
684
-        return $class_obj;
685
-    }
686
-
687
-
688
-
689
-    /**
690
-     * _get_cached_class
691
-     * attempts to find a cached version of the requested class
692
-     * by looking in the following places:
693
-     *        $this->{$class_abbreviation}            ie:    $this->CART
694
-     *        $this->{$class_name}                        ie:    $this->Some_Class
695
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
696
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
697
-     *
698
-     * @access protected
699
-     * @param string $class_name
700
-     * @param string $class_prefix
701
-     * @return mixed
702
-     */
703
-    protected function _get_cached_class($class_name, $class_prefix = '')
704
-    {
705
-        if (isset($this->_class_abbreviations[$class_name])) {
706
-            $class_abbreviation = $this->_class_abbreviations[$class_name];
707
-        } else {
708
-            // have to specify something, but not anything that will conflict
709
-            $class_abbreviation = 'FANCY_BATMAN_PANTS';
710
-        }
711
-        // check if class has already been loaded, and return it if it has been
712
-        if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
713
-            return $this->{$class_abbreviation};
714
-        } else if (isset ($this->{$class_name})) {
715
-            return $this->{$class_name};
716
-        } else if (isset ($this->LIB->{$class_name})) {
717
-            return $this->LIB->{$class_name};
718
-        } else if ($class_prefix == 'addon' && isset ($this->addons->{$class_name})) {
719
-            return $this->addons->{$class_name};
720
-        }
721
-        return null;
722
-    }
723
-
724
-
725
-
726
-    /**
727
-     * _resolve_path
728
-     * attempts to find a full valid filepath for the requested class.
729
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
730
-     * then returns that path if the target file has been found and is readable
731
-     *
732
-     * @access protected
733
-     * @param string $class_name
734
-     * @param string $type
735
-     * @param array  $file_paths
736
-     * @return string | bool
737
-     */
738
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
739
-    {
740
-        // make sure $file_paths is an array
741
-        $file_paths = is_array($file_paths) ? $file_paths : array($file_paths);
742
-        // cycle thru paths
743
-        foreach ($file_paths as $key => $file_path) {
744
-            // convert all separators to proper DS, if no filepath, then use EE_CLASSES
745
-            $file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
746
-            // prep file type
747
-            $type = ! empty($type) ? trim($type, '.') . '.' : '';
748
-            // build full file path
749
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
750
-            //does the file exist and can be read ?
751
-            if (is_readable($file_paths[$key])) {
752
-                return $file_paths[$key];
753
-            }
754
-        }
755
-        return false;
756
-    }
757
-
758
-
759
-
760
-    /**
761
-     * _require_file
762
-     * basically just performs a require_once()
763
-     * but with some error handling
764
-     *
765
-     * @access protected
766
-     * @param  string $path
767
-     * @param  string $class_name
768
-     * @param  string $type
769
-     * @param  array  $file_paths
770
-     * @return boolean
771
-     * @throws \EE_Error
772
-     */
773
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
774
-    {
775
-        // don't give up! you gotta...
776
-        try {
777
-            //does the file exist and can it be read ?
778
-            if ( ! $path) {
779
-                // so sorry, can't find the file
780
-                throw new EE_Error (
781
-                    sprintf(
782
-                        __('The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s', 'event_espresso'),
783
-                        trim($type, '.'),
784
-                        $class_name,
785
-                        '<br />' . implode(',<br />', $file_paths)
786
-                    )
787
-                );
788
-            }
789
-            // get the file
790
-            require_once($path);
791
-            // if the class isn't already declared somewhere
792
-            if (class_exists($class_name, false) === false) {
793
-                // so sorry, not a class
794
-                throw new EE_Error(
795
-                    sprintf(
796
-                        __('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
797
-                        $type,
798
-                        $path,
799
-                        $class_name
800
-                    )
801
-                );
802
-            }
803
-        } catch (EE_Error $e) {
804
-            $e->get_error();
805
-            return false;
806
-        }
807
-        return true;
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * _create_object
814
-     * Attempts to instantiate the requested class via any of the
815
-     * commonly used instantiation methods employed throughout EE.
816
-     * The priority for instantiation is as follows:
817
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
818
-     *        - model objects via their 'new_instance_from_db' method
819
-     *        - model objects via their 'new_instance' method
820
-     *        - "singleton" classes" via their 'instance' method
821
-     *    - standard instantiable classes via their __constructor
822
-     * Prior to instantiation, if the classname exists in the dependency_map,
823
-     * then the constructor for the requested class will be examined to determine
824
-     * if any dependencies exist, and if they can be injected.
825
-     * If so, then those classes will be added to the array of arguments passed to the constructor
826
-     *
827
-     * @access protected
828
-     * @param string $class_name
829
-     * @param array  $arguments
830
-     * @param string $type
831
-     * @param bool   $from_db
832
-     * @return null | object
833
-     * @throws \EE_Error
834
-     */
835
-    protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
836
-    {
837
-        $class_obj = null;
838
-        $instantiation_mode = '0) none';
839
-        // don't give up! you gotta...
840
-        try {
841
-            // create reflection
842
-            $reflector = $this->get_ReflectionClass($class_name);
843
-            // make sure arguments are an array
844
-            $arguments = is_array($arguments) ? $arguments : array($arguments);
845
-            // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
846
-            // else wrap it in an additional array so that it doesn't get split into multiple parameters
847
-            $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
848
-                ? $arguments
849
-                : array($arguments);
850
-            // attempt to inject dependencies ?
851
-            if ($this->_dependency_map->has($class_name)) {
852
-                $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
853
-            }
854
-            // instantiate the class if possible
855
-            if ($reflector->isAbstract()) {
856
-                // nothing to instantiate, loading file was enough
857
-                // does not throw an exception so $instantiation_mode is unused
858
-                // $instantiation_mode = "1) no constructor abstract class";
859
-                $class_obj = true;
860
-            } else if ($reflector->getConstructor() === null && $reflector->isInstantiable() && empty($arguments)) {
861
-                // no constructor = static methods only... nothing to instantiate, loading file was enough
862
-                $instantiation_mode = "2) no constructor but instantiable";
863
-                $class_obj = $reflector->newInstance();
864
-            } else if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
865
-                $instantiation_mode = "3) new_instance_from_db()";
866
-                $class_obj = call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
867
-            } else if (method_exists($class_name, 'new_instance')) {
868
-                $instantiation_mode = "4) new_instance()";
869
-                $class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
870
-            } else if (method_exists($class_name, 'instance')) {
871
-                $instantiation_mode = "5) instance()";
872
-                $class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
873
-            } else if ($reflector->isInstantiable()) {
874
-                $instantiation_mode = "6) constructor";
875
-                $class_obj = $reflector->newInstanceArgs($arguments);
876
-            } else {
877
-                // heh ? something's not right !
878
-                throw new EE_Error(
879
-                    sprintf(
880
-                        __('The %s file %s could not be instantiated.', 'event_espresso'),
881
-                        $type,
882
-                        $class_name
883
-                    )
884
-                );
885
-            }
886
-        } catch (Exception $e) {
887
-            if ( ! $e instanceof EE_Error) {
888
-                $e = new EE_Error(
889
-                    sprintf(
890
-                        __('The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s', 'event_espresso'),
891
-                        $class_name,
892
-                        '<br />',
893
-                        $e->getMessage(),
894
-                        $instantiation_mode
895
-                    )
896
-                );
897
-            }
898
-            $e->get_error();
899
-        }
900
-        return $class_obj;
901
-    }
902
-
903
-
904
-
905
-    /**
906
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
907
-     * @param array $array
908
-     * @return bool
909
-     */
910
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
911
-    {
912
-        return ! empty($array) ? array_keys($array) === range(0, count($array) - 1) : true;
913
-    }
914
-
915
-
916
-
917
-    /**
918
-     * getReflectionClass
919
-     * checks if a ReflectionClass object has already been generated for a class
920
-     * and returns that instead of creating a new one
921
-     *
922
-     * @access public
923
-     * @param string $class_name
924
-     * @return ReflectionClass
925
-     */
926
-    public function get_ReflectionClass($class_name)
927
-    {
928
-        if (
929
-            ! isset($this->_reflectors[$class_name])
930
-            || ! $this->_reflectors[$class_name] instanceof ReflectionClass
931
-        ) {
932
-            $this->_reflectors[$class_name] = new ReflectionClass($class_name);
933
-        }
934
-        return $this->_reflectors[$class_name];
935
-    }
936
-
937
-
938
-
939
-    /**
940
-     * _resolve_dependencies
941
-     * examines the constructor for the requested class to determine
942
-     * if any dependencies exist, and if they can be injected.
943
-     * If so, then those classes will be added to the array of arguments passed to the constructor
944
-     * PLZ NOTE: this is achieved by type hinting the constructor params
945
-     * For example:
946
-     *        if attempting to load a class "Foo" with the following constructor:
947
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
948
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
949
-     *        but only IF they are NOT already present in the incoming arguments array,
950
-     *        and the correct classes can be loaded
951
-     *
952
-     * @access protected
953
-     * @param ReflectionClass $reflector
954
-     * @param string          $class_name
955
-     * @param array           $arguments
956
-     * @return array
957
-     * @throws \ReflectionException
958
-     */
959
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
960
-    {
961
-        // let's examine the constructor
962
-        $constructor = $reflector->getConstructor();
963
-        // whu? huh? nothing?
964
-        if ( ! $constructor) {
965
-            return $arguments;
966
-        }
967
-        // get constructor parameters
968
-        $params = $constructor->getParameters();
969
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
970
-        $argument_keys = array_keys($arguments);
971
-        // now loop thru all of the constructors expected parameters
972
-        foreach ($params as $index => $param) {
973
-            // is this a dependency for a specific class ?
974
-            $param_class = $param->getClass() ? $param->getClass()->name : null;
975
-            if (
976
-                // param is not even a class
977
-                empty($param_class)
978
-                // and something already exists in the incoming arguments for this param
979
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
980
-            ) {
981
-                // so let's skip this argument and move on to the next
982
-                continue;
983
-            } else if (
984
-                // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
985
-                ! empty($param_class)
986
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
987
-                && $arguments[$argument_keys[$index]] instanceof $param_class
988
-            ) {
989
-                // skip this argument and move on to the next
990
-                continue;
991
-            } else if (
992
-                // parameter is type hinted as a class, and should be injected
993
-                ! empty($param_class)
994
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
995
-            ) {
996
-                $arguments = $this->_resolve_dependency($class_name, $param_class, $arguments, $index);
997
-            } else {
998
-                try {
999
-                    $arguments[$index] = $param->getDefaultValue();
1000
-                } catch (ReflectionException $e) {
1001
-                    throw new ReflectionException(
1002
-                        sprintf(
1003
-                            __('%1$s for parameter "$%2$s"', 'event_espresso'),
1004
-                            $e->getMessage(),
1005
-                            $param->getName()
1006
-                        )
1007
-                    );
1008
-                }
1009
-            }
1010
-        }
1011
-        return $arguments;
1012
-    }
1013
-
1014
-
1015
-
1016
-    /**
1017
-     * @access protected
1018
-     * @param string $class_name
1019
-     * @param string $param_class
1020
-     * @param array  $arguments
1021
-     * @param mixed  $index
1022
-     * @return array
1023
-     */
1024
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1025
-    {
1026
-        $dependency = null;
1027
-        // should dependency be loaded from cache ?
1028
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $param_class)
1029
-                    !== EE_Dependency_Map::load_new_object
1030
-            ? true
1031
-            : false;
1032
-        // we might have a dependency...
1033
-        // let's MAYBE try and find it in our cache if that's what's been requested
1034
-        $cached_class = $cache_on ? $this->_get_cached_class($param_class) : null;
1035
-        // and grab it if it exists
1036
-        if ($cached_class instanceof $param_class) {
1037
-            $dependency = $cached_class;
1038
-        } else if ($param_class != $class_name) {
1039
-            // obtain the loader method from the dependency map
1040
-            $loader = $this->_dependency_map->class_loader($param_class);
1041
-            // is loader a custom closure ?
1042
-            if ($loader instanceof Closure) {
1043
-                $dependency = $loader();
1044
-            } else {
1045
-                // set the cache on property for the recursive loading call
1046
-                $this->_cache_on = $cache_on;
1047
-                // if not, then let's try and load it via the registry
1048
-                if (method_exists($this, $loader)) {
1049
-                    $dependency = $this->{$loader}($param_class);
1050
-                } else {
1051
-                    $dependency = $this->create($param_class, array(), $cache_on);
1052
-                }
1053
-            }
1054
-        }
1055
-        // did we successfully find the correct dependency ?
1056
-        if ($dependency instanceof $param_class) {
1057
-            // then let's inject it into the incoming array of arguments at the correct location
1058
-            if (isset($argument_keys[$index])) {
1059
-                $arguments[$argument_keys[$index]] = $dependency;
1060
-            } else {
1061
-                $arguments[$index] = $dependency;
1062
-            }
1063
-        }
1064
-        return $arguments;
1065
-    }
1066
-
1067
-
1068
-
1069
-    /**
1070
-     * _set_cached_class
1071
-     * attempts to cache the instantiated class locally
1072
-     * in one of the following places, in the following order:
1073
-     *        $this->{class_abbreviation}   ie:    $this->CART
1074
-     *        $this->{$class_name}          ie:    $this->Some_Class
1075
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1076
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1077
-     *
1078
-     * @access protected
1079
-     * @param object $class_obj
1080
-     * @param string $class_name
1081
-     * @param string $class_prefix
1082
-     * @param bool   $from_db
1083
-     * @return void
1084
-     */
1085
-    protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1086
-    {
1087
-        if (empty($class_obj)) {
1088
-            return;
1089
-        }
1090
-        // return newly instantiated class
1091
-        if (isset($this->_class_abbreviations[$class_name])) {
1092
-            $class_abbreviation = $this->_class_abbreviations[$class_name];
1093
-            $this->{$class_abbreviation} = $class_obj;
1094
-        } else if (property_exists($this, $class_name)) {
1095
-            $this->{$class_name} = $class_obj;
1096
-        } else if ($class_prefix == 'addon') {
1097
-            $this->addons->{$class_name} = $class_obj;
1098
-        } else if ( ! $from_db) {
1099
-            $this->LIB->{$class_name} = $class_obj;
1100
-        }
1101
-    }
1102
-
1103
-
1104
-
1105
-    /**
1106
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1107
-     *
1108
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1109
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1110
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1111
-     * @param array  $arguments
1112
-     * @return object
1113
-     */
1114
-    public static function factory($classname, $arguments = array())
1115
-    {
1116
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1117
-        if ($loader instanceof Closure) {
1118
-            return $loader($arguments);
1119
-        } else if (method_exists(EE_Registry::instance(), $loader)) {
1120
-            return EE_Registry::instance()->{$loader}($classname, $arguments);
1121
-        }
1122
-        return null;
1123
-    }
1124
-
1125
-
1126
-
1127
-    /**
1128
-     * Gets the addon by its name/slug (not classname. For that, just
1129
-     * use the classname as the property name on EE_Config::instance()->addons)
1130
-     *
1131
-     * @param string $name
1132
-     * @return EE_Addon
1133
-     */
1134
-    public function get_addon_by_name($name)
1135
-    {
1136
-        foreach ($this->addons as $addon) {
1137
-            if ($addon->name() == $name) {
1138
-                return $addon;
1139
-            }
1140
-        }
1141
-        return null;
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their name() function) They're already available on EE_Config::instance()->addons as properties, where each property's name is
1148
-     * the addon's classname. So if you just want to get the addon by classname, use EE_Config::instance()->addons->{classname}
1149
-     *
1150
-     * @return EE_Addon[] where the KEYS are the addon's name()
1151
-     */
1152
-    public function get_addons_by_name()
1153
-    {
1154
-        $addons = array();
1155
-        foreach ($this->addons as $addon) {
1156
-            $addons[$addon->name()] = $addon;
1157
-        }
1158
-        return $addons;
1159
-    }
1160
-
1161
-
1162
-
1163
-    /**
1164
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1165
-     * a stale copy of it around
1166
-     *
1167
-     * @param string $model_name
1168
-     * @return \EEM_Base
1169
-     * @throws \EE_Error
1170
-     */
1171
-    public function reset_model($model_name)
1172
-    {
1173
-        $model_class_name = strpos($model_name, 'EEM_') !== 0 ? "EEM_{$model_name}" : $model_name;
1174
-        if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1175
-            return null;
1176
-        }
1177
-        //get that model reset it and make sure we nuke the old reference to it
1178
-        if ($this->LIB->{$model_class_name} instanceof $model_class_name && is_callable(array($model_class_name, 'reset'))) {
1179
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1180
-        } else {
1181
-            throw new EE_Error(sprintf(__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1182
-        }
1183
-        return $this->LIB->{$model_class_name};
1184
-    }
1185
-
1186
-
1187
-
1188
-    /**
1189
-     * Resets the registry.
1190
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when switch_to_blog
1191
-     * is used in a multisite install.  Here is a list of things that are NOT reset.
1192
-     * - $_dependency_map
1193
-     * - $_class_abbreviations
1194
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1195
-     * - $REQ:  Still on the same request so no need to change.
1196
-     * - $CAP: There is no site specific state in the EE_Capability class.
1197
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only one Session
1198
-     *         can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1199
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1200
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1201
-     *             switch or on the restore.
1202
-     * - $modules
1203
-     * - $shortcodes
1204
-     * - $widgets
1205
-     *
1206
-     * @param boolean $hard             whether to reset data in the database too, or just refresh
1207
-     *                                  the Registry to its state at the beginning of the request
1208
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1209
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not sure if you CAN
1210
-     *                                  currently reinstantiate the singletons at the moment)
1211
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so client
1212
-     *                                  code instead can just change the model context to a different blog id if necessary
1213
-     * @return EE_Registry
1214
-     */
1215
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1216
-    {
1217
-        $instance = self::instance();
1218
-        EEH_Activation::reset();
1219
-        //properties that get reset
1220
-        $instance->_cache_on = true;
1221
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1222
-        $instance->CART = null;
1223
-        $instance->MRM = null;
1224
-        //messages reset
1225
-        EED_Messages::reset();
1226
-        if ($reset_models) {
1227
-            foreach (array_keys($instance->non_abstract_db_models) as $model_name) {
1228
-                $instance->reset_model($model_name);
1229
-            }
1230
-        }
1231
-        $instance->LIB = new stdClass();
1232
-        return $instance;
1233
-    }
1234
-
1235
-
1236
-
1237
-    /**
1238
-     * @override magic methods
1239
-     * @return void
1240
-     */
1241
-    final function __destruct()
1242
-    {
1243
-    }
1244
-
1245
-
1246
-
1247
-    /**
1248
-     * @param $a
1249
-     * @param $b
1250
-     */
1251
-    final function __call($a, $b)
1252
-    {
1253
-    }
1254
-
1255
-
1256
-
1257
-    /**
1258
-     * @param $a
1259
-     */
1260
-    final function __get($a)
1261
-    {
1262
-    }
1263
-
1264
-
1265
-
1266
-    /**
1267
-     * @param $a
1268
-     * @param $b
1269
-     */
1270
-    final function __set($a, $b)
1271
-    {
1272
-    }
1273
-
1274
-
1275
-
1276
-    /**
1277
-     * @param $a
1278
-     */
1279
-    final function __isset($a)
1280
-    {
1281
-    }
18
+	/**
19
+	 *    EE_Registry Object
20
+	 *
21
+	 * @var EE_Registry $_instance
22
+	 * @access    private
23
+	 */
24
+	private static $_instance = null;
25
+
26
+	/**
27
+	 * @var EE_Dependency_Map $_dependency_map
28
+	 * @access    protected
29
+	 */
30
+	protected $_dependency_map = null;
31
+
32
+	/**
33
+	 * @var array $_class_abbreviations
34
+	 * @access    protected
35
+	 */
36
+	protected $_class_abbreviations = array();
37
+
38
+	/**
39
+	 * @access public
40
+	 * @var \EventEspresso\core\services\commands\CommandBusInterface $BUS
41
+	 */
42
+	public $BUS;
43
+
44
+	/**
45
+	 *    EE_Cart Object
46
+	 *
47
+	 * @access    public
48
+	 * @var    EE_Cart $CART
49
+	 */
50
+	public $CART = null;
51
+
52
+	/**
53
+	 *    EE_Config Object
54
+	 *
55
+	 * @access    public
56
+	 * @var    EE_Config $CFG
57
+	 */
58
+	public $CFG = null;
59
+
60
+	/**
61
+	 * EE_Network_Config Object
62
+	 *
63
+	 * @access public
64
+	 * @var EE_Network_Config $NET_CFG
65
+	 */
66
+	public $NET_CFG = null;
67
+
68
+	/**
69
+	 *    StdClass object for storing library classes in
70
+	 *
71
+	 * @public LIB
72
+	 * @var StdClass $LIB
73
+	 */
74
+	public $LIB = null;
75
+
76
+	/**
77
+	 *    EE_Request_Handler Object
78
+	 *
79
+	 * @access    public
80
+	 * @var    EE_Request_Handler $REQ
81
+	 */
82
+	public $REQ = null;
83
+
84
+	/**
85
+	 *    EE_Session Object
86
+	 *
87
+	 * @access    public
88
+	 * @var    EE_Session $SSN
89
+	 */
90
+	public $SSN = null;
91
+
92
+	/**
93
+	 * holds the ee capabilities object.
94
+	 *
95
+	 * @since 4.5.0
96
+	 * @var EE_Capabilities
97
+	 */
98
+	public $CAP = null;
99
+
100
+	/**
101
+	 * holds the EE_Message_Resource_Manager object.
102
+	 *
103
+	 * @since 4.9.0
104
+	 * @var EE_Message_Resource_Manager
105
+	 */
106
+	public $MRM = null;
107
+
108
+	/**
109
+	 *    $addons - StdClass object for holding addons which have registered themselves to work with EE core
110
+	 *
111
+	 * @access    public
112
+	 * @var    EE_Addon[]
113
+	 */
114
+	public $addons = null;
115
+
116
+	/**
117
+	 *    $models
118
+	 * @access    public
119
+	 * @var    EEM_Base[] $models keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
120
+	 */
121
+	public $models = array();
122
+
123
+	/**
124
+	 *    $modules
125
+	 * @access    public
126
+	 * @var    EED_Module[] $modules
127
+	 */
128
+	public $modules = null;
129
+
130
+	/**
131
+	 *    $shortcodes
132
+	 * @access    public
133
+	 * @var    EES_Shortcode[] $shortcodes
134
+	 */
135
+	public $shortcodes = null;
136
+
137
+	/**
138
+	 *    $widgets
139
+	 * @access    public
140
+	 * @var    WP_Widget[] $widgets
141
+	 */
142
+	public $widgets = null;
143
+
144
+	/**
145
+	 * $non_abstract_db_models
146
+	 * @access public
147
+	 * @var array this is an array of all implemented model names (i.e. not the parent abstract models, or models
148
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
149
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
150
+	 * classnames (eg "EEM_Event")
151
+	 */
152
+	public $non_abstract_db_models = array();
153
+
154
+	/**
155
+	 *    $i18n_js_strings - internationalization for JS strings
156
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = __( 'string to translate.', 'event_espresso' );
157
+	 *    in js file:  var translatedString = eei18n.string_key;
158
+	 *
159
+	 * @access    public
160
+	 * @var    array
161
+	 */
162
+	public static $i18n_js_strings = array();
163
+
164
+	/**
165
+	 *    $main_file - path to espresso.php
166
+	 *
167
+	 * @access    public
168
+	 * @var    array
169
+	 */
170
+	public $main_file;
171
+
172
+	/**
173
+	 * array of ReflectionClass objects where the key is the class name
174
+	 *
175
+	 * @access    public
176
+	 * @var ReflectionClass[]
177
+	 */
178
+	public $_reflectors;
179
+
180
+	/**
181
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
182
+	 *
183
+	 * @access    protected
184
+	 * @var boolean $_cache_on
185
+	 */
186
+	protected $_cache_on = true;
187
+
188
+
189
+
190
+	/**
191
+	 * @singleton method used to instantiate class object
192
+	 * @access    public
193
+	 * @param  \EE_Dependency_Map $dependency_map
194
+	 * @return \EE_Registry instance
195
+	 */
196
+	public static function instance(\EE_Dependency_Map $dependency_map = null)
197
+	{
198
+		// check if class object is instantiated
199
+		if ( ! self::$_instance instanceof EE_Registry) {
200
+			self::$_instance = new EE_Registry($dependency_map);
201
+		}
202
+		return self::$_instance;
203
+	}
204
+
205
+
206
+
207
+	/**
208
+	 *protected constructor to prevent direct creation
209
+	 *
210
+	 * @Constructor
211
+	 * @access protected
212
+	 * @param  \EE_Dependency_Map $dependency_map
213
+	 * @return \EE_Registry
214
+	 */
215
+	protected function __construct(\EE_Dependency_Map $dependency_map)
216
+	{
217
+		$this->_dependency_map = $dependency_map;
218
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
219
+	}
220
+
221
+
222
+
223
+	/**
224
+	 * initialize
225
+	 */
226
+	public function initialize()
227
+	{
228
+		$this->_class_abbreviations = apply_filters(
229
+			'FHEE__EE_Registry____construct___class_abbreviations',
230
+			array(
231
+				'EE_Config'                                       => 'CFG',
232
+				'EE_Session'                                      => 'SSN',
233
+				'EE_Capabilities'                                 => 'CAP',
234
+				'EE_Cart'                                         => 'CART',
235
+				'EE_Network_Config'                               => 'NET_CFG',
236
+				'EE_Request_Handler'                              => 'REQ',
237
+				'EE_Message_Resource_Manager'                     => 'MRM',
238
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
239
+			)
240
+		);
241
+		// class library
242
+		$this->LIB = new stdClass();
243
+		$this->addons = new stdClass();
244
+		$this->modules = new stdClass();
245
+		$this->shortcodes = new stdClass();
246
+		$this->widgets = new stdClass();
247
+		$this->load_core('Base', array(), true);
248
+		// add our request and response objects to the cache
249
+		$request_loader = $this->_dependency_map->class_loader('EE_Request');
250
+		$this->_set_cached_class(
251
+			$request_loader(),
252
+			'EE_Request'
253
+		);
254
+		$response_loader = $this->_dependency_map->class_loader('EE_Response');
255
+		$this->_set_cached_class(
256
+			$response_loader(),
257
+			'EE_Response'
258
+		);
259
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
260
+	}
261
+
262
+
263
+
264
+	/**
265
+	 *    init
266
+	 *
267
+	 * @access    public
268
+	 * @return    void
269
+	 */
270
+	public function init()
271
+	{
272
+		// Get current page protocol
273
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
274
+		// Output admin-ajax.php URL with same protocol as current page
275
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
276
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * localize_i18n_js_strings
283
+	 *
284
+	 * @return string
285
+	 */
286
+	public static function localize_i18n_js_strings()
287
+	{
288
+		$i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
289
+		foreach ($i18n_js_strings as $key => $value) {
290
+			if (is_scalar($value)) {
291
+				$i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
292
+			}
293
+		}
294
+		return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
295
+	}
296
+
297
+
298
+
299
+	/**
300
+	 * @param mixed string | EED_Module $module
301
+	 */
302
+	public function add_module($module)
303
+	{
304
+		if ($module instanceof EED_Module) {
305
+			$module_class = get_class($module);
306
+			$this->modules->{$module_class} = $module;
307
+		} else {
308
+			if ( ! class_exists('EE_Module_Request_Router')) {
309
+				$this->load_core('Module_Request_Router');
310
+			}
311
+			$this->modules->{$module} = EE_Module_Request_Router::module_factory($module);
312
+		}
313
+	}
314
+
315
+
316
+
317
+	/**
318
+	 * @param string $module_name
319
+	 * @return mixed EED_Module | NULL
320
+	 */
321
+	public function get_module($module_name = '')
322
+	{
323
+		return isset($this->modules->{$module_name}) ? $this->modules->{$module_name} : null;
324
+	}
325
+
326
+
327
+
328
+	/**
329
+	 *    loads core classes - must be singletons
330
+	 *
331
+	 * @access    public
332
+	 * @param string $class_name - simple class name ie: session
333
+	 * @param mixed  $arguments
334
+	 * @param bool   $load_only
335
+	 * @return mixed
336
+	 */
337
+	public function load_core($class_name, $arguments = array(), $load_only = false)
338
+	{
339
+		$core_paths = apply_filters(
340
+			'FHEE__EE_Registry__load_core__core_paths',
341
+			array(
342
+				EE_CORE,
343
+				EE_ADMIN,
344
+				EE_CPTS,
345
+				EE_CORE . 'data_migration_scripts' . DS,
346
+				EE_CORE . 'request_stack' . DS,
347
+				EE_CORE . 'middleware' . DS,
348
+			)
349
+		);
350
+		// retrieve instantiated class
351
+		return $this->_load($core_paths, 'EE_', $class_name, 'core', $arguments, false, true, $load_only);
352
+	}
353
+
354
+
355
+
356
+	/**
357
+	 *    loads service classes
358
+	 *
359
+	 * @access    public
360
+	 * @param string $class_name - simple class name ie: session
361
+	 * @param mixed  $arguments
362
+	 * @param bool   $load_only
363
+	 * @return mixed
364
+	 */
365
+	public function load_service($class_name, $arguments = array(), $load_only = false)
366
+	{
367
+		$service_paths = apply_filters(
368
+			'FHEE__EE_Registry__load_service__service_paths',
369
+			array(
370
+				EE_CORE . 'services' . DS,
371
+			)
372
+		);
373
+		// retrieve instantiated class
374
+		return $this->_load($service_paths, 'EE_', $class_name, 'class', $arguments, false, true, $load_only);
375
+	}
376
+
377
+
378
+
379
+	/**
380
+	 *    loads data_migration_scripts
381
+	 *
382
+	 * @access    public
383
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
384
+	 * @param mixed  $arguments
385
+	 * @return EE_Data_Migration_Script_Base|mixed
386
+	 */
387
+	public function load_dms($class_name, $arguments = array())
388
+	{
389
+		// retrieve instantiated class
390
+		return $this->_load(EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(), 'EE_DMS_', $class_name, 'dms', $arguments, false, false, false);
391
+	}
392
+
393
+
394
+
395
+	/**
396
+	 *    loads object creating classes - must be singletons
397
+	 *
398
+	 * @param string $class_name - simple class name ie: attendee
399
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
400
+	 * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to instantiate
401
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then set this to FALSE (ie. when instantiating model objects from client in a loop)
402
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate (default)
403
+	 * @return EE_Base_Class | bool
404
+	 */
405
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
406
+	{
407
+		$paths = apply_filters('FHEE__EE_Registry__load_class__paths', array(
408
+			EE_CORE,
409
+			EE_CLASSES,
410
+			EE_BUSINESS,
411
+		));
412
+		// retrieve instantiated class
413
+		return $this->_load($paths, 'EE_', $class_name, 'class', $arguments, $from_db, $cache, $load_only);
414
+	}
415
+
416
+
417
+
418
+	/**
419
+	 *    loads helper classes - must be singletons
420
+	 *
421
+	 * @param string $class_name - simple class name ie: price
422
+	 * @param mixed  $arguments
423
+	 * @param bool   $load_only
424
+	 * @return EEH_Base | bool
425
+	 */
426
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
427
+	{
428
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
429
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
430
+		// retrieve instantiated class
431
+		return $this->_load($helper_paths, 'EEH_', $class_name, 'helper', $arguments, false, true, $load_only);
432
+	}
433
+
434
+
435
+
436
+	/**
437
+	 *    loads core classes - must be singletons
438
+	 *
439
+	 * @access    public
440
+	 * @param string $class_name - simple class name ie: session
441
+	 * @param mixed  $arguments
442
+	 * @param bool   $load_only
443
+	 * @param bool   $cache      whether to cache the object or not.
444
+	 * @return mixed
445
+	 */
446
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
447
+	{
448
+		$paths = array(
449
+			EE_LIBRARIES,
450
+			EE_LIBRARIES . 'messages' . DS,
451
+			EE_LIBRARIES . 'shortcodes' . DS,
452
+			EE_LIBRARIES . 'qtips' . DS,
453
+			EE_LIBRARIES . 'payment_methods' . DS,
454
+		);
455
+		// retrieve instantiated class
456
+		return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, false, $cache, $load_only);
457
+	}
458
+
459
+
460
+
461
+	/**
462
+	 *    loads model classes - must be singletons
463
+	 *
464
+	 * @param string $class_name - simple class name ie: price
465
+	 * @param mixed  $arguments
466
+	 * @param bool   $load_only
467
+	 * @return EEM_Base | bool
468
+	 */
469
+	public function load_model($class_name, $arguments = array(), $load_only = false)
470
+	{
471
+		$paths = apply_filters('FHEE__EE_Registry__load_model__paths', array(
472
+			EE_MODELS,
473
+			EE_CORE,
474
+		));
475
+		// retrieve instantiated class
476
+		return $this->_load($paths, 'EEM_', $class_name, 'model', $arguments, false, true, $load_only);
477
+	}
478
+
479
+
480
+
481
+	/**
482
+	 *    loads model classes - must be singletons
483
+	 *
484
+	 * @param string $class_name - simple class name ie: price
485
+	 * @param mixed  $arguments
486
+	 * @param bool   $load_only
487
+	 * @return mixed | bool
488
+	 */
489
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
490
+	{
491
+		$paths = array(
492
+			EE_MODELS . 'fields' . DS,
493
+			EE_MODELS . 'helpers' . DS,
494
+			EE_MODELS . 'relations' . DS,
495
+			EE_MODELS . 'strategies' . DS,
496
+		);
497
+		// retrieve instantiated class
498
+		return $this->_load($paths, 'EE_', $class_name, '', $arguments, false, true, $load_only);
499
+	}
500
+
501
+
502
+
503
+	/**
504
+	 * Determines if $model_name is the name of an actual EE model.
505
+	 *
506
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
507
+	 * @return boolean
508
+	 */
509
+	public function is_model_name($model_name)
510
+	{
511
+		return isset($this->models[$model_name]) ? true : false;
512
+	}
513
+
514
+
515
+
516
+	/**
517
+	 *    generic class loader
518
+	 *
519
+	 * @param string $path_to_file - directory path to file location, not including filename
520
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
521
+	 * @param string $type         - file type - core? class? helper? model?
522
+	 * @param mixed  $arguments
523
+	 * @param bool   $load_only
524
+	 * @return mixed
525
+	 */
526
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
527
+	{
528
+		// retrieve instantiated class
529
+		return $this->_load($path_to_file, '', $file_name, $type, $arguments, false, true, $load_only);
530
+	}
531
+
532
+
533
+
534
+	/**
535
+	 *    load_addon
536
+	 *
537
+	 * @param string $path_to_file - directory path to file location, not including filename
538
+	 * @param string $class_name   - full class name  ie:  My_Class
539
+	 * @param string $type         - file type - core? class? helper? model?
540
+	 * @param mixed  $arguments
541
+	 * @param bool   $load_only
542
+	 * @return EE_Addon
543
+	 */
544
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
545
+	{
546
+		// retrieve instantiated class
547
+		return $this->_load($path_to_file, 'addon', $class_name, $type, $arguments, false, true, $load_only);
548
+	}
549
+
550
+
551
+
552
+	/**
553
+	 * instantiates, caches, and automatically resolves dependencies
554
+	 * for classes that use a Fully Qualified Class Name.
555
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
556
+	 * then you need to use one of the existing load_*() methods
557
+	 * which can resolve the classname and filepath from the passed arguments
558
+	 *
559
+	 * @param bool|string $class_name   Fully Qualified Class Name
560
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
561
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
562
+	 * @param bool        $from_db      some classes are instantiated from the db
563
+	 *                                  and thus call a different method to instantiate
564
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
565
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
566
+	 * @return mixed                    null = failure to load or instantiate class object.
567
+	 *                                  object = class loaded and instantiated successfully.
568
+	 *                                  bool = fail or success when $load_only is true
569
+	 */
570
+	public function create(
571
+		$class_name = false,
572
+		$arguments = array(),
573
+		$cache = false,
574
+		$from_db = false,
575
+		$load_only = false,
576
+		$addon = false
577
+	) {
578
+		$class_name = $this->_dependency_map->get_alias($class_name);
579
+		if ( ! class_exists($class_name)) {
580
+			// maybe the class is registered with a preceding \
581
+			$class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
582
+			// still doesn't exist ?
583
+			if ( ! class_exists($class_name)) {
584
+				return null;
585
+			}
586
+		}
587
+		// if we're only loading the class and it already exists, then let's just return true immediately
588
+		if ($load_only) {
589
+			return true;
590
+		}
591
+		$addon = $addon ? 'addon' : '';
592
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
593
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
594
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
595
+		if ($this->_cache_on && $cache && ! $load_only) {
596
+			// return object if it's already cached
597
+			$cached_class = $this->_get_cached_class($class_name, $addon);
598
+			if ($cached_class !== null) {
599
+				return $cached_class;
600
+			}
601
+		}
602
+		// instantiate the requested object
603
+		$class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
604
+		if ($this->_cache_on && $cache) {
605
+			// save it for later... kinda like gum  { : $
606
+			$this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
607
+		}
608
+		$this->_cache_on = true;
609
+		return $class_obj;
610
+	}
611
+
612
+
613
+
614
+	/**
615
+	 * instantiates, caches, and injects dependencies for classes
616
+	 *
617
+	 * @param array       $file_paths   an array of paths to folders to look in
618
+	 * @param string      $class_prefix EE  or EEM or... ???
619
+	 * @param bool|string $class_name   $class name
620
+	 * @param string      $type         file type - core? class? helper? model?
621
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
622
+	 * @param bool        $from_db      some classes are instantiated from the db
623
+	 *                                  and thus call a different method to instantiate
624
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
625
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
626
+	 * @return null|object|bool         null = failure to load or instantiate class object.
627
+	 *                                  object = class loaded and instantiated successfully.
628
+	 *                                  bool = fail or success when $load_only is true
629
+	 */
630
+	protected function _load(
631
+		$file_paths = array(),
632
+		$class_prefix = 'EE_',
633
+		$class_name = false,
634
+		$type = 'class',
635
+		$arguments = array(),
636
+		$from_db = false,
637
+		$cache = true,
638
+		$load_only = false
639
+	) {
640
+		// strip php file extension
641
+		$class_name = str_replace('.php', '', trim($class_name));
642
+		// does the class have a prefix ?
643
+		if ( ! empty($class_prefix) && $class_prefix != 'addon') {
644
+			// make sure $class_prefix is uppercase
645
+			$class_prefix = strtoupper(trim($class_prefix));
646
+			// add class prefix ONCE!!!
647
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
648
+		}
649
+		$class_name = $this->_dependency_map->get_alias($class_name);
650
+		$class_exists = class_exists($class_name);
651
+		// if we're only loading the class and it already exists, then let's just return true immediately
652
+		if ($load_only && $class_exists) {
653
+			return true;
654
+		}
655
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
656
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
657
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
658
+		if ($this->_cache_on && $cache && ! $load_only) {
659
+			// return object if it's already cached
660
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix);
661
+			if ($cached_class !== null) {
662
+				return $cached_class;
663
+			}
664
+		}
665
+		// if the class doesn't already exist.. then we need to try and find the file and load it
666
+		if ( ! $class_exists) {
667
+			// get full path to file
668
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
669
+			// load the file
670
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
671
+			// if loading failed, or we are only loading a file but NOT instantiating an object
672
+			if ( ! $loaded || $load_only) {
673
+				// return boolean if only loading, or null if an object was expected
674
+				return $load_only ? $loaded : null;
675
+			}
676
+		}
677
+		// instantiate the requested object
678
+		$class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
679
+		if ($this->_cache_on && $cache) {
680
+			// save it for later... kinda like gum  { : $
681
+			$this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
682
+		}
683
+		$this->_cache_on = true;
684
+		return $class_obj;
685
+	}
686
+
687
+
688
+
689
+	/**
690
+	 * _get_cached_class
691
+	 * attempts to find a cached version of the requested class
692
+	 * by looking in the following places:
693
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
694
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
695
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
696
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
697
+	 *
698
+	 * @access protected
699
+	 * @param string $class_name
700
+	 * @param string $class_prefix
701
+	 * @return mixed
702
+	 */
703
+	protected function _get_cached_class($class_name, $class_prefix = '')
704
+	{
705
+		if (isset($this->_class_abbreviations[$class_name])) {
706
+			$class_abbreviation = $this->_class_abbreviations[$class_name];
707
+		} else {
708
+			// have to specify something, but not anything that will conflict
709
+			$class_abbreviation = 'FANCY_BATMAN_PANTS';
710
+		}
711
+		// check if class has already been loaded, and return it if it has been
712
+		if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
713
+			return $this->{$class_abbreviation};
714
+		} else if (isset ($this->{$class_name})) {
715
+			return $this->{$class_name};
716
+		} else if (isset ($this->LIB->{$class_name})) {
717
+			return $this->LIB->{$class_name};
718
+		} else if ($class_prefix == 'addon' && isset ($this->addons->{$class_name})) {
719
+			return $this->addons->{$class_name};
720
+		}
721
+		return null;
722
+	}
723
+
724
+
725
+
726
+	/**
727
+	 * _resolve_path
728
+	 * attempts to find a full valid filepath for the requested class.
729
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
730
+	 * then returns that path if the target file has been found and is readable
731
+	 *
732
+	 * @access protected
733
+	 * @param string $class_name
734
+	 * @param string $type
735
+	 * @param array  $file_paths
736
+	 * @return string | bool
737
+	 */
738
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
739
+	{
740
+		// make sure $file_paths is an array
741
+		$file_paths = is_array($file_paths) ? $file_paths : array($file_paths);
742
+		// cycle thru paths
743
+		foreach ($file_paths as $key => $file_path) {
744
+			// convert all separators to proper DS, if no filepath, then use EE_CLASSES
745
+			$file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
746
+			// prep file type
747
+			$type = ! empty($type) ? trim($type, '.') . '.' : '';
748
+			// build full file path
749
+			$file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
750
+			//does the file exist and can be read ?
751
+			if (is_readable($file_paths[$key])) {
752
+				return $file_paths[$key];
753
+			}
754
+		}
755
+		return false;
756
+	}
757
+
758
+
759
+
760
+	/**
761
+	 * _require_file
762
+	 * basically just performs a require_once()
763
+	 * but with some error handling
764
+	 *
765
+	 * @access protected
766
+	 * @param  string $path
767
+	 * @param  string $class_name
768
+	 * @param  string $type
769
+	 * @param  array  $file_paths
770
+	 * @return boolean
771
+	 * @throws \EE_Error
772
+	 */
773
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
774
+	{
775
+		// don't give up! you gotta...
776
+		try {
777
+			//does the file exist and can it be read ?
778
+			if ( ! $path) {
779
+				// so sorry, can't find the file
780
+				throw new EE_Error (
781
+					sprintf(
782
+						__('The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s', 'event_espresso'),
783
+						trim($type, '.'),
784
+						$class_name,
785
+						'<br />' . implode(',<br />', $file_paths)
786
+					)
787
+				);
788
+			}
789
+			// get the file
790
+			require_once($path);
791
+			// if the class isn't already declared somewhere
792
+			if (class_exists($class_name, false) === false) {
793
+				// so sorry, not a class
794
+				throw new EE_Error(
795
+					sprintf(
796
+						__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
797
+						$type,
798
+						$path,
799
+						$class_name
800
+					)
801
+				);
802
+			}
803
+		} catch (EE_Error $e) {
804
+			$e->get_error();
805
+			return false;
806
+		}
807
+		return true;
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * _create_object
814
+	 * Attempts to instantiate the requested class via any of the
815
+	 * commonly used instantiation methods employed throughout EE.
816
+	 * The priority for instantiation is as follows:
817
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
818
+	 *        - model objects via their 'new_instance_from_db' method
819
+	 *        - model objects via their 'new_instance' method
820
+	 *        - "singleton" classes" via their 'instance' method
821
+	 *    - standard instantiable classes via their __constructor
822
+	 * Prior to instantiation, if the classname exists in the dependency_map,
823
+	 * then the constructor for the requested class will be examined to determine
824
+	 * if any dependencies exist, and if they can be injected.
825
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
826
+	 *
827
+	 * @access protected
828
+	 * @param string $class_name
829
+	 * @param array  $arguments
830
+	 * @param string $type
831
+	 * @param bool   $from_db
832
+	 * @return null | object
833
+	 * @throws \EE_Error
834
+	 */
835
+	protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
836
+	{
837
+		$class_obj = null;
838
+		$instantiation_mode = '0) none';
839
+		// don't give up! you gotta...
840
+		try {
841
+			// create reflection
842
+			$reflector = $this->get_ReflectionClass($class_name);
843
+			// make sure arguments are an array
844
+			$arguments = is_array($arguments) ? $arguments : array($arguments);
845
+			// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
846
+			// else wrap it in an additional array so that it doesn't get split into multiple parameters
847
+			$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
848
+				? $arguments
849
+				: array($arguments);
850
+			// attempt to inject dependencies ?
851
+			if ($this->_dependency_map->has($class_name)) {
852
+				$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
853
+			}
854
+			// instantiate the class if possible
855
+			if ($reflector->isAbstract()) {
856
+				// nothing to instantiate, loading file was enough
857
+				// does not throw an exception so $instantiation_mode is unused
858
+				// $instantiation_mode = "1) no constructor abstract class";
859
+				$class_obj = true;
860
+			} else if ($reflector->getConstructor() === null && $reflector->isInstantiable() && empty($arguments)) {
861
+				// no constructor = static methods only... nothing to instantiate, loading file was enough
862
+				$instantiation_mode = "2) no constructor but instantiable";
863
+				$class_obj = $reflector->newInstance();
864
+			} else if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
865
+				$instantiation_mode = "3) new_instance_from_db()";
866
+				$class_obj = call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
867
+			} else if (method_exists($class_name, 'new_instance')) {
868
+				$instantiation_mode = "4) new_instance()";
869
+				$class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
870
+			} else if (method_exists($class_name, 'instance')) {
871
+				$instantiation_mode = "5) instance()";
872
+				$class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
873
+			} else if ($reflector->isInstantiable()) {
874
+				$instantiation_mode = "6) constructor";
875
+				$class_obj = $reflector->newInstanceArgs($arguments);
876
+			} else {
877
+				// heh ? something's not right !
878
+				throw new EE_Error(
879
+					sprintf(
880
+						__('The %s file %s could not be instantiated.', 'event_espresso'),
881
+						$type,
882
+						$class_name
883
+					)
884
+				);
885
+			}
886
+		} catch (Exception $e) {
887
+			if ( ! $e instanceof EE_Error) {
888
+				$e = new EE_Error(
889
+					sprintf(
890
+						__('The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s', 'event_espresso'),
891
+						$class_name,
892
+						'<br />',
893
+						$e->getMessage(),
894
+						$instantiation_mode
895
+					)
896
+				);
897
+			}
898
+			$e->get_error();
899
+		}
900
+		return $class_obj;
901
+	}
902
+
903
+
904
+
905
+	/**
906
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
907
+	 * @param array $array
908
+	 * @return bool
909
+	 */
910
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
911
+	{
912
+		return ! empty($array) ? array_keys($array) === range(0, count($array) - 1) : true;
913
+	}
914
+
915
+
916
+
917
+	/**
918
+	 * getReflectionClass
919
+	 * checks if a ReflectionClass object has already been generated for a class
920
+	 * and returns that instead of creating a new one
921
+	 *
922
+	 * @access public
923
+	 * @param string $class_name
924
+	 * @return ReflectionClass
925
+	 */
926
+	public function get_ReflectionClass($class_name)
927
+	{
928
+		if (
929
+			! isset($this->_reflectors[$class_name])
930
+			|| ! $this->_reflectors[$class_name] instanceof ReflectionClass
931
+		) {
932
+			$this->_reflectors[$class_name] = new ReflectionClass($class_name);
933
+		}
934
+		return $this->_reflectors[$class_name];
935
+	}
936
+
937
+
938
+
939
+	/**
940
+	 * _resolve_dependencies
941
+	 * examines the constructor for the requested class to determine
942
+	 * if any dependencies exist, and if they can be injected.
943
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
944
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
945
+	 * For example:
946
+	 *        if attempting to load a class "Foo" with the following constructor:
947
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
948
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
949
+	 *        but only IF they are NOT already present in the incoming arguments array,
950
+	 *        and the correct classes can be loaded
951
+	 *
952
+	 * @access protected
953
+	 * @param ReflectionClass $reflector
954
+	 * @param string          $class_name
955
+	 * @param array           $arguments
956
+	 * @return array
957
+	 * @throws \ReflectionException
958
+	 */
959
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
960
+	{
961
+		// let's examine the constructor
962
+		$constructor = $reflector->getConstructor();
963
+		// whu? huh? nothing?
964
+		if ( ! $constructor) {
965
+			return $arguments;
966
+		}
967
+		// get constructor parameters
968
+		$params = $constructor->getParameters();
969
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
970
+		$argument_keys = array_keys($arguments);
971
+		// now loop thru all of the constructors expected parameters
972
+		foreach ($params as $index => $param) {
973
+			// is this a dependency for a specific class ?
974
+			$param_class = $param->getClass() ? $param->getClass()->name : null;
975
+			if (
976
+				// param is not even a class
977
+				empty($param_class)
978
+				// and something already exists in the incoming arguments for this param
979
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
980
+			) {
981
+				// so let's skip this argument and move on to the next
982
+				continue;
983
+			} else if (
984
+				// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
985
+				! empty($param_class)
986
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
987
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
988
+			) {
989
+				// skip this argument and move on to the next
990
+				continue;
991
+			} else if (
992
+				// parameter is type hinted as a class, and should be injected
993
+				! empty($param_class)
994
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
995
+			) {
996
+				$arguments = $this->_resolve_dependency($class_name, $param_class, $arguments, $index);
997
+			} else {
998
+				try {
999
+					$arguments[$index] = $param->getDefaultValue();
1000
+				} catch (ReflectionException $e) {
1001
+					throw new ReflectionException(
1002
+						sprintf(
1003
+							__('%1$s for parameter "$%2$s"', 'event_espresso'),
1004
+							$e->getMessage(),
1005
+							$param->getName()
1006
+						)
1007
+					);
1008
+				}
1009
+			}
1010
+		}
1011
+		return $arguments;
1012
+	}
1013
+
1014
+
1015
+
1016
+	/**
1017
+	 * @access protected
1018
+	 * @param string $class_name
1019
+	 * @param string $param_class
1020
+	 * @param array  $arguments
1021
+	 * @param mixed  $index
1022
+	 * @return array
1023
+	 */
1024
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1025
+	{
1026
+		$dependency = null;
1027
+		// should dependency be loaded from cache ?
1028
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $param_class)
1029
+					!== EE_Dependency_Map::load_new_object
1030
+			? true
1031
+			: false;
1032
+		// we might have a dependency...
1033
+		// let's MAYBE try and find it in our cache if that's what's been requested
1034
+		$cached_class = $cache_on ? $this->_get_cached_class($param_class) : null;
1035
+		// and grab it if it exists
1036
+		if ($cached_class instanceof $param_class) {
1037
+			$dependency = $cached_class;
1038
+		} else if ($param_class != $class_name) {
1039
+			// obtain the loader method from the dependency map
1040
+			$loader = $this->_dependency_map->class_loader($param_class);
1041
+			// is loader a custom closure ?
1042
+			if ($loader instanceof Closure) {
1043
+				$dependency = $loader();
1044
+			} else {
1045
+				// set the cache on property for the recursive loading call
1046
+				$this->_cache_on = $cache_on;
1047
+				// if not, then let's try and load it via the registry
1048
+				if (method_exists($this, $loader)) {
1049
+					$dependency = $this->{$loader}($param_class);
1050
+				} else {
1051
+					$dependency = $this->create($param_class, array(), $cache_on);
1052
+				}
1053
+			}
1054
+		}
1055
+		// did we successfully find the correct dependency ?
1056
+		if ($dependency instanceof $param_class) {
1057
+			// then let's inject it into the incoming array of arguments at the correct location
1058
+			if (isset($argument_keys[$index])) {
1059
+				$arguments[$argument_keys[$index]] = $dependency;
1060
+			} else {
1061
+				$arguments[$index] = $dependency;
1062
+			}
1063
+		}
1064
+		return $arguments;
1065
+	}
1066
+
1067
+
1068
+
1069
+	/**
1070
+	 * _set_cached_class
1071
+	 * attempts to cache the instantiated class locally
1072
+	 * in one of the following places, in the following order:
1073
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1074
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1075
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1076
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1077
+	 *
1078
+	 * @access protected
1079
+	 * @param object $class_obj
1080
+	 * @param string $class_name
1081
+	 * @param string $class_prefix
1082
+	 * @param bool   $from_db
1083
+	 * @return void
1084
+	 */
1085
+	protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1086
+	{
1087
+		if (empty($class_obj)) {
1088
+			return;
1089
+		}
1090
+		// return newly instantiated class
1091
+		if (isset($this->_class_abbreviations[$class_name])) {
1092
+			$class_abbreviation = $this->_class_abbreviations[$class_name];
1093
+			$this->{$class_abbreviation} = $class_obj;
1094
+		} else if (property_exists($this, $class_name)) {
1095
+			$this->{$class_name} = $class_obj;
1096
+		} else if ($class_prefix == 'addon') {
1097
+			$this->addons->{$class_name} = $class_obj;
1098
+		} else if ( ! $from_db) {
1099
+			$this->LIB->{$class_name} = $class_obj;
1100
+		}
1101
+	}
1102
+
1103
+
1104
+
1105
+	/**
1106
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1107
+	 *
1108
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1109
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1110
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1111
+	 * @param array  $arguments
1112
+	 * @return object
1113
+	 */
1114
+	public static function factory($classname, $arguments = array())
1115
+	{
1116
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1117
+		if ($loader instanceof Closure) {
1118
+			return $loader($arguments);
1119
+		} else if (method_exists(EE_Registry::instance(), $loader)) {
1120
+			return EE_Registry::instance()->{$loader}($classname, $arguments);
1121
+		}
1122
+		return null;
1123
+	}
1124
+
1125
+
1126
+
1127
+	/**
1128
+	 * Gets the addon by its name/slug (not classname. For that, just
1129
+	 * use the classname as the property name on EE_Config::instance()->addons)
1130
+	 *
1131
+	 * @param string $name
1132
+	 * @return EE_Addon
1133
+	 */
1134
+	public function get_addon_by_name($name)
1135
+	{
1136
+		foreach ($this->addons as $addon) {
1137
+			if ($addon->name() == $name) {
1138
+				return $addon;
1139
+			}
1140
+		}
1141
+		return null;
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their name() function) They're already available on EE_Config::instance()->addons as properties, where each property's name is
1148
+	 * the addon's classname. So if you just want to get the addon by classname, use EE_Config::instance()->addons->{classname}
1149
+	 *
1150
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1151
+	 */
1152
+	public function get_addons_by_name()
1153
+	{
1154
+		$addons = array();
1155
+		foreach ($this->addons as $addon) {
1156
+			$addons[$addon->name()] = $addon;
1157
+		}
1158
+		return $addons;
1159
+	}
1160
+
1161
+
1162
+
1163
+	/**
1164
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1165
+	 * a stale copy of it around
1166
+	 *
1167
+	 * @param string $model_name
1168
+	 * @return \EEM_Base
1169
+	 * @throws \EE_Error
1170
+	 */
1171
+	public function reset_model($model_name)
1172
+	{
1173
+		$model_class_name = strpos($model_name, 'EEM_') !== 0 ? "EEM_{$model_name}" : $model_name;
1174
+		if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1175
+			return null;
1176
+		}
1177
+		//get that model reset it and make sure we nuke the old reference to it
1178
+		if ($this->LIB->{$model_class_name} instanceof $model_class_name && is_callable(array($model_class_name, 'reset'))) {
1179
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1180
+		} else {
1181
+			throw new EE_Error(sprintf(__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1182
+		}
1183
+		return $this->LIB->{$model_class_name};
1184
+	}
1185
+
1186
+
1187
+
1188
+	/**
1189
+	 * Resets the registry.
1190
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when switch_to_blog
1191
+	 * is used in a multisite install.  Here is a list of things that are NOT reset.
1192
+	 * - $_dependency_map
1193
+	 * - $_class_abbreviations
1194
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1195
+	 * - $REQ:  Still on the same request so no need to change.
1196
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1197
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only one Session
1198
+	 *         can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1199
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1200
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1201
+	 *             switch or on the restore.
1202
+	 * - $modules
1203
+	 * - $shortcodes
1204
+	 * - $widgets
1205
+	 *
1206
+	 * @param boolean $hard             whether to reset data in the database too, or just refresh
1207
+	 *                                  the Registry to its state at the beginning of the request
1208
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1209
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not sure if you CAN
1210
+	 *                                  currently reinstantiate the singletons at the moment)
1211
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so client
1212
+	 *                                  code instead can just change the model context to a different blog id if necessary
1213
+	 * @return EE_Registry
1214
+	 */
1215
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1216
+	{
1217
+		$instance = self::instance();
1218
+		EEH_Activation::reset();
1219
+		//properties that get reset
1220
+		$instance->_cache_on = true;
1221
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1222
+		$instance->CART = null;
1223
+		$instance->MRM = null;
1224
+		//messages reset
1225
+		EED_Messages::reset();
1226
+		if ($reset_models) {
1227
+			foreach (array_keys($instance->non_abstract_db_models) as $model_name) {
1228
+				$instance->reset_model($model_name);
1229
+			}
1230
+		}
1231
+		$instance->LIB = new stdClass();
1232
+		return $instance;
1233
+	}
1234
+
1235
+
1236
+
1237
+	/**
1238
+	 * @override magic methods
1239
+	 * @return void
1240
+	 */
1241
+	final function __destruct()
1242
+	{
1243
+	}
1244
+
1245
+
1246
+
1247
+	/**
1248
+	 * @param $a
1249
+	 * @param $b
1250
+	 */
1251
+	final function __call($a, $b)
1252
+	{
1253
+	}
1254
+
1255
+
1256
+
1257
+	/**
1258
+	 * @param $a
1259
+	 */
1260
+	final function __get($a)
1261
+	{
1262
+	}
1263
+
1264
+
1265
+
1266
+	/**
1267
+	 * @param $a
1268
+	 * @param $b
1269
+	 */
1270
+	final function __set($a, $b)
1271
+	{
1272
+	}
1273
+
1274
+
1275
+
1276
+	/**
1277
+	 * @param $a
1278
+	 */
1279
+	final function __isset($a)
1280
+	{
1281
+	}
1282 1282
 
1283 1283
 
1284 1284
 
1285
-    /**
1286
-     * @param $a
1287
-     */
1288
-    final function __unset($a)
1289
-    {
1290
-    }
1285
+	/**
1286
+	 * @param $a
1287
+	 */
1288
+	final function __unset($a)
1289
+	{
1290
+	}
1291 1291
 
1292 1292
 
1293 1293
 
1294
-    /**
1295
-     * @return array
1296
-     */
1297
-    final function __sleep()
1298
-    {
1299
-        return array();
1300
-    }
1294
+	/**
1295
+	 * @return array
1296
+	 */
1297
+	final function __sleep()
1298
+	{
1299
+		return array();
1300
+	}
1301 1301
 
1302 1302
 
1303 1303
 
1304
-    final function __wakeup()
1305
-    {
1306
-    }
1304
+	final function __wakeup()
1305
+	{
1306
+	}
1307 1307
 
1308 1308
 
1309 1309
 
1310
-    /**
1311
-     * @return string
1312
-     */
1313
-    final function __toString()
1314
-    {
1315
-        return '';
1316
-    }
1310
+	/**
1311
+	 * @return string
1312
+	 */
1313
+	final function __toString()
1314
+	{
1315
+		return '';
1316
+	}
1317 1317
 
1318 1318
 
1319 1319
 
1320
-    final function __invoke()
1321
-    {
1322
-    }
1320
+	final function __invoke()
1321
+	{
1322
+	}
1323 1323
 
1324 1324
 
1325 1325
 
1326
-    final function __set_state()
1327
-    {
1328
-    }
1326
+	final function __set_state()
1327
+	{
1328
+	}
1329 1329
 
1330 1330
 
1331 1331
 
1332
-    final function __clone()
1333
-    {
1334
-    }
1332
+	final function __clone()
1333
+	{
1334
+	}
1335 1335
 
1336 1336
 
1337 1337
 
1338
-    /**
1339
-     * @param $a
1340
-     * @param $b
1341
-     */
1342
-    final static function __callStatic($a, $b)
1343
-    {
1344
-    }
1338
+	/**
1339
+	 * @param $a
1340
+	 * @param $b
1341
+	 */
1342
+	final static function __callStatic($a, $b)
1343
+	{
1344
+	}
1345 1345
 
1346 1346
 
1347 1347
 
1348
-    /**
1349
-     * Gets all the custom post type models defined
1350
-     *
1351
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1352
-     */
1353
-    public function cpt_models()
1354
-    {
1355
-        $cpt_models = array();
1356
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1357
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1358
-                $cpt_models[$short_name] = $classname;
1359
-            }
1360
-        }
1361
-        return $cpt_models;
1362
-    }
1348
+	/**
1349
+	 * Gets all the custom post type models defined
1350
+	 *
1351
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1352
+	 */
1353
+	public function cpt_models()
1354
+	{
1355
+		$cpt_models = array();
1356
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1357
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1358
+				$cpt_models[$short_name] = $classname;
1359
+			}
1360
+		}
1361
+		return $cpt_models;
1362
+	}
1363 1363
 
1364 1364
 
1365 1365
 
1366
-    /**
1367
-     * @return \EE_Config
1368
-     */
1369
-    public static function CFG()
1370
-    {
1371
-        return self::instance()->CFG;
1372
-    }
1366
+	/**
1367
+	 * @return \EE_Config
1368
+	 */
1369
+	public static function CFG()
1370
+	{
1371
+		return self::instance()->CFG;
1372
+	}
1373 1373
 
1374 1374
 
1375 1375
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -285,13 +285,13 @@  discard block
 block discarded – undo
285 285
      */
286 286
     public static function localize_i18n_js_strings()
287 287
     {
288
-        $i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
288
+        $i18n_js_strings = (array) EE_Registry::$i18n_js_strings;
289 289
         foreach ($i18n_js_strings as $key => $value) {
290 290
             if (is_scalar($value)) {
291
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
291
+                $i18n_js_strings[$key] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
292 292
             }
293 293
         }
294
-        return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
294
+        return "/* <![CDATA[ */ var eei18n = ".wp_json_encode($i18n_js_strings).'; /* ]]> */';
295 295
     }
296 296
 
297 297
 
@@ -342,9 +342,9 @@  discard block
 block discarded – undo
342 342
                 EE_CORE,
343 343
                 EE_ADMIN,
344 344
                 EE_CPTS,
345
-                EE_CORE . 'data_migration_scripts' . DS,
346
-                EE_CORE . 'request_stack' . DS,
347
-                EE_CORE . 'middleware' . DS,
345
+                EE_CORE.'data_migration_scripts'.DS,
346
+                EE_CORE.'request_stack'.DS,
347
+                EE_CORE.'middleware'.DS,
348 348
             )
349 349
         );
350 350
         // retrieve instantiated class
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
         $service_paths = apply_filters(
368 368
             'FHEE__EE_Registry__load_service__service_paths',
369 369
             array(
370
-                EE_CORE . 'services' . DS,
370
+                EE_CORE.'services'.DS,
371 371
             )
372 372
         );
373 373
         // retrieve instantiated class
@@ -447,10 +447,10 @@  discard block
 block discarded – undo
447 447
     {
448 448
         $paths = array(
449 449
             EE_LIBRARIES,
450
-            EE_LIBRARIES . 'messages' . DS,
451
-            EE_LIBRARIES . 'shortcodes' . DS,
452
-            EE_LIBRARIES . 'qtips' . DS,
453
-            EE_LIBRARIES . 'payment_methods' . DS,
450
+            EE_LIBRARIES.'messages'.DS,
451
+            EE_LIBRARIES.'shortcodes'.DS,
452
+            EE_LIBRARIES.'qtips'.DS,
453
+            EE_LIBRARIES.'payment_methods'.DS,
454 454
         );
455 455
         // retrieve instantiated class
456 456
         return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, false, $cache, $load_only);
@@ -489,10 +489,10 @@  discard block
 block discarded – undo
489 489
     public function load_model_class($class_name, $arguments = array(), $load_only = true)
490 490
     {
491 491
         $paths = array(
492
-            EE_MODELS . 'fields' . DS,
493
-            EE_MODELS . 'helpers' . DS,
494
-            EE_MODELS . 'relations' . DS,
495
-            EE_MODELS . 'strategies' . DS,
492
+            EE_MODELS.'fields'.DS,
493
+            EE_MODELS.'helpers'.DS,
494
+            EE_MODELS.'relations'.DS,
495
+            EE_MODELS.'strategies'.DS,
496 496
         );
497 497
         // retrieve instantiated class
498 498
         return $this->_load($paths, 'EE_', $class_name, '', $arguments, false, true, $load_only);
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
         $class_name = $this->_dependency_map->get_alias($class_name);
579 579
         if ( ! class_exists($class_name)) {
580 580
             // maybe the class is registered with a preceding \
581
-            $class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
581
+            $class_name = strpos($class_name, '\\') !== 0 ? '\\'.$class_name : $class_name;
582 582
             // still doesn't exist ?
583 583
             if ( ! class_exists($class_name)) {
584 584
                 return null;
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
             // make sure $class_prefix is uppercase
645 645
             $class_prefix = strtoupper(trim($class_prefix));
646 646
             // add class prefix ONCE!!!
647
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
647
+            $class_name = $class_prefix.str_replace($class_prefix, '', $class_name);
648 648
         }
649 649
         $class_name = $this->_dependency_map->get_alias($class_name);
650 650
         $class_exists = class_exists($class_name);
@@ -744,9 +744,9 @@  discard block
 block discarded – undo
744 744
             // convert all separators to proper DS, if no filepath, then use EE_CLASSES
745 745
             $file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
746 746
             // prep file type
747
-            $type = ! empty($type) ? trim($type, '.') . '.' : '';
747
+            $type = ! empty($type) ? trim($type, '.').'.' : '';
748 748
             // build full file path
749
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
749
+            $file_paths[$key] = rtrim($file_path, DS).DS.$class_name.'.'.$type.'php';
750 750
             //does the file exist and can be read ?
751 751
             if (is_readable($file_paths[$key])) {
752 752
                 return $file_paths[$key];
@@ -777,12 +777,12 @@  discard block
 block discarded – undo
777 777
             //does the file exist and can it be read ?
778 778
             if ( ! $path) {
779 779
                 // so sorry, can't find the file
780
-                throw new EE_Error (
780
+                throw new EE_Error(
781 781
                     sprintf(
782 782
                         __('The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s', 'event_espresso'),
783 783
                         trim($type, '.'),
784 784
                         $class_name,
785
-                        '<br />' . implode(',<br />', $file_paths)
785
+                        '<br />'.implode(',<br />', $file_paths)
786 786
                     )
787 787
                 );
788 788
             }
Please login to merge, or discard this patch.
core/helpers/EEH_Activation.helper.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
      *
614 614
      * @since  4.6.0
615 615
      * @global WPDB $wpdb
616
-     * @return mixed null|int WP_user ID or NULL
616
+     * @return integer|null null|int WP_user ID or NULL
617 617
      */
618 618
     public static function get_default_creator_id()
619 619
     {
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
      * @static
775 775
      * @deprecated instead use TableManager::dropTable()
776 776
      * @param string $table_name
777
-     * @return bool | int
777
+     * @return integer | int
778 778
      */
779 779
     public static function delete_unused_db_table($table_name)
780 780
     {
@@ -791,7 +791,7 @@  discard block
 block discarded – undo
791 791
      * @deprecated instead use TableManager::dropIndex()
792 792
      * @param string $table_name
793 793
      * @param string $index_name
794
-     * @return bool | int
794
+     * @return integer | int
795 795
      */
796 796
     public static function drop_index($table_name, $index_name)
797 797
     {
Please login to merge, or discard this patch.
Indentation   +1650 added lines, -1650 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -14,236 +14,236 @@  discard block
 block discarded – undo
14 14
 class EEH_Activation
15 15
 {
16 16
 
17
-    /**
18
-     * constant used to indicate a cron task is no longer in use
19
-     */
20
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
21
-
22
-    /**
23
-     * option name that will indicate whether or not we still
24
-     * need to create EE's folders in the uploads directory
25
-     * (because if EE was installed without file system access,
26
-     * we need to request credentials before we can create them)
27
-     */
28
-    const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
29
-
30
-    /**
31
-     * WP_User->ID
32
-     *
33
-     * @var int
34
-     */
35
-    private static $_default_creator_id;
36
-
37
-    /**
38
-     * indicates whether or not we've already verified core's default data during this request,
39
-     * because after migrations are done, any addons activated while in maintenance mode
40
-     * will want to setup their own default data, and they might hook into core's default data
41
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
42
-     * This prevents doing that for EVERY single addon.
43
-     *
44
-     * @var boolean
45
-     */
46
-    protected static $_initialized_db_content_already_in_this_request = false;
47
-
48
-    /**
49
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
50
-     */
51
-    private static $table_analysis;
52
-
53
-    /**
54
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
55
-     */
56
-    private static $table_manager;
57
-
58
-
59
-
60
-    /**
61
-     * @return \EventEspresso\core\services\database\TableAnalysis
62
-     */
63
-    public static function getTableAnalysis()
64
-    {
65
-        if ( ! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
66
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
67
-        }
68
-        return self::$table_analysis;
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * @return \EventEspresso\core\services\database\TableManager
75
-     */
76
-    public static function getTableManager()
77
-    {
78
-        if ( ! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
79
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
80
-        }
81
-        return self::$table_manager;
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     *    _ensure_table_name_has_prefix
88
-     *
89
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
90
-     * @access     public
91
-     * @static
92
-     * @param $table_name
93
-     * @return string
94
-     */
95
-    public static function ensure_table_name_has_prefix($table_name)
96
-    {
97
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
98
-    }
99
-
100
-
101
-
102
-    /**
103
-     *    system_initialization
104
-     *    ensures the EE configuration settings are loaded with at least default options set
105
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
106
-     *
107
-     * @access public
108
-     * @static
109
-     * @return void
110
-     */
111
-    public static function system_initialization()
112
-    {
113
-        EEH_Activation::reset_and_update_config();
114
-        //which is fired BEFORE activation of plugin anyways
115
-        EEH_Activation::verify_default_pages_exist();
116
-    }
117
-
118
-
119
-
120
-    /**
121
-     * Sets the database schema and creates folders. This should
122
-     * be called on plugin activation and reactivation
123
-     *
124
-     * @return boolean success, whether the database and folders are setup properly
125
-     * @throws \EE_Error
126
-     */
127
-    public static function initialize_db_and_folders()
128
-    {
129
-        $good_filesystem = EEH_Activation::create_upload_directories();
130
-        $good_db = EEH_Activation::create_database_tables();
131
-        return $good_filesystem && $good_db;
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * assuming we have an up-to-date database schema, this will populate it
138
-     * with default and initial data. This should be called
139
-     * upon activation of a new plugin, reactivation, and at the end
140
-     * of running migration scripts
141
-     *
142
-     * @throws \EE_Error
143
-     */
144
-    public static function initialize_db_content()
145
-    {
146
-        //let's avoid doing all this logic repeatedly, especially when addons are requesting it
147
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
148
-            return;
149
-        }
150
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
151
-        EEH_Activation::initialize_system_questions();
152
-        EEH_Activation::insert_default_status_codes();
153
-        EEH_Activation::generate_default_message_templates();
154
-        EEH_Activation::create_no_ticket_prices_array();
155
-        EE_Registry::instance()->CAP->init_caps();
156
-        EEH_Activation::validate_messages_system();
157
-        EEH_Activation::insert_default_payment_methods();
158
-        //in case we've
159
-        EEH_Activation::remove_cron_tasks();
160
-        EEH_Activation::create_cron_tasks();
161
-        // remove all TXN locks since that is being done via extra meta now
162
-        delete_option('ee_locked_transactions');
163
-        //also, check for CAF default db content
164
-        do_action('AHEE__EEH_Activation__initialize_db_content');
165
-        //also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
166
-        //which users really won't care about on initial activation
167
-        EE_Error::overwrite_success();
168
-    }
169
-
170
-
171
-
172
-    /**
173
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
174
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
175
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
176
-     * (null)
177
-     *
178
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
179
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
180
-     * @return array
181
-     * @throws \EE_Error
182
-     */
183
-    public static function get_cron_tasks($which_to_include)
184
-    {
185
-        $cron_tasks = apply_filters(
186
-            'FHEE__EEH_Activation__get_cron_tasks',
187
-            array(
188
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
189
-                //				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
190
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
191
-                //there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
192
-            )
193
-        );
194
-        if ($which_to_include === 'old') {
195
-            $cron_tasks = array_filter(
196
-                $cron_tasks,
197
-                function ($value) {
198
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
199
-                }
200
-            );
201
-        } elseif ($which_to_include === 'current') {
202
-            $cron_tasks = array_filter($cron_tasks);
203
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
204
-            throw new EE_Error(
205
-                sprintf(
206
-                    __(
207
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
208
-                        'event_espresso'
209
-                    ),
210
-                    $which_to_include
211
-                )
212
-            );
213
-        }
214
-        return $cron_tasks;
215
-    }
216
-
217
-
218
-
219
-    /**
220
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
221
-     *
222
-     * @throws \EE_Error
223
-     */
224
-    public static function create_cron_tasks()
225
-    {
226
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
227
-            if ( ! wp_next_scheduled($hook_name)) {
228
-                wp_schedule_event(time(), $frequency, $hook_name);
229
-            }
230
-        }
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * Remove the currently-existing and now-removed cron tasks.
237
-     *
238
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
239
-     * @throws \EE_Error
240
-     */
241
-    public static function remove_cron_tasks($remove_all = true)
242
-    {
243
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
244
-        $crons = _get_cron_array();
245
-        $crons = is_array($crons) ? $crons : array();
246
-        /* reminder of what $crons look like:
17
+	/**
18
+	 * constant used to indicate a cron task is no longer in use
19
+	 */
20
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
21
+
22
+	/**
23
+	 * option name that will indicate whether or not we still
24
+	 * need to create EE's folders in the uploads directory
25
+	 * (because if EE was installed without file system access,
26
+	 * we need to request credentials before we can create them)
27
+	 */
28
+	const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
29
+
30
+	/**
31
+	 * WP_User->ID
32
+	 *
33
+	 * @var int
34
+	 */
35
+	private static $_default_creator_id;
36
+
37
+	/**
38
+	 * indicates whether or not we've already verified core's default data during this request,
39
+	 * because after migrations are done, any addons activated while in maintenance mode
40
+	 * will want to setup their own default data, and they might hook into core's default data
41
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
42
+	 * This prevents doing that for EVERY single addon.
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	protected static $_initialized_db_content_already_in_this_request = false;
47
+
48
+	/**
49
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
50
+	 */
51
+	private static $table_analysis;
52
+
53
+	/**
54
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
55
+	 */
56
+	private static $table_manager;
57
+
58
+
59
+
60
+	/**
61
+	 * @return \EventEspresso\core\services\database\TableAnalysis
62
+	 */
63
+	public static function getTableAnalysis()
64
+	{
65
+		if ( ! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
66
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
67
+		}
68
+		return self::$table_analysis;
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * @return \EventEspresso\core\services\database\TableManager
75
+	 */
76
+	public static function getTableManager()
77
+	{
78
+		if ( ! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
79
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
80
+		}
81
+		return self::$table_manager;
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 *    _ensure_table_name_has_prefix
88
+	 *
89
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
90
+	 * @access     public
91
+	 * @static
92
+	 * @param $table_name
93
+	 * @return string
94
+	 */
95
+	public static function ensure_table_name_has_prefix($table_name)
96
+	{
97
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
98
+	}
99
+
100
+
101
+
102
+	/**
103
+	 *    system_initialization
104
+	 *    ensures the EE configuration settings are loaded with at least default options set
105
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
106
+	 *
107
+	 * @access public
108
+	 * @static
109
+	 * @return void
110
+	 */
111
+	public static function system_initialization()
112
+	{
113
+		EEH_Activation::reset_and_update_config();
114
+		//which is fired BEFORE activation of plugin anyways
115
+		EEH_Activation::verify_default_pages_exist();
116
+	}
117
+
118
+
119
+
120
+	/**
121
+	 * Sets the database schema and creates folders. This should
122
+	 * be called on plugin activation and reactivation
123
+	 *
124
+	 * @return boolean success, whether the database and folders are setup properly
125
+	 * @throws \EE_Error
126
+	 */
127
+	public static function initialize_db_and_folders()
128
+	{
129
+		$good_filesystem = EEH_Activation::create_upload_directories();
130
+		$good_db = EEH_Activation::create_database_tables();
131
+		return $good_filesystem && $good_db;
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 * assuming we have an up-to-date database schema, this will populate it
138
+	 * with default and initial data. This should be called
139
+	 * upon activation of a new plugin, reactivation, and at the end
140
+	 * of running migration scripts
141
+	 *
142
+	 * @throws \EE_Error
143
+	 */
144
+	public static function initialize_db_content()
145
+	{
146
+		//let's avoid doing all this logic repeatedly, especially when addons are requesting it
147
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
148
+			return;
149
+		}
150
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
151
+		EEH_Activation::initialize_system_questions();
152
+		EEH_Activation::insert_default_status_codes();
153
+		EEH_Activation::generate_default_message_templates();
154
+		EEH_Activation::create_no_ticket_prices_array();
155
+		EE_Registry::instance()->CAP->init_caps();
156
+		EEH_Activation::validate_messages_system();
157
+		EEH_Activation::insert_default_payment_methods();
158
+		//in case we've
159
+		EEH_Activation::remove_cron_tasks();
160
+		EEH_Activation::create_cron_tasks();
161
+		// remove all TXN locks since that is being done via extra meta now
162
+		delete_option('ee_locked_transactions');
163
+		//also, check for CAF default db content
164
+		do_action('AHEE__EEH_Activation__initialize_db_content');
165
+		//also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
166
+		//which users really won't care about on initial activation
167
+		EE_Error::overwrite_success();
168
+	}
169
+
170
+
171
+
172
+	/**
173
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
174
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
175
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
176
+	 * (null)
177
+	 *
178
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
179
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
180
+	 * @return array
181
+	 * @throws \EE_Error
182
+	 */
183
+	public static function get_cron_tasks($which_to_include)
184
+	{
185
+		$cron_tasks = apply_filters(
186
+			'FHEE__EEH_Activation__get_cron_tasks',
187
+			array(
188
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
189
+				//				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
190
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
191
+				//there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
192
+			)
193
+		);
194
+		if ($which_to_include === 'old') {
195
+			$cron_tasks = array_filter(
196
+				$cron_tasks,
197
+				function ($value) {
198
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
199
+				}
200
+			);
201
+		} elseif ($which_to_include === 'current') {
202
+			$cron_tasks = array_filter($cron_tasks);
203
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
204
+			throw new EE_Error(
205
+				sprintf(
206
+					__(
207
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
208
+						'event_espresso'
209
+					),
210
+					$which_to_include
211
+				)
212
+			);
213
+		}
214
+		return $cron_tasks;
215
+	}
216
+
217
+
218
+
219
+	/**
220
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
221
+	 *
222
+	 * @throws \EE_Error
223
+	 */
224
+	public static function create_cron_tasks()
225
+	{
226
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
227
+			if ( ! wp_next_scheduled($hook_name)) {
228
+				wp_schedule_event(time(), $frequency, $hook_name);
229
+			}
230
+		}
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * Remove the currently-existing and now-removed cron tasks.
237
+	 *
238
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
239
+	 * @throws \EE_Error
240
+	 */
241
+	public static function remove_cron_tasks($remove_all = true)
242
+	{
243
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
244
+		$crons = _get_cron_array();
245
+		$crons = is_array($crons) ? $crons : array();
246
+		/* reminder of what $crons look like:
247 247
          * Top-level keys are timestamps, and their values are arrays.
248 248
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
249 249
          * and their values are arrays.
@@ -260,908 +260,908 @@  discard block
 block discarded – undo
260 260
          *					...
261 261
          *      ...
262 262
          */
263
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
264
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
265
-            if (is_array($hooks_to_fire_at_time)) {
266
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
267
-                    if (isset($ee_cron_tasks_to_remove[$hook_name])
268
-                        && is_array($ee_cron_tasks_to_remove[$hook_name])
269
-                    ) {
270
-                        unset($crons[$timestamp][$hook_name]);
271
-                    }
272
-                }
273
-                //also take care of any empty cron timestamps.
274
-                if (empty($hooks_to_fire_at_time)) {
275
-                    unset($crons[$timestamp]);
276
-                }
277
-            }
278
-        }
279
-        _set_cron_array($crons);
280
-    }
281
-
282
-
283
-
284
-    /**
285
-     *    CPT_initialization
286
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
287
-     *
288
-     * @access public
289
-     * @static
290
-     * @return void
291
-     */
292
-    public static function CPT_initialization()
293
-    {
294
-        // register Custom Post Types
295
-        EE_Registry::instance()->load_core('Register_CPTs');
296
-        flush_rewrite_rules();
297
-    }
298
-
299
-
300
-
301
-    /**
302
-     *    reset_and_update_config
303
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
304
-     * If there is old calendar config data saved, then it will get converted on activation.
305
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
306
-     *
307
-     * @access public
308
-     * @static
309
-     * @return void
310
-     */
311
-    public static function reset_and_update_config()
312
-    {
313
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
314
-        add_filter('FHEE__EE_Config___load_core_config__config_settings', array('EEH_Activation', 'migrate_old_config_data'), 10, 3);
315
-        //EE_Config::reset();
316
-        if ( ! EE_Config::logging_enabled()) {
317
-            delete_option(EE_Config::LOG_NAME);
318
-        }
319
-    }
320
-
321
-
322
-
323
-    /**
324
-     *    load_calendar_config
325
-     *
326
-     * @access    public
327
-     * @return    void
328
-     */
329
-    public static function load_calendar_config()
330
-    {
331
-        // grab array of all plugin folders and loop thru it
332
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
333
-        if (empty($plugins)) {
334
-            return;
335
-        }
336
-        foreach ($plugins as $plugin_path) {
337
-            // grab plugin folder name from path
338
-            $plugin = basename($plugin_path);
339
-            // drill down to Espresso plugins
340
-            // then to calendar related plugins
341
-            if (
342
-                strpos($plugin, 'espresso') !== false
343
-                || strpos($plugin, 'Espresso') !== false
344
-                || strpos($plugin, 'ee4') !== false
345
-                || strpos($plugin, 'EE4') !== false
346
-                || strpos($plugin, 'calendar') !== false
347
-            ) {
348
-                // this is what we are looking for
349
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
350
-                // does it exist in this folder ?
351
-                if (is_readable($calendar_config)) {
352
-                    // YEAH! let's load it
353
-                    require_once($calendar_config);
354
-                }
355
-            }
356
-        }
357
-    }
358
-
359
-
360
-
361
-    /**
362
-     *    _migrate_old_config_data
363
-     *
364
-     * @access    public
365
-     * @param array|stdClass $settings
366
-     * @param string         $config
367
-     * @param \EE_Config     $EE_Config
368
-     * @return \stdClass
369
-     */
370
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
371
-    {
372
-        $convert_from_array = array('addons');
373
-        // in case old settings were saved as an array
374
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
375
-            // convert existing settings to an object
376
-            $config_array = $settings;
377
-            $settings = new stdClass();
378
-            foreach ($config_array as $key => $value) {
379
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
380
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
381
-                } else {
382
-                    $settings->{$key} = $value;
383
-                }
384
-            }
385
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
386
-        }
387
-        return $settings;
388
-    }
389
-
390
-
391
-
392
-    /**
393
-     * deactivate_event_espresso
394
-     *
395
-     * @access public
396
-     * @static
397
-     * @return void
398
-     */
399
-    public static function deactivate_event_espresso()
400
-    {
401
-        // check permissions
402
-        if (current_user_can('activate_plugins')) {
403
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
404
-        }
405
-    }
406
-
407
-
408
-
409
-    /**
410
-     * verify_default_pages_exist
411
-     *
412
-     * @access public
413
-     * @static
414
-     * @return void
415
-     */
416
-    public static function verify_default_pages_exist()
417
-    {
418
-        $critical_page_problem = false;
419
-        $critical_pages = array(
420
-            array(
421
-                'id'   => 'reg_page_id',
422
-                'name' => __('Registration Checkout', 'event_espresso'),
423
-                'post' => null,
424
-                'code' => 'ESPRESSO_CHECKOUT',
425
-            ),
426
-            array(
427
-                'id'   => 'txn_page_id',
428
-                'name' => __('Transactions', 'event_espresso'),
429
-                'post' => null,
430
-                'code' => 'ESPRESSO_TXN_PAGE',
431
-            ),
432
-            array(
433
-                'id'   => 'thank_you_page_id',
434
-                'name' => __('Thank You', 'event_espresso'),
435
-                'post' => null,
436
-                'code' => 'ESPRESSO_THANK_YOU',
437
-            ),
438
-            array(
439
-                'id'   => 'cancel_page_id',
440
-                'name' => __('Registration Cancelled', 'event_espresso'),
441
-                'post' => null,
442
-                'code' => 'ESPRESSO_CANCELLED',
443
-            ),
444
-        );
445
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
446
-        foreach ($critical_pages as $critical_page) {
447
-            // is critical page ID set in config ?
448
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
449
-                // attempt to find post by ID
450
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
451
-            }
452
-            // no dice?
453
-            if ($critical_page['post'] === null) {
454
-                // attempt to find post by title
455
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
456
-                // still nothing?
457
-                if ($critical_page['post'] === null) {
458
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
459
-                    // REALLY? Still nothing ??!?!?
460
-                    if ($critical_page['post'] === null) {
461
-                        $msg = __('The Event Espresso critical page configuration settings could not be updated.', 'event_espresso');
462
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
463
-                        break;
464
-                    }
465
-                }
466
-            }
467
-            // track post_shortcodes
468
-            if ($critical_page['post']) {
469
-                EEH_Activation::_track_critical_page_post_shortcodes($critical_page);
470
-            }
471
-            // check that Post ID matches critical page ID in config
472
-            if (
473
-                isset($critical_page['post']->ID)
474
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
475
-            ) {
476
-                //update Config with post ID
477
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
478
-                if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
479
-                    $msg = __('The Event Espresso critical page configuration settings could not be updated.', 'event_espresso');
480
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
481
-                }
482
-            }
483
-            $critical_page_problem =
484
-                ! isset($critical_page['post']->post_status)
485
-                || $critical_page['post']->post_status !== 'publish'
486
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
487
-                    ? true
488
-                    : $critical_page_problem;
489
-        }
490
-        if ($critical_page_problem) {
491
-            $msg = sprintf(
492
-                __('A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.', 'event_espresso'),
493
-                '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">' . __('Event Espresso Critical Pages Settings', 'event_espresso') . '</a>'
494
-            );
495
-            EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
496
-        }
497
-        if (EE_Error::has_notices()) {
498
-            EE_Error::get_notices(false, true, true);
499
-        }
500
-    }
501
-
502
-
503
-
504
-    /**
505
-     * Returns the first post which uses the specified shortcode
506
-     *
507
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
508
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content "[ESPRESSO_THANK_YOU"
509
-     *                             (we don't search for the closing shortcode bracket because they might have added
510
-     *                             parameter to the shortcode
511
-     * @return WP_Post or NULl
512
-     */
513
-    public static function get_page_by_ee_shortcode($ee_shortcode)
514
-    {
515
-        global $wpdb;
516
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
517
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
518
-        if ($post_id) {
519
-            return get_post($post_id);
520
-        } else {
521
-            return null;
522
-        }
523
-        //		return $post_id;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     *    This function generates a post for critical espresso pages
530
-     *
531
-     * @access public
532
-     * @static
533
-     * @param array $critical_page
534
-     * @return array
535
-     */
536
-    public static function create_critical_page($critical_page)
537
-    {
538
-        $post_args = array(
539
-            'post_title'     => $critical_page['name'],
540
-            'post_status'    => 'publish',
541
-            'post_type'      => 'page',
542
-            'comment_status' => 'closed',
543
-            'post_content'   => '[' . $critical_page['code'] . ']',
544
-        );
545
-        $post_id = wp_insert_post($post_args);
546
-        if ( ! $post_id) {
547
-            $msg = sprintf(
548
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
549
-                $critical_page['name']
550
-            );
551
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
552
-            return $critical_page;
553
-        }
554
-        // get newly created post's details
555
-        if ( ! $critical_page['post'] = get_post($post_id)) {
556
-            $msg = sprintf(
557
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
558
-                $critical_page['name']
559
-            );
560
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
561
-        }
562
-        return $critical_page;
563
-    }
564
-
565
-
566
-
567
-    /**
568
-     *    This function adds a critical page's shortcode to the post_shortcodes array
569
-     *
570
-     * @access private
571
-     * @static
572
-     * @param array $critical_page
573
-     * @return void
574
-     */
575
-    private static function _track_critical_page_post_shortcodes($critical_page = array())
576
-    {
577
-        // check the goods
578
-        if ( ! $critical_page['post'] instanceof WP_Post) {
579
-            $msg = sprintf(
580
-                __('The Event Espresso critical page shortcode for the page %s can not be tracked because it is not a WP_Post object.', 'event_espresso'),
581
-                $critical_page['name']
582
-            );
583
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
584
-            return;
585
-        }
586
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
587
-        // map shortcode to post
588
-        $EE_Core_Config->post_shortcodes[$critical_page['post']->post_name][$critical_page['code']] = $critical_page['post']->ID;
589
-        // and make sure it's NOT added to the WP "Posts Page"
590
-        // name of the WP Posts Page
591
-        $posts_page = EE_Config::get_page_for_posts();
592
-        if (isset($EE_Core_Config->post_shortcodes[$posts_page])) {
593
-            unset($EE_Core_Config->post_shortcodes[$posts_page][$critical_page['code']]);
594
-        }
595
-        if ($posts_page !== 'posts' && isset($EE_Core_Config->post_shortcodes['posts'])) {
596
-            unset($EE_Core_Config->post_shortcodes['posts'][$critical_page['code']]);
597
-        }
598
-        // update post_shortcode CFG
599
-        if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
600
-            $msg = sprintf(
601
-                __('The Event Espresso critical page shortcode for the %s page could not be configured properly.', 'event_espresso'),
602
-                $critical_page['name']
603
-            );
604
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
605
-        }
606
-    }
607
-
608
-
609
-
610
-    /**
611
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
612
-     * The role being used to check is filterable.
613
-     *
614
-     * @since  4.6.0
615
-     * @global WPDB $wpdb
616
-     * @return mixed null|int WP_user ID or NULL
617
-     */
618
-    public static function get_default_creator_id()
619
-    {
620
-        global $wpdb;
621
-        if ( ! empty(self::$_default_creator_id)) {
622
-            return self::$_default_creator_id;
623
-        }/**/
624
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
625
-        //let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
626
-        $pre_filtered_id = apply_filters('FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id', false, $role_to_check);
627
-        if ($pre_filtered_id !== false) {
628
-            return (int)$pre_filtered_id;
629
-        }
630
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
631
-        $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1", '%' . $role_to_check . '%');
632
-        $user_id = $wpdb->get_var($query);
633
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
634
-        if ($user_id && (int)$user_id) {
635
-            self::$_default_creator_id = (int)$user_id;
636
-            return self::$_default_creator_id;
637
-        } else {
638
-            return null;
639
-        }
640
-    }
641
-
642
-
643
-
644
-    /**
645
-     * used by EE and EE addons during plugin activation to create tables.
646
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
647
-     * but includes extra logic regarding activations.
648
-     *
649
-     * @access public
650
-     * @static
651
-     * @param string  $table_name              without the $wpdb->prefix
652
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create table query)
653
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
654
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
655
-     *                                         and new once this function is done (ie, you really do want to CREATE a table, and
656
-     *                                         expect it to be empty once you're done)
657
-     *                                         leave as FALSE when you just want to verify the table exists and matches this definition (and if it
658
-     *                                         HAS data in it you want to leave it be)
659
-     * @return void
660
-     * @throws EE_Error if there are database errors
661
-     */
662
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
663
-    {
664
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
665
-            return;
666
-        }
667
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
668
-        if ( ! function_exists('dbDelta')) {
669
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
670
-        }
671
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
672
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
673
-        // do we need to first delete an existing version of this table ?
674
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
675
-            // ok, delete the table... but ONLY if it's empty
676
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
677
-            // table is NOT empty, are you SURE you want to delete this table ???
678
-            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
679
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
680
-            } else if ( ! $deleted_safely) {
681
-                // so we should be more cautious rather than just dropping tables so easily
682
-                EE_Error::add_persistent_admin_notice(
683
-                    'bad_table_' . $wp_table_name . '_detected',
684
-                    sprintf(__('Database table %1$s exists when it shouldn\'t, and may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend adding %2$s to your %3$s file then restore to that backup again. This will clear out the invalid data from %1$s. Afterwards you should undo that change from your %3$s file. %4$sIf you cannot edit %3$s, you should remove the data from %1$s manually then restore to the backup again.',
685
-                        'event_espresso'),
686
-                        $wp_table_name,
687
-                        "<pre>define( 'EE_DROP_BAD_TABLES', TRUE );</pre>",
688
-                        '<b>wp-config.php</b>',
689
-                        '<br/>'),
690
-                    true);
691
-            }
692
-        }
693
-        $engine = str_replace('ENGINE=', '', $engine);
694
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *    add_column_if_it_doesn't_exist
701
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
702
-     *
703
-     * @access     public
704
-     * @static
705
-     * @deprecated instead use TableManager::addColumn()
706
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
707
-     * @param string $column_name
708
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
709
-     *                            'VARCHAR(10)'
710
-     * @return bool|int
711
-     */
712
-    public static function add_column_if_it_doesnt_exist($table_name, $column_name, $column_info = 'INT UNSIGNED NOT NULL')
713
-    {
714
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
715
-    }
716
-
717
-
718
-
719
-    /**
720
-     * get_fields_on_table
721
-     * Gets all the fields on the database table.
722
-     *
723
-     * @access     public
724
-     * @deprecated instead use TableManager::getTableColumns()
725
-     * @static
726
-     * @param string $table_name , without prefixed $wpdb->prefix
727
-     * @return array of database column names
728
-     */
729
-    public static function get_fields_on_table($table_name = null)
730
-    {
731
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
732
-    }
733
-
734
-
735
-
736
-    /**
737
-     * db_table_is_empty
738
-     *
739
-     * @access     public\
740
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
741
-     * @static
742
-     * @param string $table_name
743
-     * @return bool
744
-     */
745
-    public static function db_table_is_empty($table_name)
746
-    {
747
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
748
-    }
749
-
750
-
751
-
752
-    /**
753
-     * delete_db_table_if_empty
754
-     *
755
-     * @access public
756
-     * @static
757
-     * @param string $table_name
758
-     * @return bool | int
759
-     */
760
-    public static function delete_db_table_if_empty($table_name)
761
-    {
762
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
763
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
764
-        }
765
-        return false;
766
-    }
767
-
768
-
769
-
770
-    /**
771
-     * delete_unused_db_table
772
-     *
773
-     * @access     public
774
-     * @static
775
-     * @deprecated instead use TableManager::dropTable()
776
-     * @param string $table_name
777
-     * @return bool | int
778
-     */
779
-    public static function delete_unused_db_table($table_name)
780
-    {
781
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
782
-    }
783
-
784
-
785
-
786
-    /**
787
-     * drop_index
788
-     *
789
-     * @access     public
790
-     * @static
791
-     * @deprecated instead use TableManager::dropIndex()
792
-     * @param string $table_name
793
-     * @param string $index_name
794
-     * @return bool | int
795
-     */
796
-    public static function drop_index($table_name, $index_name)
797
-    {
798
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
799
-    }
800
-
801
-
802
-
803
-    /**
804
-     * create_database_tables
805
-     *
806
-     * @access public
807
-     * @static
808
-     * @throws EE_Error
809
-     * @return boolean success (whether database is setup properly or not)
810
-     */
811
-    public static function create_database_tables()
812
-    {
813
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
814
-        //find the migration script that sets the database to be compatible with the code
815
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
816
-        if ($dms_name) {
817
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
818
-            $current_data_migration_script->set_migrating(false);
819
-            $current_data_migration_script->schema_changes_before_migration();
820
-            $current_data_migration_script->schema_changes_after_migration();
821
-            if ($current_data_migration_script->get_errors()) {
822
-                if (WP_DEBUG) {
823
-                    foreach ($current_data_migration_script->get_errors() as $error) {
824
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
825
-                    }
826
-                } else {
827
-                    EE_Error::add_error(__('There were errors creating the Event Espresso database tables and Event Espresso has been deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.', 'event_espresso'));
828
-                }
829
-                return false;
830
-            }
831
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
832
-        } else {
833
-            EE_Error::add_error(__('Could not determine most up-to-date data migration script from which to pull database schema structure. So database is probably not setup properly', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
834
-            return false;
835
-        }
836
-        return true;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * initialize_system_questions
843
-     *
844
-     * @access public
845
-     * @static
846
-     * @return void
847
-     */
848
-    public static function initialize_system_questions()
849
-    {
850
-        // QUESTION GROUPS
851
-        global $wpdb;
852
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
853
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
854
-        // what we have
855
-        $question_groups = $wpdb->get_col($SQL);
856
-        // check the response
857
-        $question_groups = is_array($question_groups) ? $question_groups : array();
858
-        // what we should have
859
-        $QSG_systems = array(1, 2);
860
-        // loop thru what we should have and compare to what we have
861
-        foreach ($QSG_systems as $QSG_system) {
862
-            // reset values array
863
-            $QSG_values = array();
864
-            // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
865
-            if ( ! in_array("$QSG_system", $question_groups)) {
866
-                // add it
867
-                switch ($QSG_system) {
868
-                    case 1:
869
-                        $QSG_values = array(
870
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
871
-                            'QSG_identifier'      => 'personal-information-' . time(),
872
-                            'QSG_desc'            => '',
873
-                            'QSG_order'           => 1,
874
-                            'QSG_show_group_name' => 1,
875
-                            'QSG_show_group_desc' => 1,
876
-                            'QSG_system'          => EEM_Question_Group::system_personal,
877
-                            'QSG_deleted'         => 0,
878
-                        );
879
-                        break;
880
-                    case 2:
881
-                        $QSG_values = array(
882
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
883
-                            'QSG_identifier'      => 'address-information-' . time(),
884
-                            'QSG_desc'            => '',
885
-                            'QSG_order'           => 2,
886
-                            'QSG_show_group_name' => 1,
887
-                            'QSG_show_group_desc' => 1,
888
-                            'QSG_system'          => EEM_Question_Group::system_address,
889
-                            'QSG_deleted'         => 0,
890
-                        );
891
-                        break;
892
-                }
893
-                // make sure we have some values before inserting them
894
-                if ( ! empty($QSG_values)) {
895
-                    // insert system question
896
-                    $wpdb->insert(
897
-                        $table_name,
898
-                        $QSG_values,
899
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
900
-                    );
901
-                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
902
-                }
903
-            }
904
-        }
905
-        // QUESTIONS
906
-        global $wpdb;
907
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
908
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
909
-        // what we have
910
-        $questions = $wpdb->get_col($SQL);
911
-        // what we should have
912
-        $QST_systems = array(
913
-            'fname',
914
-            'lname',
915
-            'email',
916
-            'address',
917
-            'address2',
918
-            'city',
919
-            'country',
920
-            'state',
921
-            'zip',
922
-            'phone',
923
-        );
924
-        $order_for_group_1 = 1;
925
-        $order_for_group_2 = 1;
926
-        // loop thru what we should have and compare to what we have
927
-        foreach ($QST_systems as $QST_system) {
928
-            // reset values array
929
-            $QST_values = array();
930
-            // if we don't have what we should have
931
-            if ( ! in_array($QST_system, $questions)) {
932
-                // add it
933
-                switch ($QST_system) {
934
-                    case 'fname':
935
-                        $QST_values = array(
936
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
937
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
938
-                            'QST_system'        => 'fname',
939
-                            'QST_type'          => 'TEXT',
940
-                            'QST_required'      => 1,
941
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
942
-                            'QST_order'         => 1,
943
-                            'QST_admin_only'    => 0,
944
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
945
-                            'QST_wp_user'       => self::get_default_creator_id(),
946
-                            'QST_deleted'       => 0,
947
-                        );
948
-                        break;
949
-                    case 'lname':
950
-                        $QST_values = array(
951
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
952
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
953
-                            'QST_system'        => 'lname',
954
-                            'QST_type'          => 'TEXT',
955
-                            'QST_required'      => 1,
956
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
957
-                            'QST_order'         => 2,
958
-                            'QST_admin_only'    => 0,
959
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
960
-                            'QST_wp_user'       => self::get_default_creator_id(),
961
-                            'QST_deleted'       => 0,
962
-                        );
963
-                        break;
964
-                    case 'email':
965
-                        $QST_values = array(
966
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
967
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
968
-                            'QST_system'        => 'email',
969
-                            'QST_type'          => 'EMAIL',
970
-                            'QST_required'      => 1,
971
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
972
-                            'QST_order'         => 3,
973
-                            'QST_admin_only'    => 0,
974
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
975
-                            'QST_wp_user'       => self::get_default_creator_id(),
976
-                            'QST_deleted'       => 0,
977
-                        );
978
-                        break;
979
-                    case 'address':
980
-                        $QST_values = array(
981
-                            'QST_display_text'  => __('Address', 'event_espresso'),
982
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
983
-                            'QST_system'        => 'address',
984
-                            'QST_type'          => 'TEXT',
985
-                            'QST_required'      => 0,
986
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
987
-                            'QST_order'         => 4,
988
-                            'QST_admin_only'    => 0,
989
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
990
-                            'QST_wp_user'       => self::get_default_creator_id(),
991
-                            'QST_deleted'       => 0,
992
-                        );
993
-                        break;
994
-                    case 'address2':
995
-                        $QST_values = array(
996
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
997
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
998
-                            'QST_system'        => 'address2',
999
-                            'QST_type'          => 'TEXT',
1000
-                            'QST_required'      => 0,
1001
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1002
-                            'QST_order'         => 5,
1003
-                            'QST_admin_only'    => 0,
1004
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1005
-                            'QST_wp_user'       => self::get_default_creator_id(),
1006
-                            'QST_deleted'       => 0,
1007
-                        );
1008
-                        break;
1009
-                    case 'city':
1010
-                        $QST_values = array(
1011
-                            'QST_display_text'  => __('City', 'event_espresso'),
1012
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1013
-                            'QST_system'        => 'city',
1014
-                            'QST_type'          => 'TEXT',
1015
-                            'QST_required'      => 0,
1016
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1017
-                            'QST_order'         => 6,
1018
-                            'QST_admin_only'    => 0,
1019
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1020
-                            'QST_wp_user'       => self::get_default_creator_id(),
1021
-                            'QST_deleted'       => 0,
1022
-                        );
1023
-                        break;
1024
-                    case 'country' :
1025
-                        $QST_values = array(
1026
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1027
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1028
-                            'QST_system'        => 'country',
1029
-                            'QST_type'          => 'COUNTRY',
1030
-                            'QST_required'      => 0,
1031
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1032
-                            'QST_order'         => 7,
1033
-                            'QST_admin_only'    => 0,
1034
-                            'QST_wp_user'       => self::get_default_creator_id(),
1035
-                            'QST_deleted'       => 0,
1036
-                        );
1037
-                        break;
1038
-                    case 'state':
1039
-                        $QST_values = array(
1040
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1041
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1042
-                            'QST_system'        => 'state',
1043
-                            'QST_type'          => 'STATE',
1044
-                            'QST_required'      => 0,
1045
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1046
-                            'QST_order'         => 8,
1047
-                            'QST_admin_only'    => 0,
1048
-                            'QST_wp_user'       => self::get_default_creator_id(),
1049
-                            'QST_deleted'       => 0,
1050
-                        );
1051
-                        break;
1052
-                    case 'zip':
1053
-                        $QST_values = array(
1054
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1055
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1056
-                            'QST_system'        => 'zip',
1057
-                            'QST_type'          => 'TEXT',
1058
-                            'QST_required'      => 0,
1059
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1060
-                            'QST_order'         => 9,
1061
-                            'QST_admin_only'    => 0,
1062
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1063
-                            'QST_wp_user'       => self::get_default_creator_id(),
1064
-                            'QST_deleted'       => 0,
1065
-                        );
1066
-                        break;
1067
-                    case 'phone':
1068
-                        $QST_values = array(
1069
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1070
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1071
-                            'QST_system'        => 'phone',
1072
-                            'QST_type'          => 'TEXT',
1073
-                            'QST_required'      => 0,
1074
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1075
-                            'QST_order'         => 10,
1076
-                            'QST_admin_only'    => 0,
1077
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1078
-                            'QST_wp_user'       => self::get_default_creator_id(),
1079
-                            'QST_deleted'       => 0,
1080
-                        );
1081
-                        break;
1082
-                }
1083
-                if ( ! empty($QST_values)) {
1084
-                    // insert system question
1085
-                    $wpdb->insert(
1086
-                        $table_name,
1087
-                        $QST_values,
1088
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1089
-                    );
1090
-                    $QST_ID = $wpdb->insert_id;
1091
-                    // QUESTION GROUP QUESTIONS
1092
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1093
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1094
-                    } else {
1095
-                        $system_question_we_want = EEM_Question_Group::system_address;
1096
-                    }
1097
-                    if (isset($QSG_IDs[$system_question_we_want])) {
1098
-                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1099
-                    } else {
1100
-                        $id_col = EEM_Question_Group::instance()->get_col(array(array('QSG_system' => $system_question_we_want)));
1101
-                        if (is_array($id_col)) {
1102
-                            $QSG_ID = reset($id_col);
1103
-                        } else {
1104
-                            //ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1105
-                            EE_Log::instance()->log(
1106
-                                __FILE__,
1107
-                                __FUNCTION__,
1108
-                                sprintf(
1109
-                                    __('Could not associate question %1$s to a question group because no system question group existed', 'event_espresso'),
1110
-                                    $QST_ID),
1111
-                                'error');
1112
-                            continue;
1113
-                        }
1114
-                    }
1115
-                    // add system questions to groups
1116
-                    $wpdb->insert(
1117
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1118
-                        array(
1119
-                            'QSG_ID'    => $QSG_ID,
1120
-                            'QST_ID'    => $QST_ID,
1121
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1122
-                        ),
1123
-                        array('%d', '%d', '%d')
1124
-                    );
1125
-                }
1126
-            }
1127
-        }
1128
-    }
1129
-
1130
-
1131
-
1132
-    /**
1133
-     * Makes sure the default payment method (Invoice) is active.
1134
-     * This used to be done automatically as part of constructing the old gateways config
1135
-     *
1136
-     * @throws \EE_Error
1137
-     */
1138
-    public static function insert_default_payment_methods()
1139
-    {
1140
-        if ( ! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1141
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1142
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1143
-        } else {
1144
-            EEM_Payment_Method::instance()->verify_button_urls();
1145
-        }
1146
-    }
1147
-
1148
-
1149
-
1150
-    /**
1151
-     * insert_default_status_codes
1152
-     *
1153
-     * @access public
1154
-     * @static
1155
-     * @return void
1156
-     */
1157
-    public static function insert_default_status_codes()
1158
-    {
1159
-        global $wpdb;
1160
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1161
-            $table_name = EEM_Status::instance()->table();
1162
-            $SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC' );";
1163
-            $wpdb->query($SQL);
1164
-            $SQL = "INSERT INTO $table_name
263
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
264
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
265
+			if (is_array($hooks_to_fire_at_time)) {
266
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
267
+					if (isset($ee_cron_tasks_to_remove[$hook_name])
268
+						&& is_array($ee_cron_tasks_to_remove[$hook_name])
269
+					) {
270
+						unset($crons[$timestamp][$hook_name]);
271
+					}
272
+				}
273
+				//also take care of any empty cron timestamps.
274
+				if (empty($hooks_to_fire_at_time)) {
275
+					unset($crons[$timestamp]);
276
+				}
277
+			}
278
+		}
279
+		_set_cron_array($crons);
280
+	}
281
+
282
+
283
+
284
+	/**
285
+	 *    CPT_initialization
286
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
287
+	 *
288
+	 * @access public
289
+	 * @static
290
+	 * @return void
291
+	 */
292
+	public static function CPT_initialization()
293
+	{
294
+		// register Custom Post Types
295
+		EE_Registry::instance()->load_core('Register_CPTs');
296
+		flush_rewrite_rules();
297
+	}
298
+
299
+
300
+
301
+	/**
302
+	 *    reset_and_update_config
303
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
304
+	 * If there is old calendar config data saved, then it will get converted on activation.
305
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
306
+	 *
307
+	 * @access public
308
+	 * @static
309
+	 * @return void
310
+	 */
311
+	public static function reset_and_update_config()
312
+	{
313
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
314
+		add_filter('FHEE__EE_Config___load_core_config__config_settings', array('EEH_Activation', 'migrate_old_config_data'), 10, 3);
315
+		//EE_Config::reset();
316
+		if ( ! EE_Config::logging_enabled()) {
317
+			delete_option(EE_Config::LOG_NAME);
318
+		}
319
+	}
320
+
321
+
322
+
323
+	/**
324
+	 *    load_calendar_config
325
+	 *
326
+	 * @access    public
327
+	 * @return    void
328
+	 */
329
+	public static function load_calendar_config()
330
+	{
331
+		// grab array of all plugin folders and loop thru it
332
+		$plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
333
+		if (empty($plugins)) {
334
+			return;
335
+		}
336
+		foreach ($plugins as $plugin_path) {
337
+			// grab plugin folder name from path
338
+			$plugin = basename($plugin_path);
339
+			// drill down to Espresso plugins
340
+			// then to calendar related plugins
341
+			if (
342
+				strpos($plugin, 'espresso') !== false
343
+				|| strpos($plugin, 'Espresso') !== false
344
+				|| strpos($plugin, 'ee4') !== false
345
+				|| strpos($plugin, 'EE4') !== false
346
+				|| strpos($plugin, 'calendar') !== false
347
+			) {
348
+				// this is what we are looking for
349
+				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
350
+				// does it exist in this folder ?
351
+				if (is_readable($calendar_config)) {
352
+					// YEAH! let's load it
353
+					require_once($calendar_config);
354
+				}
355
+			}
356
+		}
357
+	}
358
+
359
+
360
+
361
+	/**
362
+	 *    _migrate_old_config_data
363
+	 *
364
+	 * @access    public
365
+	 * @param array|stdClass $settings
366
+	 * @param string         $config
367
+	 * @param \EE_Config     $EE_Config
368
+	 * @return \stdClass
369
+	 */
370
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
371
+	{
372
+		$convert_from_array = array('addons');
373
+		// in case old settings were saved as an array
374
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
375
+			// convert existing settings to an object
376
+			$config_array = $settings;
377
+			$settings = new stdClass();
378
+			foreach ($config_array as $key => $value) {
379
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
380
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
381
+				} else {
382
+					$settings->{$key} = $value;
383
+				}
384
+			}
385
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
386
+		}
387
+		return $settings;
388
+	}
389
+
390
+
391
+
392
+	/**
393
+	 * deactivate_event_espresso
394
+	 *
395
+	 * @access public
396
+	 * @static
397
+	 * @return void
398
+	 */
399
+	public static function deactivate_event_espresso()
400
+	{
401
+		// check permissions
402
+		if (current_user_can('activate_plugins')) {
403
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
404
+		}
405
+	}
406
+
407
+
408
+
409
+	/**
410
+	 * verify_default_pages_exist
411
+	 *
412
+	 * @access public
413
+	 * @static
414
+	 * @return void
415
+	 */
416
+	public static function verify_default_pages_exist()
417
+	{
418
+		$critical_page_problem = false;
419
+		$critical_pages = array(
420
+			array(
421
+				'id'   => 'reg_page_id',
422
+				'name' => __('Registration Checkout', 'event_espresso'),
423
+				'post' => null,
424
+				'code' => 'ESPRESSO_CHECKOUT',
425
+			),
426
+			array(
427
+				'id'   => 'txn_page_id',
428
+				'name' => __('Transactions', 'event_espresso'),
429
+				'post' => null,
430
+				'code' => 'ESPRESSO_TXN_PAGE',
431
+			),
432
+			array(
433
+				'id'   => 'thank_you_page_id',
434
+				'name' => __('Thank You', 'event_espresso'),
435
+				'post' => null,
436
+				'code' => 'ESPRESSO_THANK_YOU',
437
+			),
438
+			array(
439
+				'id'   => 'cancel_page_id',
440
+				'name' => __('Registration Cancelled', 'event_espresso'),
441
+				'post' => null,
442
+				'code' => 'ESPRESSO_CANCELLED',
443
+			),
444
+		);
445
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
446
+		foreach ($critical_pages as $critical_page) {
447
+			// is critical page ID set in config ?
448
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
449
+				// attempt to find post by ID
450
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
451
+			}
452
+			// no dice?
453
+			if ($critical_page['post'] === null) {
454
+				// attempt to find post by title
455
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
456
+				// still nothing?
457
+				if ($critical_page['post'] === null) {
458
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
459
+					// REALLY? Still nothing ??!?!?
460
+					if ($critical_page['post'] === null) {
461
+						$msg = __('The Event Espresso critical page configuration settings could not be updated.', 'event_espresso');
462
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
463
+						break;
464
+					}
465
+				}
466
+			}
467
+			// track post_shortcodes
468
+			if ($critical_page['post']) {
469
+				EEH_Activation::_track_critical_page_post_shortcodes($critical_page);
470
+			}
471
+			// check that Post ID matches critical page ID in config
472
+			if (
473
+				isset($critical_page['post']->ID)
474
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
475
+			) {
476
+				//update Config with post ID
477
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
478
+				if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
479
+					$msg = __('The Event Espresso critical page configuration settings could not be updated.', 'event_espresso');
480
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
481
+				}
482
+			}
483
+			$critical_page_problem =
484
+				! isset($critical_page['post']->post_status)
485
+				|| $critical_page['post']->post_status !== 'publish'
486
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
487
+					? true
488
+					: $critical_page_problem;
489
+		}
490
+		if ($critical_page_problem) {
491
+			$msg = sprintf(
492
+				__('A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.', 'event_espresso'),
493
+				'<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">' . __('Event Espresso Critical Pages Settings', 'event_espresso') . '</a>'
494
+			);
495
+			EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
496
+		}
497
+		if (EE_Error::has_notices()) {
498
+			EE_Error::get_notices(false, true, true);
499
+		}
500
+	}
501
+
502
+
503
+
504
+	/**
505
+	 * Returns the first post which uses the specified shortcode
506
+	 *
507
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
508
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content "[ESPRESSO_THANK_YOU"
509
+	 *                             (we don't search for the closing shortcode bracket because they might have added
510
+	 *                             parameter to the shortcode
511
+	 * @return WP_Post or NULl
512
+	 */
513
+	public static function get_page_by_ee_shortcode($ee_shortcode)
514
+	{
515
+		global $wpdb;
516
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
517
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
518
+		if ($post_id) {
519
+			return get_post($post_id);
520
+		} else {
521
+			return null;
522
+		}
523
+		//		return $post_id;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 *    This function generates a post for critical espresso pages
530
+	 *
531
+	 * @access public
532
+	 * @static
533
+	 * @param array $critical_page
534
+	 * @return array
535
+	 */
536
+	public static function create_critical_page($critical_page)
537
+	{
538
+		$post_args = array(
539
+			'post_title'     => $critical_page['name'],
540
+			'post_status'    => 'publish',
541
+			'post_type'      => 'page',
542
+			'comment_status' => 'closed',
543
+			'post_content'   => '[' . $critical_page['code'] . ']',
544
+		);
545
+		$post_id = wp_insert_post($post_args);
546
+		if ( ! $post_id) {
547
+			$msg = sprintf(
548
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
549
+				$critical_page['name']
550
+			);
551
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
552
+			return $critical_page;
553
+		}
554
+		// get newly created post's details
555
+		if ( ! $critical_page['post'] = get_post($post_id)) {
556
+			$msg = sprintf(
557
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
558
+				$critical_page['name']
559
+			);
560
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
561
+		}
562
+		return $critical_page;
563
+	}
564
+
565
+
566
+
567
+	/**
568
+	 *    This function adds a critical page's shortcode to the post_shortcodes array
569
+	 *
570
+	 * @access private
571
+	 * @static
572
+	 * @param array $critical_page
573
+	 * @return void
574
+	 */
575
+	private static function _track_critical_page_post_shortcodes($critical_page = array())
576
+	{
577
+		// check the goods
578
+		if ( ! $critical_page['post'] instanceof WP_Post) {
579
+			$msg = sprintf(
580
+				__('The Event Espresso critical page shortcode for the page %s can not be tracked because it is not a WP_Post object.', 'event_espresso'),
581
+				$critical_page['name']
582
+			);
583
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
584
+			return;
585
+		}
586
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
587
+		// map shortcode to post
588
+		$EE_Core_Config->post_shortcodes[$critical_page['post']->post_name][$critical_page['code']] = $critical_page['post']->ID;
589
+		// and make sure it's NOT added to the WP "Posts Page"
590
+		// name of the WP Posts Page
591
+		$posts_page = EE_Config::get_page_for_posts();
592
+		if (isset($EE_Core_Config->post_shortcodes[$posts_page])) {
593
+			unset($EE_Core_Config->post_shortcodes[$posts_page][$critical_page['code']]);
594
+		}
595
+		if ($posts_page !== 'posts' && isset($EE_Core_Config->post_shortcodes['posts'])) {
596
+			unset($EE_Core_Config->post_shortcodes['posts'][$critical_page['code']]);
597
+		}
598
+		// update post_shortcode CFG
599
+		if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
600
+			$msg = sprintf(
601
+				__('The Event Espresso critical page shortcode for the %s page could not be configured properly.', 'event_espresso'),
602
+				$critical_page['name']
603
+			);
604
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
605
+		}
606
+	}
607
+
608
+
609
+
610
+	/**
611
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
612
+	 * The role being used to check is filterable.
613
+	 *
614
+	 * @since  4.6.0
615
+	 * @global WPDB $wpdb
616
+	 * @return mixed null|int WP_user ID or NULL
617
+	 */
618
+	public static function get_default_creator_id()
619
+	{
620
+		global $wpdb;
621
+		if ( ! empty(self::$_default_creator_id)) {
622
+			return self::$_default_creator_id;
623
+		}/**/
624
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
625
+		//let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
626
+		$pre_filtered_id = apply_filters('FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id', false, $role_to_check);
627
+		if ($pre_filtered_id !== false) {
628
+			return (int)$pre_filtered_id;
629
+		}
630
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
631
+		$query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1", '%' . $role_to_check . '%');
632
+		$user_id = $wpdb->get_var($query);
633
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
634
+		if ($user_id && (int)$user_id) {
635
+			self::$_default_creator_id = (int)$user_id;
636
+			return self::$_default_creator_id;
637
+		} else {
638
+			return null;
639
+		}
640
+	}
641
+
642
+
643
+
644
+	/**
645
+	 * used by EE and EE addons during plugin activation to create tables.
646
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
647
+	 * but includes extra logic regarding activations.
648
+	 *
649
+	 * @access public
650
+	 * @static
651
+	 * @param string  $table_name              without the $wpdb->prefix
652
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create table query)
653
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
654
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
655
+	 *                                         and new once this function is done (ie, you really do want to CREATE a table, and
656
+	 *                                         expect it to be empty once you're done)
657
+	 *                                         leave as FALSE when you just want to verify the table exists and matches this definition (and if it
658
+	 *                                         HAS data in it you want to leave it be)
659
+	 * @return void
660
+	 * @throws EE_Error if there are database errors
661
+	 */
662
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
663
+	{
664
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
665
+			return;
666
+		}
667
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
668
+		if ( ! function_exists('dbDelta')) {
669
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
670
+		}
671
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
672
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
673
+		// do we need to first delete an existing version of this table ?
674
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
675
+			// ok, delete the table... but ONLY if it's empty
676
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
677
+			// table is NOT empty, are you SURE you want to delete this table ???
678
+			if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
679
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
680
+			} else if ( ! $deleted_safely) {
681
+				// so we should be more cautious rather than just dropping tables so easily
682
+				EE_Error::add_persistent_admin_notice(
683
+					'bad_table_' . $wp_table_name . '_detected',
684
+					sprintf(__('Database table %1$s exists when it shouldn\'t, and may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend adding %2$s to your %3$s file then restore to that backup again. This will clear out the invalid data from %1$s. Afterwards you should undo that change from your %3$s file. %4$sIf you cannot edit %3$s, you should remove the data from %1$s manually then restore to the backup again.',
685
+						'event_espresso'),
686
+						$wp_table_name,
687
+						"<pre>define( 'EE_DROP_BAD_TABLES', TRUE );</pre>",
688
+						'<b>wp-config.php</b>',
689
+						'<br/>'),
690
+					true);
691
+			}
692
+		}
693
+		$engine = str_replace('ENGINE=', '', $engine);
694
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *    add_column_if_it_doesn't_exist
701
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
702
+	 *
703
+	 * @access     public
704
+	 * @static
705
+	 * @deprecated instead use TableManager::addColumn()
706
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
707
+	 * @param string $column_name
708
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
709
+	 *                            'VARCHAR(10)'
710
+	 * @return bool|int
711
+	 */
712
+	public static function add_column_if_it_doesnt_exist($table_name, $column_name, $column_info = 'INT UNSIGNED NOT NULL')
713
+	{
714
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
715
+	}
716
+
717
+
718
+
719
+	/**
720
+	 * get_fields_on_table
721
+	 * Gets all the fields on the database table.
722
+	 *
723
+	 * @access     public
724
+	 * @deprecated instead use TableManager::getTableColumns()
725
+	 * @static
726
+	 * @param string $table_name , without prefixed $wpdb->prefix
727
+	 * @return array of database column names
728
+	 */
729
+	public static function get_fields_on_table($table_name = null)
730
+	{
731
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
732
+	}
733
+
734
+
735
+
736
+	/**
737
+	 * db_table_is_empty
738
+	 *
739
+	 * @access     public\
740
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
741
+	 * @static
742
+	 * @param string $table_name
743
+	 * @return bool
744
+	 */
745
+	public static function db_table_is_empty($table_name)
746
+	{
747
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
748
+	}
749
+
750
+
751
+
752
+	/**
753
+	 * delete_db_table_if_empty
754
+	 *
755
+	 * @access public
756
+	 * @static
757
+	 * @param string $table_name
758
+	 * @return bool | int
759
+	 */
760
+	public static function delete_db_table_if_empty($table_name)
761
+	{
762
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
763
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
764
+		}
765
+		return false;
766
+	}
767
+
768
+
769
+
770
+	/**
771
+	 * delete_unused_db_table
772
+	 *
773
+	 * @access     public
774
+	 * @static
775
+	 * @deprecated instead use TableManager::dropTable()
776
+	 * @param string $table_name
777
+	 * @return bool | int
778
+	 */
779
+	public static function delete_unused_db_table($table_name)
780
+	{
781
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
782
+	}
783
+
784
+
785
+
786
+	/**
787
+	 * drop_index
788
+	 *
789
+	 * @access     public
790
+	 * @static
791
+	 * @deprecated instead use TableManager::dropIndex()
792
+	 * @param string $table_name
793
+	 * @param string $index_name
794
+	 * @return bool | int
795
+	 */
796
+	public static function drop_index($table_name, $index_name)
797
+	{
798
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
799
+	}
800
+
801
+
802
+
803
+	/**
804
+	 * create_database_tables
805
+	 *
806
+	 * @access public
807
+	 * @static
808
+	 * @throws EE_Error
809
+	 * @return boolean success (whether database is setup properly or not)
810
+	 */
811
+	public static function create_database_tables()
812
+	{
813
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
814
+		//find the migration script that sets the database to be compatible with the code
815
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
816
+		if ($dms_name) {
817
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
818
+			$current_data_migration_script->set_migrating(false);
819
+			$current_data_migration_script->schema_changes_before_migration();
820
+			$current_data_migration_script->schema_changes_after_migration();
821
+			if ($current_data_migration_script->get_errors()) {
822
+				if (WP_DEBUG) {
823
+					foreach ($current_data_migration_script->get_errors() as $error) {
824
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
825
+					}
826
+				} else {
827
+					EE_Error::add_error(__('There were errors creating the Event Espresso database tables and Event Espresso has been deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.', 'event_espresso'));
828
+				}
829
+				return false;
830
+			}
831
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
832
+		} else {
833
+			EE_Error::add_error(__('Could not determine most up-to-date data migration script from which to pull database schema structure. So database is probably not setup properly', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
834
+			return false;
835
+		}
836
+		return true;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * initialize_system_questions
843
+	 *
844
+	 * @access public
845
+	 * @static
846
+	 * @return void
847
+	 */
848
+	public static function initialize_system_questions()
849
+	{
850
+		// QUESTION GROUPS
851
+		global $wpdb;
852
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
853
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
854
+		// what we have
855
+		$question_groups = $wpdb->get_col($SQL);
856
+		// check the response
857
+		$question_groups = is_array($question_groups) ? $question_groups : array();
858
+		// what we should have
859
+		$QSG_systems = array(1, 2);
860
+		// loop thru what we should have and compare to what we have
861
+		foreach ($QSG_systems as $QSG_system) {
862
+			// reset values array
863
+			$QSG_values = array();
864
+			// if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
865
+			if ( ! in_array("$QSG_system", $question_groups)) {
866
+				// add it
867
+				switch ($QSG_system) {
868
+					case 1:
869
+						$QSG_values = array(
870
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
871
+							'QSG_identifier'      => 'personal-information-' . time(),
872
+							'QSG_desc'            => '',
873
+							'QSG_order'           => 1,
874
+							'QSG_show_group_name' => 1,
875
+							'QSG_show_group_desc' => 1,
876
+							'QSG_system'          => EEM_Question_Group::system_personal,
877
+							'QSG_deleted'         => 0,
878
+						);
879
+						break;
880
+					case 2:
881
+						$QSG_values = array(
882
+							'QSG_name'            => __('Address Information', 'event_espresso'),
883
+							'QSG_identifier'      => 'address-information-' . time(),
884
+							'QSG_desc'            => '',
885
+							'QSG_order'           => 2,
886
+							'QSG_show_group_name' => 1,
887
+							'QSG_show_group_desc' => 1,
888
+							'QSG_system'          => EEM_Question_Group::system_address,
889
+							'QSG_deleted'         => 0,
890
+						);
891
+						break;
892
+				}
893
+				// make sure we have some values before inserting them
894
+				if ( ! empty($QSG_values)) {
895
+					// insert system question
896
+					$wpdb->insert(
897
+						$table_name,
898
+						$QSG_values,
899
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
900
+					);
901
+					$QSG_IDs[$QSG_system] = $wpdb->insert_id;
902
+				}
903
+			}
904
+		}
905
+		// QUESTIONS
906
+		global $wpdb;
907
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
908
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
909
+		// what we have
910
+		$questions = $wpdb->get_col($SQL);
911
+		// what we should have
912
+		$QST_systems = array(
913
+			'fname',
914
+			'lname',
915
+			'email',
916
+			'address',
917
+			'address2',
918
+			'city',
919
+			'country',
920
+			'state',
921
+			'zip',
922
+			'phone',
923
+		);
924
+		$order_for_group_1 = 1;
925
+		$order_for_group_2 = 1;
926
+		// loop thru what we should have and compare to what we have
927
+		foreach ($QST_systems as $QST_system) {
928
+			// reset values array
929
+			$QST_values = array();
930
+			// if we don't have what we should have
931
+			if ( ! in_array($QST_system, $questions)) {
932
+				// add it
933
+				switch ($QST_system) {
934
+					case 'fname':
935
+						$QST_values = array(
936
+							'QST_display_text'  => __('First Name', 'event_espresso'),
937
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
938
+							'QST_system'        => 'fname',
939
+							'QST_type'          => 'TEXT',
940
+							'QST_required'      => 1,
941
+							'QST_required_text' => __('This field is required', 'event_espresso'),
942
+							'QST_order'         => 1,
943
+							'QST_admin_only'    => 0,
944
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
945
+							'QST_wp_user'       => self::get_default_creator_id(),
946
+							'QST_deleted'       => 0,
947
+						);
948
+						break;
949
+					case 'lname':
950
+						$QST_values = array(
951
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
952
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
953
+							'QST_system'        => 'lname',
954
+							'QST_type'          => 'TEXT',
955
+							'QST_required'      => 1,
956
+							'QST_required_text' => __('This field is required', 'event_espresso'),
957
+							'QST_order'         => 2,
958
+							'QST_admin_only'    => 0,
959
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
960
+							'QST_wp_user'       => self::get_default_creator_id(),
961
+							'QST_deleted'       => 0,
962
+						);
963
+						break;
964
+					case 'email':
965
+						$QST_values = array(
966
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
967
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
968
+							'QST_system'        => 'email',
969
+							'QST_type'          => 'EMAIL',
970
+							'QST_required'      => 1,
971
+							'QST_required_text' => __('This field is required', 'event_espresso'),
972
+							'QST_order'         => 3,
973
+							'QST_admin_only'    => 0,
974
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
975
+							'QST_wp_user'       => self::get_default_creator_id(),
976
+							'QST_deleted'       => 0,
977
+						);
978
+						break;
979
+					case 'address':
980
+						$QST_values = array(
981
+							'QST_display_text'  => __('Address', 'event_espresso'),
982
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
983
+							'QST_system'        => 'address',
984
+							'QST_type'          => 'TEXT',
985
+							'QST_required'      => 0,
986
+							'QST_required_text' => __('This field is required', 'event_espresso'),
987
+							'QST_order'         => 4,
988
+							'QST_admin_only'    => 0,
989
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
990
+							'QST_wp_user'       => self::get_default_creator_id(),
991
+							'QST_deleted'       => 0,
992
+						);
993
+						break;
994
+					case 'address2':
995
+						$QST_values = array(
996
+							'QST_display_text'  => __('Address2', 'event_espresso'),
997
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
998
+							'QST_system'        => 'address2',
999
+							'QST_type'          => 'TEXT',
1000
+							'QST_required'      => 0,
1001
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1002
+							'QST_order'         => 5,
1003
+							'QST_admin_only'    => 0,
1004
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1005
+							'QST_wp_user'       => self::get_default_creator_id(),
1006
+							'QST_deleted'       => 0,
1007
+						);
1008
+						break;
1009
+					case 'city':
1010
+						$QST_values = array(
1011
+							'QST_display_text'  => __('City', 'event_espresso'),
1012
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1013
+							'QST_system'        => 'city',
1014
+							'QST_type'          => 'TEXT',
1015
+							'QST_required'      => 0,
1016
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1017
+							'QST_order'         => 6,
1018
+							'QST_admin_only'    => 0,
1019
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1020
+							'QST_wp_user'       => self::get_default_creator_id(),
1021
+							'QST_deleted'       => 0,
1022
+						);
1023
+						break;
1024
+					case 'country' :
1025
+						$QST_values = array(
1026
+							'QST_display_text'  => __('Country', 'event_espresso'),
1027
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1028
+							'QST_system'        => 'country',
1029
+							'QST_type'          => 'COUNTRY',
1030
+							'QST_required'      => 0,
1031
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1032
+							'QST_order'         => 7,
1033
+							'QST_admin_only'    => 0,
1034
+							'QST_wp_user'       => self::get_default_creator_id(),
1035
+							'QST_deleted'       => 0,
1036
+						);
1037
+						break;
1038
+					case 'state':
1039
+						$QST_values = array(
1040
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1041
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1042
+							'QST_system'        => 'state',
1043
+							'QST_type'          => 'STATE',
1044
+							'QST_required'      => 0,
1045
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1046
+							'QST_order'         => 8,
1047
+							'QST_admin_only'    => 0,
1048
+							'QST_wp_user'       => self::get_default_creator_id(),
1049
+							'QST_deleted'       => 0,
1050
+						);
1051
+						break;
1052
+					case 'zip':
1053
+						$QST_values = array(
1054
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1055
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1056
+							'QST_system'        => 'zip',
1057
+							'QST_type'          => 'TEXT',
1058
+							'QST_required'      => 0,
1059
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1060
+							'QST_order'         => 9,
1061
+							'QST_admin_only'    => 0,
1062
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1063
+							'QST_wp_user'       => self::get_default_creator_id(),
1064
+							'QST_deleted'       => 0,
1065
+						);
1066
+						break;
1067
+					case 'phone':
1068
+						$QST_values = array(
1069
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1070
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1071
+							'QST_system'        => 'phone',
1072
+							'QST_type'          => 'TEXT',
1073
+							'QST_required'      => 0,
1074
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1075
+							'QST_order'         => 10,
1076
+							'QST_admin_only'    => 0,
1077
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1078
+							'QST_wp_user'       => self::get_default_creator_id(),
1079
+							'QST_deleted'       => 0,
1080
+						);
1081
+						break;
1082
+				}
1083
+				if ( ! empty($QST_values)) {
1084
+					// insert system question
1085
+					$wpdb->insert(
1086
+						$table_name,
1087
+						$QST_values,
1088
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1089
+					);
1090
+					$QST_ID = $wpdb->insert_id;
1091
+					// QUESTION GROUP QUESTIONS
1092
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1093
+						$system_question_we_want = EEM_Question_Group::system_personal;
1094
+					} else {
1095
+						$system_question_we_want = EEM_Question_Group::system_address;
1096
+					}
1097
+					if (isset($QSG_IDs[$system_question_we_want])) {
1098
+						$QSG_ID = $QSG_IDs[$system_question_we_want];
1099
+					} else {
1100
+						$id_col = EEM_Question_Group::instance()->get_col(array(array('QSG_system' => $system_question_we_want)));
1101
+						if (is_array($id_col)) {
1102
+							$QSG_ID = reset($id_col);
1103
+						} else {
1104
+							//ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1105
+							EE_Log::instance()->log(
1106
+								__FILE__,
1107
+								__FUNCTION__,
1108
+								sprintf(
1109
+									__('Could not associate question %1$s to a question group because no system question group existed', 'event_espresso'),
1110
+									$QST_ID),
1111
+								'error');
1112
+							continue;
1113
+						}
1114
+					}
1115
+					// add system questions to groups
1116
+					$wpdb->insert(
1117
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1118
+						array(
1119
+							'QSG_ID'    => $QSG_ID,
1120
+							'QST_ID'    => $QST_ID,
1121
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1122
+						),
1123
+						array('%d', '%d', '%d')
1124
+					);
1125
+				}
1126
+			}
1127
+		}
1128
+	}
1129
+
1130
+
1131
+
1132
+	/**
1133
+	 * Makes sure the default payment method (Invoice) is active.
1134
+	 * This used to be done automatically as part of constructing the old gateways config
1135
+	 *
1136
+	 * @throws \EE_Error
1137
+	 */
1138
+	public static function insert_default_payment_methods()
1139
+	{
1140
+		if ( ! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1141
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1142
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1143
+		} else {
1144
+			EEM_Payment_Method::instance()->verify_button_urls();
1145
+		}
1146
+	}
1147
+
1148
+
1149
+
1150
+	/**
1151
+	 * insert_default_status_codes
1152
+	 *
1153
+	 * @access public
1154
+	 * @static
1155
+	 * @return void
1156
+	 */
1157
+	public static function insert_default_status_codes()
1158
+	{
1159
+		global $wpdb;
1160
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1161
+			$table_name = EEM_Status::instance()->table();
1162
+			$SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC' );";
1163
+			$wpdb->query($SQL);
1164
+			$SQL = "INSERT INTO $table_name
1165 1165
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1166 1166
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1167 1167
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1199,526 +1199,526 @@  discard block
 block discarded – undo
1199 1199
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1200 1200
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1201 1201
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1202
-            $wpdb->query($SQL);
1203
-        }
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * create_upload_directories
1210
-     * Creates folders in the uploads directory to facilitate addons and templates
1211
-     *
1212
-     * @access public
1213
-     * @static
1214
-     * @return boolean success of verifying upload directories exist
1215
-     */
1216
-    public static function create_upload_directories()
1217
-    {
1218
-        // Create the required folders
1219
-        $folders = array(
1220
-            EVENT_ESPRESSO_TEMPLATE_DIR,
1221
-            EVENT_ESPRESSO_GATEWAY_DIR,
1222
-            EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1223
-            EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1224
-            EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1225
-        );
1226
-        foreach ($folders as $folder) {
1227
-            try {
1228
-                EEH_File::ensure_folder_exists_and_is_writable($folder);
1229
-                @ chmod($folder, 0755);
1230
-            } catch (EE_Error $e) {
1231
-                EE_Error::add_error(
1232
-                    sprintf(
1233
-                        __('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1234
-                        $folder,
1235
-                        '<br />' . $e->getMessage()
1236
-                    ),
1237
-                    __FILE__, __FUNCTION__, __LINE__
1238
-                );
1239
-                //indicate we'll need to fix this later
1240
-                update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1241
-                return false;
1242
-            }
1243
-        }
1244
-        //just add the .htaccess file to the logs directory to begin with. Even if logging
1245
-        //is disabled, there might be activation errors recorded in there
1246
-        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1247
-        //remember EE's folders are all good
1248
-        delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1249
-        return true;
1250
-    }
1251
-
1252
-
1253
-
1254
-    /**
1255
-     * Whether the upload directories need to be fixed or not.
1256
-     * If EE is installed but filesystem access isn't initially available,
1257
-     * we need to get the user's filesystem credentials and THEN create them,
1258
-     * so there might be period of time when EE is installed but its
1259
-     * upload directories aren't available. This indicates such a state
1260
-     *
1261
-     * @return boolean
1262
-     */
1263
-    public static function upload_directories_incomplete()
1264
-    {
1265
-        return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1266
-    }
1267
-
1268
-
1269
-
1270
-    /**
1271
-     * generate_default_message_templates
1272
-     *
1273
-     * @static
1274
-     * @throws EE_Error
1275
-     * @return bool     true means new templates were created.
1276
-     *                  false means no templates were created.
1277
-     *                  This is NOT an error flag. To check for errors you will want
1278
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1279
-     */
1280
-    public static function generate_default_message_templates()
1281
-    {
1282
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1283
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1284
-        /*
1202
+			$wpdb->query($SQL);
1203
+		}
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * create_upload_directories
1210
+	 * Creates folders in the uploads directory to facilitate addons and templates
1211
+	 *
1212
+	 * @access public
1213
+	 * @static
1214
+	 * @return boolean success of verifying upload directories exist
1215
+	 */
1216
+	public static function create_upload_directories()
1217
+	{
1218
+		// Create the required folders
1219
+		$folders = array(
1220
+			EVENT_ESPRESSO_TEMPLATE_DIR,
1221
+			EVENT_ESPRESSO_GATEWAY_DIR,
1222
+			EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1223
+			EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1224
+			EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1225
+		);
1226
+		foreach ($folders as $folder) {
1227
+			try {
1228
+				EEH_File::ensure_folder_exists_and_is_writable($folder);
1229
+				@ chmod($folder, 0755);
1230
+			} catch (EE_Error $e) {
1231
+				EE_Error::add_error(
1232
+					sprintf(
1233
+						__('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1234
+						$folder,
1235
+						'<br />' . $e->getMessage()
1236
+					),
1237
+					__FILE__, __FUNCTION__, __LINE__
1238
+				);
1239
+				//indicate we'll need to fix this later
1240
+				update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1241
+				return false;
1242
+			}
1243
+		}
1244
+		//just add the .htaccess file to the logs directory to begin with. Even if logging
1245
+		//is disabled, there might be activation errors recorded in there
1246
+		EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1247
+		//remember EE's folders are all good
1248
+		delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1249
+		return true;
1250
+	}
1251
+
1252
+
1253
+
1254
+	/**
1255
+	 * Whether the upload directories need to be fixed or not.
1256
+	 * If EE is installed but filesystem access isn't initially available,
1257
+	 * we need to get the user's filesystem credentials and THEN create them,
1258
+	 * so there might be period of time when EE is installed but its
1259
+	 * upload directories aren't available. This indicates such a state
1260
+	 *
1261
+	 * @return boolean
1262
+	 */
1263
+	public static function upload_directories_incomplete()
1264
+	{
1265
+		return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1266
+	}
1267
+
1268
+
1269
+
1270
+	/**
1271
+	 * generate_default_message_templates
1272
+	 *
1273
+	 * @static
1274
+	 * @throws EE_Error
1275
+	 * @return bool     true means new templates were created.
1276
+	 *                  false means no templates were created.
1277
+	 *                  This is NOT an error flag. To check for errors you will want
1278
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1279
+	 */
1280
+	public static function generate_default_message_templates()
1281
+	{
1282
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1283
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1284
+		/*
1285 1285
          * This first method is taking care of ensuring any default messengers
1286 1286
          * that should be made active and have templates generated are done.
1287 1287
          */
1288
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1289
-            $message_resource_manager
1290
-        );
1291
-        /**
1292
-         * This method is verifying there are no NEW default message types
1293
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1294
-         */
1295
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1296
-            $message_resource_manager
1297
-        );
1298
-        //after all is done, let's persist these changes to the db.
1299
-        $message_resource_manager->update_has_activated_messengers_option();
1300
-        $message_resource_manager->update_active_messengers_option();
1301
-        // will return true if either of these are true.  Otherwise will return false.
1302
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1303
-    }
1304
-
1305
-
1306
-
1307
-    /**
1308
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1309
-     * @return array|bool
1310
-     * @throws \EE_Error
1311
-     */
1312
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1313
-        EE_Message_Resource_Manager $message_resource_manager
1314
-    ) {
1315
-        /** @type EE_messenger[] $active_messengers */
1316
-        $active_messengers = $message_resource_manager->active_messengers();
1317
-        $installed_message_types = $message_resource_manager->installed_message_types();
1318
-        $templates_created = false;
1319
-        foreach ($active_messengers as $active_messenger) {
1320
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1321
-            $default_message_type_names_to_activate = array();
1322
-            // looping through each default message type reported by the messenger
1323
-            // and setup the actual message types to activate.
1324
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1325
-                // if already active or has already been activated before we skip
1326
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1327
-                // we also skip if the message type is not installed.
1328
-                if (
1329
-                    $message_resource_manager->has_message_type_been_activated_for_messenger($default_message_type_name_for_messenger, $active_messenger->name)
1330
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1331
-                        $active_messenger->name,
1332
-                        $default_message_type_name_for_messenger
1333
-                    )
1334
-                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1335
-                ) {
1336
-                    continue;
1337
-                }
1338
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1339
-            }
1340
-            //let's activate!
1341
-            $message_resource_manager->ensure_message_types_are_active(
1342
-                $default_message_type_names_to_activate,
1343
-                $active_messenger->name,
1344
-                false
1345
-            );
1346
-            //activate the templates for these message types
1347
-            if ( ! empty($default_message_type_names_to_activate)) {
1348
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1349
-                    $active_messenger->name,
1350
-                    $default_message_type_names_for_messenger,
1351
-                    '',
1352
-                    true
1353
-                );
1354
-            }
1355
-        }
1356
-        return $templates_created;
1357
-    }
1358
-
1359
-
1360
-
1361
-    /**
1362
-     * This will activate and generate default messengers and default message types for those messengers.
1363
-     *
1364
-     * @param EE_message_Resource_Manager $message_resource_manager
1365
-     * @return array|bool  True means there were default messengers and message type templates generated.
1366
-     *                     False means that there were no templates generated
1367
-     *                     (which could simply mean there are no default message types for a messenger).
1368
-     * @throws EE_Error
1369
-     */
1370
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1371
-        EE_Message_Resource_Manager $message_resource_manager
1372
-    ) {
1373
-        /** @type EE_messenger[] $messengers_to_generate */
1374
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1375
-        $installed_message_types = $message_resource_manager->installed_message_types();
1376
-        $templates_generated = false;
1377
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1378
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1379
-            //verify the default message types match an installed message type.
1380
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1381
-                if (
1382
-                    ! isset($installed_message_types[$name])
1383
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger($name, $messenger_to_generate->name)
1384
-                ) {
1385
-                    unset($default_message_type_names_for_messenger[$key]);
1386
-                }
1387
-            }
1388
-            // in previous iterations, the active_messengers option in the db
1389
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1390
-            // This comment is left here just in case we discover that we _do_ need to update before
1391
-            // passing off to create templates (after the refactor is done).
1392
-            // @todo remove this comment when determined not necessary.
1393
-            $message_resource_manager->activate_messenger(
1394
-                $messenger_to_generate->name,
1395
-                $default_message_type_names_for_messenger,
1396
-                false
1397
-            );
1398
-            //create any templates needing created (or will reactivate templates already generated as necessary).
1399
-            if ( ! empty($default_message_type_names_for_messenger)) {
1400
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1401
-                    $messenger_to_generate->name,
1402
-                    $default_message_type_names_for_messenger,
1403
-                    '',
1404
-                    true
1405
-                );
1406
-            }
1407
-        }
1408
-        return $templates_generated;
1409
-    }
1410
-
1411
-
1412
-
1413
-    /**
1414
-     * This returns the default messengers to generate templates for on activation of EE.
1415
-     * It considers:
1416
-     * - whether a messenger is already active in the db.
1417
-     * - whether a messenger has been made active at any time in the past.
1418
-     *
1419
-     * @static
1420
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1421
-     * @return EE_messenger[]
1422
-     */
1423
-    protected static function _get_default_messengers_to_generate_on_activation(
1424
-        EE_Message_Resource_Manager $message_resource_manager
1425
-    ) {
1426
-        $active_messengers = $message_resource_manager->active_messengers();
1427
-        $installed_messengers = $message_resource_manager->installed_messengers();
1428
-        $has_activated = $message_resource_manager->get_has_activated_messengers_option();
1429
-        $messengers_to_generate = array();
1430
-        foreach ($installed_messengers as $installed_messenger) {
1431
-            //if installed messenger is a messenger that should be activated on install
1432
-            //and is not already active
1433
-            //and has never been activated
1434
-            if (
1435
-                ! $installed_messenger->activate_on_install
1436
-                || isset($active_messengers[$installed_messenger->name])
1437
-                || isset($has_activated[$installed_messenger->name])
1438
-            ) {
1439
-                continue;
1440
-            }
1441
-            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1442
-        }
1443
-        return $messengers_to_generate;
1444
-    }
1445
-
1446
-
1447
-
1448
-    /**
1449
-     * This simply validates active message types to ensure they actually match installed
1450
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1451
-     * rows are set inactive.
1452
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1453
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1454
-     * are still handled in here.
1455
-     *
1456
-     * @since 4.3.1
1457
-     * @return void
1458
-     */
1459
-    public static function validate_messages_system()
1460
-    {
1461
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1462
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1463
-        $message_resource_manager->validate_active_message_types_are_installed();
1464
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1465
-    }
1466
-
1467
-
1468
-
1469
-    /**
1470
-     * create_no_ticket_prices_array
1471
-     *
1472
-     * @access public
1473
-     * @static
1474
-     * @return void
1475
-     */
1476
-    public static function create_no_ticket_prices_array()
1477
-    {
1478
-        // this creates an array for tracking events that have no active ticket prices created
1479
-        // this allows us to warn admins of the situation so that it can be corrected
1480
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1481
-        if ( ! $espresso_no_ticket_prices) {
1482
-            add_option('ee_no_ticket_prices', array(), '', false);
1483
-        }
1484
-    }
1485
-
1486
-
1487
-
1488
-    /**
1489
-     * plugin_deactivation
1490
-     *
1491
-     * @access public
1492
-     * @static
1493
-     * @return void
1494
-     */
1495
-    public static function plugin_deactivation()
1496
-    {
1497
-    }
1498
-
1499
-
1500
-
1501
-    /**
1502
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1503
-     * (like post meta or term relations)
1504
-     *
1505
-     * @global wpdb $wpdb
1506
-     * @throws \EE_Error
1507
-     */
1508
-    public static function delete_all_espresso_cpt_data()
1509
-    {
1510
-        global $wpdb;
1511
-        //get all the CPT post_types
1512
-        $ee_post_types = array();
1513
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1514
-            if (method_exists($model_name, 'instance')) {
1515
-                $model_obj = call_user_func(array($model_name, 'instance'));
1516
-                if ($model_obj instanceof EEM_CPT_Base) {
1517
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1518
-                }
1519
-            }
1520
-        }
1521
-        //get all our CPTs
1522
-        $query = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1523
-        $cpt_ids = $wpdb->get_col($query);
1524
-        //delete each post meta and term relations too
1525
-        foreach ($cpt_ids as $post_id) {
1526
-            wp_delete_post($post_id, true);
1527
-        }
1528
-    }
1529
-
1530
-
1531
-
1532
-    /**
1533
-     * Deletes all EE custom tables
1534
-     *
1535
-     * @return array
1536
-     */
1537
-    public static function drop_espresso_tables()
1538
-    {
1539
-        $tables = array();
1540
-        // load registry
1541
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1542
-            if (method_exists($model_name, 'instance')) {
1543
-                $model_obj = call_user_func(array($model_name, 'instance'));
1544
-                if ($model_obj instanceof EEM_Base) {
1545
-                    foreach ($model_obj->get_tables() as $table) {
1546
-                        if (strpos($table->get_table_name(), 'esp_')
1547
-                            && (
1548
-                                is_main_site()//main site? nuke them all
1549
-                                || ! $table->is_global()//not main site,but not global either. nuke it
1550
-                            )
1551
-                        ) {
1552
-                            $tables[] = $table->get_table_name();
1553
-                        }
1554
-                    }
1555
-                }
1556
-            }
1557
-        }
1558
-        //there are some tables whose models were removed.
1559
-        //they should be removed when removing all EE core's data
1560
-        $tables_without_models = array(
1561
-            'esp_promotion',
1562
-            'esp_promotion_applied',
1563
-            'esp_promotion_object',
1564
-            'esp_promotion_rule',
1565
-            'esp_rule',
1566
-        );
1567
-        foreach ($tables_without_models as $table) {
1568
-            $tables[] = $table;
1569
-        }
1570
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1577
-     * each table name provided has a wpdb prefix attached, and that it exists.
1578
-     * Returns the list actually deleted
1579
-     *
1580
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1581
-     * @global WPDB $wpdb
1582
-     * @param array $table_names
1583
-     * @return array of table names which we deleted
1584
-     */
1585
-    public static function drop_tables($table_names)
1586
-    {
1587
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1588
-    }
1589
-
1590
-
1591
-
1592
-    /**
1593
-     * plugin_uninstall
1594
-     *
1595
-     * @access public
1596
-     * @static
1597
-     * @param bool $remove_all
1598
-     * @return void
1599
-     */
1600
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1601
-    {
1602
-        global $wpdb;
1603
-        self::drop_espresso_tables();
1604
-        $wp_options_to_delete = array(
1605
-            'ee_no_ticket_prices'                => true,
1606
-            'ee_active_messengers'               => true,
1607
-            'ee_has_activated_messenger'         => true,
1608
-            'ee_flush_rewrite_rules'             => true,
1609
-            'ee_config'                          => false,
1610
-            'ee_data_migration_current_db_state' => true,
1611
-            'ee_data_migration_mapping_'         => false,
1612
-            'ee_data_migration_script_'          => false,
1613
-            'ee_data_migrations'                 => true,
1614
-            'ee_dms_map'                         => false,
1615
-            'ee_notices'                         => true,
1616
-            'lang_file_check_'                   => false,
1617
-            'ee_maintenance_mode'                => true,
1618
-            'ee_ueip_optin'                      => true,
1619
-            'ee_ueip_has_notified'               => true,
1620
-            'ee_plugin_activation_errors'        => true,
1621
-            'ee_id_mapping_from'                 => false,
1622
-            'espresso_persistent_admin_notices'  => true,
1623
-            'ee_encryption_key'                  => true,
1624
-            'pue_force_upgrade_'                 => false,
1625
-            'pue_json_error_'                    => false,
1626
-            'pue_install_key_'                   => false,
1627
-            'pue_verification_error_'            => false,
1628
-            'pu_dismissed_upgrade_'              => false,
1629
-            'external_updates-'                  => false,
1630
-            'ee_extra_data'                      => true,
1631
-            'ee_ssn_'                            => false,
1632
-            'ee_rss_'                            => false,
1633
-            'ee_rte_n_tx_'                       => false,
1634
-            'ee_pers_admin_notices'              => true,
1635
-            'ee_job_parameters_'                 => false,
1636
-            'ee_upload_directories_incomplete'   => true,
1637
-        );
1638
-        if (is_main_site()) {
1639
-            $wp_options_to_delete['ee_network_config'] = true;
1640
-        }
1641
-        $undeleted_options = array();
1642
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1643
-            if ($no_wildcard) {
1644
-                if ( ! delete_option($option_name)) {
1645
-                    $undeleted_options[] = $option_name;
1646
-                }
1647
-            } else {
1648
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1649
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1650
-                    if ( ! delete_option($option_name_from_wildcard)) {
1651
-                        $undeleted_options[] = $option_name_from_wildcard;
1652
-                    }
1653
-                }
1654
-            }
1655
-        }
1656
-        //also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1657
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1658
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1659
-            $db_update_sans_ee4 = array();
1660
-            foreach ($espresso_db_update as $version => $times_activated) {
1661
-                if ((string)$version[0] === '3') {//if its NON EE4
1662
-                    $db_update_sans_ee4[$version] = $times_activated;
1663
-                }
1664
-            }
1665
-            update_option('espresso_db_update', $db_update_sans_ee4);
1666
-        }
1667
-        $errors = '';
1668
-        if ( ! empty($undeleted_options)) {
1669
-            $errors .= sprintf(
1670
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1671
-                '<br/>',
1672
-                implode(',<br/>', $undeleted_options)
1673
-            );
1674
-        }
1675
-        if ( ! empty($errors)) {
1676
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1677
-        }
1678
-    }
1679
-
1680
-
1681
-
1682
-    /**
1683
-     * Gets the mysql error code from the last used query by wpdb
1684
-     *
1685
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1686
-     */
1687
-    public static function last_wpdb_error_code()
1688
-    {
1689
-        global $wpdb;
1690
-        if ($wpdb->use_mysqli) {
1691
-            return mysqli_errno($wpdb->dbh);
1692
-        } else {
1693
-            return mysql_errno($wpdb->dbh);
1694
-        }
1695
-    }
1696
-
1697
-
1698
-
1699
-    /**
1700
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1701
-     *
1702
-     * @global wpdb  $wpdb
1703
-     * @deprecated instead use TableAnalysis::tableExists()
1704
-     * @param string $table_name with or without $wpdb->prefix
1705
-     * @return boolean
1706
-     */
1707
-    public static function table_exists($table_name)
1708
-    {
1709
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1710
-    }
1711
-
1712
-
1713
-
1714
-    /**
1715
-     * Resets the cache on EEH_Activation
1716
-     */
1717
-    public static function reset()
1718
-    {
1719
-        self::$_default_creator_id = null;
1720
-        self::$_initialized_db_content_already_in_this_request = false;
1721
-    }
1288
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1289
+			$message_resource_manager
1290
+		);
1291
+		/**
1292
+		 * This method is verifying there are no NEW default message types
1293
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1294
+		 */
1295
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1296
+			$message_resource_manager
1297
+		);
1298
+		//after all is done, let's persist these changes to the db.
1299
+		$message_resource_manager->update_has_activated_messengers_option();
1300
+		$message_resource_manager->update_active_messengers_option();
1301
+		// will return true if either of these are true.  Otherwise will return false.
1302
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1303
+	}
1304
+
1305
+
1306
+
1307
+	/**
1308
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1309
+	 * @return array|bool
1310
+	 * @throws \EE_Error
1311
+	 */
1312
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1313
+		EE_Message_Resource_Manager $message_resource_manager
1314
+	) {
1315
+		/** @type EE_messenger[] $active_messengers */
1316
+		$active_messengers = $message_resource_manager->active_messengers();
1317
+		$installed_message_types = $message_resource_manager->installed_message_types();
1318
+		$templates_created = false;
1319
+		foreach ($active_messengers as $active_messenger) {
1320
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1321
+			$default_message_type_names_to_activate = array();
1322
+			// looping through each default message type reported by the messenger
1323
+			// and setup the actual message types to activate.
1324
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1325
+				// if already active or has already been activated before we skip
1326
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1327
+				// we also skip if the message type is not installed.
1328
+				if (
1329
+					$message_resource_manager->has_message_type_been_activated_for_messenger($default_message_type_name_for_messenger, $active_messenger->name)
1330
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1331
+						$active_messenger->name,
1332
+						$default_message_type_name_for_messenger
1333
+					)
1334
+					|| ! isset($installed_message_types[$default_message_type_name_for_messenger])
1335
+				) {
1336
+					continue;
1337
+				}
1338
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1339
+			}
1340
+			//let's activate!
1341
+			$message_resource_manager->ensure_message_types_are_active(
1342
+				$default_message_type_names_to_activate,
1343
+				$active_messenger->name,
1344
+				false
1345
+			);
1346
+			//activate the templates for these message types
1347
+			if ( ! empty($default_message_type_names_to_activate)) {
1348
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1349
+					$active_messenger->name,
1350
+					$default_message_type_names_for_messenger,
1351
+					'',
1352
+					true
1353
+				);
1354
+			}
1355
+		}
1356
+		return $templates_created;
1357
+	}
1358
+
1359
+
1360
+
1361
+	/**
1362
+	 * This will activate and generate default messengers and default message types for those messengers.
1363
+	 *
1364
+	 * @param EE_message_Resource_Manager $message_resource_manager
1365
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1366
+	 *                     False means that there were no templates generated
1367
+	 *                     (which could simply mean there are no default message types for a messenger).
1368
+	 * @throws EE_Error
1369
+	 */
1370
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1371
+		EE_Message_Resource_Manager $message_resource_manager
1372
+	) {
1373
+		/** @type EE_messenger[] $messengers_to_generate */
1374
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1375
+		$installed_message_types = $message_resource_manager->installed_message_types();
1376
+		$templates_generated = false;
1377
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1378
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1379
+			//verify the default message types match an installed message type.
1380
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1381
+				if (
1382
+					! isset($installed_message_types[$name])
1383
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger($name, $messenger_to_generate->name)
1384
+				) {
1385
+					unset($default_message_type_names_for_messenger[$key]);
1386
+				}
1387
+			}
1388
+			// in previous iterations, the active_messengers option in the db
1389
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1390
+			// This comment is left here just in case we discover that we _do_ need to update before
1391
+			// passing off to create templates (after the refactor is done).
1392
+			// @todo remove this comment when determined not necessary.
1393
+			$message_resource_manager->activate_messenger(
1394
+				$messenger_to_generate->name,
1395
+				$default_message_type_names_for_messenger,
1396
+				false
1397
+			);
1398
+			//create any templates needing created (or will reactivate templates already generated as necessary).
1399
+			if ( ! empty($default_message_type_names_for_messenger)) {
1400
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1401
+					$messenger_to_generate->name,
1402
+					$default_message_type_names_for_messenger,
1403
+					'',
1404
+					true
1405
+				);
1406
+			}
1407
+		}
1408
+		return $templates_generated;
1409
+	}
1410
+
1411
+
1412
+
1413
+	/**
1414
+	 * This returns the default messengers to generate templates for on activation of EE.
1415
+	 * It considers:
1416
+	 * - whether a messenger is already active in the db.
1417
+	 * - whether a messenger has been made active at any time in the past.
1418
+	 *
1419
+	 * @static
1420
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1421
+	 * @return EE_messenger[]
1422
+	 */
1423
+	protected static function _get_default_messengers_to_generate_on_activation(
1424
+		EE_Message_Resource_Manager $message_resource_manager
1425
+	) {
1426
+		$active_messengers = $message_resource_manager->active_messengers();
1427
+		$installed_messengers = $message_resource_manager->installed_messengers();
1428
+		$has_activated = $message_resource_manager->get_has_activated_messengers_option();
1429
+		$messengers_to_generate = array();
1430
+		foreach ($installed_messengers as $installed_messenger) {
1431
+			//if installed messenger is a messenger that should be activated on install
1432
+			//and is not already active
1433
+			//and has never been activated
1434
+			if (
1435
+				! $installed_messenger->activate_on_install
1436
+				|| isset($active_messengers[$installed_messenger->name])
1437
+				|| isset($has_activated[$installed_messenger->name])
1438
+			) {
1439
+				continue;
1440
+			}
1441
+			$messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1442
+		}
1443
+		return $messengers_to_generate;
1444
+	}
1445
+
1446
+
1447
+
1448
+	/**
1449
+	 * This simply validates active message types to ensure they actually match installed
1450
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1451
+	 * rows are set inactive.
1452
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1453
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1454
+	 * are still handled in here.
1455
+	 *
1456
+	 * @since 4.3.1
1457
+	 * @return void
1458
+	 */
1459
+	public static function validate_messages_system()
1460
+	{
1461
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1462
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1463
+		$message_resource_manager->validate_active_message_types_are_installed();
1464
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1465
+	}
1466
+
1467
+
1468
+
1469
+	/**
1470
+	 * create_no_ticket_prices_array
1471
+	 *
1472
+	 * @access public
1473
+	 * @static
1474
+	 * @return void
1475
+	 */
1476
+	public static function create_no_ticket_prices_array()
1477
+	{
1478
+		// this creates an array for tracking events that have no active ticket prices created
1479
+		// this allows us to warn admins of the situation so that it can be corrected
1480
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1481
+		if ( ! $espresso_no_ticket_prices) {
1482
+			add_option('ee_no_ticket_prices', array(), '', false);
1483
+		}
1484
+	}
1485
+
1486
+
1487
+
1488
+	/**
1489
+	 * plugin_deactivation
1490
+	 *
1491
+	 * @access public
1492
+	 * @static
1493
+	 * @return void
1494
+	 */
1495
+	public static function plugin_deactivation()
1496
+	{
1497
+	}
1498
+
1499
+
1500
+
1501
+	/**
1502
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1503
+	 * (like post meta or term relations)
1504
+	 *
1505
+	 * @global wpdb $wpdb
1506
+	 * @throws \EE_Error
1507
+	 */
1508
+	public static function delete_all_espresso_cpt_data()
1509
+	{
1510
+		global $wpdb;
1511
+		//get all the CPT post_types
1512
+		$ee_post_types = array();
1513
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1514
+			if (method_exists($model_name, 'instance')) {
1515
+				$model_obj = call_user_func(array($model_name, 'instance'));
1516
+				if ($model_obj instanceof EEM_CPT_Base) {
1517
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1518
+				}
1519
+			}
1520
+		}
1521
+		//get all our CPTs
1522
+		$query = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1523
+		$cpt_ids = $wpdb->get_col($query);
1524
+		//delete each post meta and term relations too
1525
+		foreach ($cpt_ids as $post_id) {
1526
+			wp_delete_post($post_id, true);
1527
+		}
1528
+	}
1529
+
1530
+
1531
+
1532
+	/**
1533
+	 * Deletes all EE custom tables
1534
+	 *
1535
+	 * @return array
1536
+	 */
1537
+	public static function drop_espresso_tables()
1538
+	{
1539
+		$tables = array();
1540
+		// load registry
1541
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1542
+			if (method_exists($model_name, 'instance')) {
1543
+				$model_obj = call_user_func(array($model_name, 'instance'));
1544
+				if ($model_obj instanceof EEM_Base) {
1545
+					foreach ($model_obj->get_tables() as $table) {
1546
+						if (strpos($table->get_table_name(), 'esp_')
1547
+							&& (
1548
+								is_main_site()//main site? nuke them all
1549
+								|| ! $table->is_global()//not main site,but not global either. nuke it
1550
+							)
1551
+						) {
1552
+							$tables[] = $table->get_table_name();
1553
+						}
1554
+					}
1555
+				}
1556
+			}
1557
+		}
1558
+		//there are some tables whose models were removed.
1559
+		//they should be removed when removing all EE core's data
1560
+		$tables_without_models = array(
1561
+			'esp_promotion',
1562
+			'esp_promotion_applied',
1563
+			'esp_promotion_object',
1564
+			'esp_promotion_rule',
1565
+			'esp_rule',
1566
+		);
1567
+		foreach ($tables_without_models as $table) {
1568
+			$tables[] = $table;
1569
+		}
1570
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1577
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1578
+	 * Returns the list actually deleted
1579
+	 *
1580
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1581
+	 * @global WPDB $wpdb
1582
+	 * @param array $table_names
1583
+	 * @return array of table names which we deleted
1584
+	 */
1585
+	public static function drop_tables($table_names)
1586
+	{
1587
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1588
+	}
1589
+
1590
+
1591
+
1592
+	/**
1593
+	 * plugin_uninstall
1594
+	 *
1595
+	 * @access public
1596
+	 * @static
1597
+	 * @param bool $remove_all
1598
+	 * @return void
1599
+	 */
1600
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1601
+	{
1602
+		global $wpdb;
1603
+		self::drop_espresso_tables();
1604
+		$wp_options_to_delete = array(
1605
+			'ee_no_ticket_prices'                => true,
1606
+			'ee_active_messengers'               => true,
1607
+			'ee_has_activated_messenger'         => true,
1608
+			'ee_flush_rewrite_rules'             => true,
1609
+			'ee_config'                          => false,
1610
+			'ee_data_migration_current_db_state' => true,
1611
+			'ee_data_migration_mapping_'         => false,
1612
+			'ee_data_migration_script_'          => false,
1613
+			'ee_data_migrations'                 => true,
1614
+			'ee_dms_map'                         => false,
1615
+			'ee_notices'                         => true,
1616
+			'lang_file_check_'                   => false,
1617
+			'ee_maintenance_mode'                => true,
1618
+			'ee_ueip_optin'                      => true,
1619
+			'ee_ueip_has_notified'               => true,
1620
+			'ee_plugin_activation_errors'        => true,
1621
+			'ee_id_mapping_from'                 => false,
1622
+			'espresso_persistent_admin_notices'  => true,
1623
+			'ee_encryption_key'                  => true,
1624
+			'pue_force_upgrade_'                 => false,
1625
+			'pue_json_error_'                    => false,
1626
+			'pue_install_key_'                   => false,
1627
+			'pue_verification_error_'            => false,
1628
+			'pu_dismissed_upgrade_'              => false,
1629
+			'external_updates-'                  => false,
1630
+			'ee_extra_data'                      => true,
1631
+			'ee_ssn_'                            => false,
1632
+			'ee_rss_'                            => false,
1633
+			'ee_rte_n_tx_'                       => false,
1634
+			'ee_pers_admin_notices'              => true,
1635
+			'ee_job_parameters_'                 => false,
1636
+			'ee_upload_directories_incomplete'   => true,
1637
+		);
1638
+		if (is_main_site()) {
1639
+			$wp_options_to_delete['ee_network_config'] = true;
1640
+		}
1641
+		$undeleted_options = array();
1642
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1643
+			if ($no_wildcard) {
1644
+				if ( ! delete_option($option_name)) {
1645
+					$undeleted_options[] = $option_name;
1646
+				}
1647
+			} else {
1648
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1649
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1650
+					if ( ! delete_option($option_name_from_wildcard)) {
1651
+						$undeleted_options[] = $option_name_from_wildcard;
1652
+					}
1653
+				}
1654
+			}
1655
+		}
1656
+		//also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1657
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1658
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1659
+			$db_update_sans_ee4 = array();
1660
+			foreach ($espresso_db_update as $version => $times_activated) {
1661
+				if ((string)$version[0] === '3') {//if its NON EE4
1662
+					$db_update_sans_ee4[$version] = $times_activated;
1663
+				}
1664
+			}
1665
+			update_option('espresso_db_update', $db_update_sans_ee4);
1666
+		}
1667
+		$errors = '';
1668
+		if ( ! empty($undeleted_options)) {
1669
+			$errors .= sprintf(
1670
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1671
+				'<br/>',
1672
+				implode(',<br/>', $undeleted_options)
1673
+			);
1674
+		}
1675
+		if ( ! empty($errors)) {
1676
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1677
+		}
1678
+	}
1679
+
1680
+
1681
+
1682
+	/**
1683
+	 * Gets the mysql error code from the last used query by wpdb
1684
+	 *
1685
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1686
+	 */
1687
+	public static function last_wpdb_error_code()
1688
+	{
1689
+		global $wpdb;
1690
+		if ($wpdb->use_mysqli) {
1691
+			return mysqli_errno($wpdb->dbh);
1692
+		} else {
1693
+			return mysql_errno($wpdb->dbh);
1694
+		}
1695
+	}
1696
+
1697
+
1698
+
1699
+	/**
1700
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1701
+	 *
1702
+	 * @global wpdb  $wpdb
1703
+	 * @deprecated instead use TableAnalysis::tableExists()
1704
+	 * @param string $table_name with or without $wpdb->prefix
1705
+	 * @return boolean
1706
+	 */
1707
+	public static function table_exists($table_name)
1708
+	{
1709
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1710
+	}
1711
+
1712
+
1713
+
1714
+	/**
1715
+	 * Resets the cache on EEH_Activation
1716
+	 */
1717
+	public static function reset()
1718
+	{
1719
+		self::$_default_creator_id = null;
1720
+		self::$_initialized_db_content_already_in_this_request = false;
1721
+	}
1722 1722
 }
1723 1723
 // End of file EEH_Activation.helper.php
1724 1724
 // Location: /helpers/EEH_Activation.core.php
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
         if ($which_to_include === 'old') {
195 195
             $cron_tasks = array_filter(
196 196
                 $cron_tasks,
197
-                function ($value) {
197
+                function($value) {
198 198
                     return $value === EEH_Activation::cron_task_no_longer_in_use;
199 199
                 }
200 200
             );
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
     public static function load_calendar_config()
330 330
     {
331 331
         // grab array of all plugin folders and loop thru it
332
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
332
+        $plugins = glob(WP_PLUGIN_DIR.DS.'*', GLOB_ONLYDIR);
333 333
         if (empty($plugins)) {
334 334
             return;
335 335
         }
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
                 || strpos($plugin, 'calendar') !== false
347 347
             ) {
348 348
                 // this is what we are looking for
349
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
349
+                $calendar_config = $plugin_path.DS.'EE_Calendar_Config.php';
350 350
                 // does it exist in this folder ?
351 351
                 if (is_readable($calendar_config)) {
352 352
                     // YEAH! let's load it
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
         if ($critical_page_problem) {
491 491
             $msg = sprintf(
492 492
                 __('A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.', 'event_espresso'),
493
-                '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">' . __('Event Espresso Critical Pages Settings', 'event_espresso') . '</a>'
493
+                '<a href="'.admin_url('admin.php?page=espresso_general_settings&action=critical_pages').'">'.__('Event Espresso Critical Pages Settings', 'event_espresso').'</a>'
494 494
             );
495 495
             EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
496 496
         }
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
     public static function get_page_by_ee_shortcode($ee_shortcode)
514 514
     {
515 515
         global $wpdb;
516
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
516
+        $shortcode_and_opening_bracket = '['.$ee_shortcode;
517 517
         $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
518 518
         if ($post_id) {
519 519
             return get_post($post_id);
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
             'post_status'    => 'publish',
541 541
             'post_type'      => 'page',
542 542
             'comment_status' => 'closed',
543
-            'post_content'   => '[' . $critical_page['code'] . ']',
543
+            'post_content'   => '['.$critical_page['code'].']',
544 544
         );
545 545
         $post_id = wp_insert_post($post_args);
546 546
         if ( ! $post_id) {
@@ -625,14 +625,14 @@  discard block
 block discarded – undo
625 625
         //let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
626 626
         $pre_filtered_id = apply_filters('FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id', false, $role_to_check);
627 627
         if ($pre_filtered_id !== false) {
628
-            return (int)$pre_filtered_id;
628
+            return (int) $pre_filtered_id;
629 629
         }
630 630
         $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
631
-        $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1", '%' . $role_to_check . '%');
631
+        $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1", '%'.$role_to_check.'%');
632 632
         $user_id = $wpdb->get_var($query);
633 633
         $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
634
-        if ($user_id && (int)$user_id) {
635
-            self::$_default_creator_id = (int)$user_id;
634
+        if ($user_id && (int) $user_id) {
635
+            self::$_default_creator_id = (int) $user_id;
636 636
             return self::$_default_creator_id;
637 637
         } else {
638 638
             return null;
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
         }
667 667
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
668 668
         if ( ! function_exists('dbDelta')) {
669
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
669
+            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
670 670
         }
671 671
         $tableAnalysis = \EEH_Activation::getTableAnalysis();
672 672
         $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
             } else if ( ! $deleted_safely) {
681 681
                 // so we should be more cautious rather than just dropping tables so easily
682 682
                 EE_Error::add_persistent_admin_notice(
683
-                    'bad_table_' . $wp_table_name . '_detected',
683
+                    'bad_table_'.$wp_table_name.'_detected',
684 684
                     sprintf(__('Database table %1$s exists when it shouldn\'t, and may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend adding %2$s to your %3$s file then restore to that backup again. This will clear out the invalid data from %1$s. Afterwards you should undo that change from your %3$s file. %4$sIf you cannot edit %3$s, you should remove the data from %1$s manually then restore to the backup again.',
685 685
                         'event_espresso'),
686 686
                         $wp_table_name,
@@ -868,7 +868,7 @@  discard block
 block discarded – undo
868 868
                     case 1:
869 869
                         $QSG_values = array(
870 870
                             'QSG_name'            => __('Personal Information', 'event_espresso'),
871
-                            'QSG_identifier'      => 'personal-information-' . time(),
871
+                            'QSG_identifier'      => 'personal-information-'.time(),
872 872
                             'QSG_desc'            => '',
873 873
                             'QSG_order'           => 1,
874 874
                             'QSG_show_group_name' => 1,
@@ -880,7 +880,7 @@  discard block
 block discarded – undo
880 880
                     case 2:
881 881
                         $QSG_values = array(
882 882
                             'QSG_name'            => __('Address Information', 'event_espresso'),
883
-                            'QSG_identifier'      => 'address-information-' . time(),
883
+                            'QSG_identifier'      => 'address-information-'.time(),
884 884
                             'QSG_desc'            => '',
885 885
                             'QSG_order'           => 2,
886 886
                             'QSG_show_group_name' => 1,
@@ -1219,9 +1219,9 @@  discard block
 block discarded – undo
1219 1219
         $folders = array(
1220 1220
             EVENT_ESPRESSO_TEMPLATE_DIR,
1221 1221
             EVENT_ESPRESSO_GATEWAY_DIR,
1222
-            EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1223
-            EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1224
-            EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1222
+            EVENT_ESPRESSO_UPLOAD_DIR.'logs/',
1223
+            EVENT_ESPRESSO_UPLOAD_DIR.'css/',
1224
+            EVENT_ESPRESSO_UPLOAD_DIR.'tickets/',
1225 1225
         );
1226 1226
         foreach ($folders as $folder) {
1227 1227
             try {
@@ -1232,7 +1232,7 @@  discard block
 block discarded – undo
1232 1232
                     sprintf(
1233 1233
                         __('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1234 1234
                         $folder,
1235
-                        '<br />' . $e->getMessage()
1235
+                        '<br />'.$e->getMessage()
1236 1236
                     ),
1237 1237
                     __FILE__, __FUNCTION__, __LINE__
1238 1238
                 );
@@ -1243,7 +1243,7 @@  discard block
 block discarded – undo
1243 1243
         }
1244 1244
         //just add the .htaccess file to the logs directory to begin with. Even if logging
1245 1245
         //is disabled, there might be activation errors recorded in there
1246
-        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1246
+        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR.'logs/');
1247 1247
         //remember EE's folders are all good
1248 1248
         delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1249 1249
         return true;
@@ -1519,7 +1519,7 @@  discard block
 block discarded – undo
1519 1519
             }
1520 1520
         }
1521 1521
         //get all our CPTs
1522
-        $query = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1522
+        $query = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (".implode(",", $ee_post_types).")";
1523 1523
         $cpt_ids = $wpdb->get_col($query);
1524 1524
         //delete each post meta and term relations too
1525 1525
         foreach ($cpt_ids as $post_id) {
@@ -1658,7 +1658,7 @@  discard block
 block discarded – undo
1658 1658
         if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1659 1659
             $db_update_sans_ee4 = array();
1660 1660
             foreach ($espresso_db_update as $version => $times_activated) {
1661
-                if ((string)$version[0] === '3') {//if its NON EE4
1661
+                if ((string) $version[0] === '3') {//if its NON EE4
1662 1662
                     $db_update_sans_ee4[$version] = $times_activated;
1663 1663
                 }
1664 1664
             }
Please login to merge, or discard this patch.
caffeinated/brewing_regular.php 2 patches
Indentation   +269 added lines, -269 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\services\database\TableAnalysis;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 /**
8 8
  * the purpose of this file is to simply contain any action/filter hook callbacks etc for specific aspects of EE
@@ -27,277 +27,277 @@  discard block
 block discarded – undo
27 27
 class EE_Brewing_Regular extends EE_BASE
28 28
 {
29 29
 
30
-    /**
31
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
32
-     */
33
-    protected $_table_analysis;
34
-
35
-
36
-
37
-    /**
38
-     * EE_Brewing_Regular constructor.
39
-     */
40
-    public function __construct(TableAnalysis $table_analysis)
41
-    {
42
-        $this->_table_analysis = $table_analysis;
43
-        if (defined('EE_CAFF_PATH')) {
44
-            // activation
45
-            add_action('AHEE__EEH_Activation__initialize_db_content', array($this, 'initialize_caf_db_content'));
46
-            // load caff init
47
-            add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'caffeinated_init'));
48
-            // remove the "powered by" credit link from receipts and invoices
49
-            add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
50
-            // add caffeinated modules
51
-            add_filter(
52
-                'FHEE__EE_Config__register_modules__modules_to_register',
53
-                array($this, 'caffeinated_modules_to_register')
54
-            );
55
-            // load caff scripts
56
-            add_action('wp_enqueue_scripts', array($this, 'enqueue_caffeinated_scripts'), 10);
57
-            add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
58
-            add_filter(
59
-                'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
60
-                array($this, 'caf_payment_methods')
61
-            );
62
-            // caffeinated constructed
63
-            do_action('AHEE__EE_Brewing_Regular__construct__complete');
64
-            //seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
65
-            add_filter('FHEE__ee_show_affiliate_links', '__return_false');
66
-        }
67
-    }
68
-
69
-
70
-
71
-    /**
72
-     * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
73
-     *
74
-     * @param array $paths original helper paths array
75
-     * @return array             new array of paths
76
-     */
77
-    public function caf_helper_paths($paths)
78
-    {
79
-        $paths[] = EE_CAF_CORE . 'helpers' . DS;
80
-        return $paths;
81
-    }
82
-
83
-
84
-
85
-    /**
86
-     * Upon brand-new activation, if this is a new activation of CAF, we want to add
87
-     * some global prices that will show off EE4's capabilities. However, if they're upgrading
88
-     * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
89
-     * This action should only be called when EE 4.x.0.P is initially activated.
90
-     * Right now the only CAF content are these global prices. If there's more in the future, then
91
-     * we should probably create a caf file to contain it all instead just a function like this.
92
-     * Right now, we ASSUME the only price types in the system are default ones
93
-     *
94
-     * @global wpdb $wpdb
95
-     */
96
-    public function initialize_caf_db_content()
97
-    {
98
-        global $wpdb;
99
-        //use same method of getting creator id as the version introducing the change
100
-        $default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
101
-        $price_type_table = $wpdb->prefix . "esp_price_type";
102
-        $price_table = $wpdb->prefix . "esp_price";
103
-        if ($this->_get_table_analysis()->tableExists($price_type_table)) {
104
-            $SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
105
-            $tax_price_type_count = $wpdb->get_var($SQL);
106
-            if ($tax_price_type_count <= 1) {
107
-                $wpdb->insert(
108
-                    $price_type_table,
109
-                    array(
110
-                        'PRT_name'       => __("Regional Tax", "event_espresso"),
111
-                        'PBT_ID'         => 4,
112
-                        'PRT_is_percent' => true,
113
-                        'PRT_order'      => 60,
114
-                        'PRT_deleted'    => false,
115
-                        'PRT_wp_user'    => $default_creator_id,
116
-                    ),
117
-                    array(
118
-                        '%s',//PRT_name
119
-                        '%d',//PBT_id
120
-                        '%d',//PRT_is_percent
121
-                        '%d',//PRT_order
122
-                        '%d',//PRT_deleted
123
-                        '%d', //PRT_wp_user
124
-                    )
125
-                );
126
-                //federal tax
127
-                $result = $wpdb->insert(
128
-                    $price_type_table,
129
-                    array(
130
-                        'PRT_name'       => __("Federal Tax", "event_espresso"),
131
-                        'PBT_ID'         => 4,
132
-                        'PRT_is_percent' => true,
133
-                        'PRT_order'      => 70,
134
-                        'PRT_deleted'    => false,
135
-                        'PRT_wp_user'    => $default_creator_id,
136
-                    ),
137
-                    array(
138
-                        '%s',//PRT_name
139
-                        '%d',//PBT_id
140
-                        '%d',//PRT_is_percent
141
-                        '%d',//PRT_order
142
-                        '%d',//PRT_deleted
143
-                        '%d' //PRT_wp_user
144
-                    )
145
-                );
146
-                if ($result) {
147
-                    $wpdb->insert(
148
-                        $price_table,
149
-                        array(
150
-                            'PRT_ID'         => $wpdb->insert_id,
151
-                            'PRC_amount'     => 15.00,
152
-                            'PRC_name'       => __("Sales Tax", "event_espresso"),
153
-                            'PRC_desc'       => '',
154
-                            'PRC_is_default' => true,
155
-                            'PRC_overrides'  => null,
156
-                            'PRC_deleted'    => false,
157
-                            'PRC_order'      => 50,
158
-                            'PRC_parent'     => null,
159
-                            'PRC_wp_user'    => $default_creator_id,
160
-                        ),
161
-                        array(
162
-                            '%d',//PRT_id
163
-                            '%f',//PRC_amount
164
-                            '%s',//PRC_name
165
-                            '%s',//PRC_desc
166
-                            '%d',//PRC_is_default
167
-                            '%d',//PRC_overrides
168
-                            '%d',//PRC_deleted
169
-                            '%d',//PRC_order
170
-                            '%d',//PRC_parent
171
-                            '%d' //PRC_wp_user
172
-                        )
173
-                    );
174
-                }
175
-            }
176
-        }
177
-    }
178
-
179
-
180
-
181
-    /**
182
-     *    caffeinated_modules_to_register
183
-     *
184
-     * @access public
185
-     * @param array $modules_to_register
186
-     * @return array
187
-     */
188
-    public function caffeinated_modules_to_register($modules_to_register = array())
189
-    {
190
-        if (is_readable(EE_CAFF_PATH . 'modules')) {
191
-            $caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
192
-            if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
193
-                $modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
194
-            }
195
-        }
196
-        return $modules_to_register;
197
-    }
198
-
199
-
200
-
201
-    public function caffeinated_init()
202
-    {
203
-        // EE_Register_CPTs hooks
204
-        add_filter('FHEE__EE_Register_CPTs__get_taxonomies__taxonomies', array($this, 'filter_taxonomies'), 10);
205
-        add_filter('FHEE__EE_Register_CPTs__get_CPTs__cpts', array($this, 'filter_cpts'), 10);
206
-        add_filter('FHEE__EE_Admin__get_extra_nav_menu_pages_items', array($this, 'nav_metabox_items'), 10);
207
-        EE_Registry::instance()->load_file(EE_CAFF_PATH, 'EE_Caf_Messages', 'class', array(), false);
208
-        // caffeinated_init__complete hook
209
-        do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
210
-    }
211
-
212
-
213
-
214
-    public function enqueue_caffeinated_scripts()
215
-    {
216
-        // sound of crickets...
217
-    }
218
-
219
-
220
-
221
-    /**
222
-     * callbacks below here
223
-     *
224
-     * @param array $taxonomy_array
225
-     * @return array
226
-     */
227
-    public function filter_taxonomies(array $taxonomy_array)
228
-    {
229
-        $taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
230
-        return $taxonomy_array;
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * @param array $cpt_array
237
-     * @return mixed
238
-     */
239
-    public function filter_cpts(array $cpt_array)
240
-    {
241
-        $cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
242
-        return $cpt_array;
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * @param array $menuitems
249
-     * @return array
250
-     */
251
-    public function nav_metabox_items(array $menuitems)
252
-    {
253
-        $menuitems[] = array(
254
-            'title'       => __('Venue List', 'event_espresso'),
255
-            'url'         => get_post_type_archive_link('espresso_venues'),
256
-            'description' => __('Archive page for all venues.', 'event_espresso'),
257
-        );
258
-        return $menuitems;
259
-    }
260
-
261
-
262
-
263
-    /**
264
-     * Adds the payment methods in {event-espresso-core}/caffeinated/payment_methods
265
-     *
266
-     * @param array $payment_method_paths
267
-     * @return array values are folder paths to payment method folders
268
-     */
269
-    public function caf_payment_methods($payment_method_paths)
270
-    {
271
-        $caf_payment_methods_paths = glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
272
-        $payment_method_paths = array_merge($payment_method_paths, $caf_payment_methods_paths);
273
-        return $payment_method_paths;
274
-    }
275
-
276
-
277
-
278
-    /**
279
-     * Gets the injected table analyzer, or throws an exception
280
-     *
281
-     * @return TableAnalysis
282
-     * @throws \EE_Error
283
-     */
284
-    protected function _get_table_analysis()
285
-    {
286
-        if ($this->_table_analysis instanceof TableAnalysis) {
287
-            return $this->_table_analysis;
288
-        } else {
289
-            throw new \EE_Error(
290
-                sprintf(
291
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
292
-                    get_class($this)
293
-                )
294
-            );
295
-        }
296
-    }
30
+	/**
31
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
32
+	 */
33
+	protected $_table_analysis;
34
+
35
+
36
+
37
+	/**
38
+	 * EE_Brewing_Regular constructor.
39
+	 */
40
+	public function __construct(TableAnalysis $table_analysis)
41
+	{
42
+		$this->_table_analysis = $table_analysis;
43
+		if (defined('EE_CAFF_PATH')) {
44
+			// activation
45
+			add_action('AHEE__EEH_Activation__initialize_db_content', array($this, 'initialize_caf_db_content'));
46
+			// load caff init
47
+			add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'caffeinated_init'));
48
+			// remove the "powered by" credit link from receipts and invoices
49
+			add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
50
+			// add caffeinated modules
51
+			add_filter(
52
+				'FHEE__EE_Config__register_modules__modules_to_register',
53
+				array($this, 'caffeinated_modules_to_register')
54
+			);
55
+			// load caff scripts
56
+			add_action('wp_enqueue_scripts', array($this, 'enqueue_caffeinated_scripts'), 10);
57
+			add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
58
+			add_filter(
59
+				'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
60
+				array($this, 'caf_payment_methods')
61
+			);
62
+			// caffeinated constructed
63
+			do_action('AHEE__EE_Brewing_Regular__construct__complete');
64
+			//seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
65
+			add_filter('FHEE__ee_show_affiliate_links', '__return_false');
66
+		}
67
+	}
68
+
69
+
70
+
71
+	/**
72
+	 * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
73
+	 *
74
+	 * @param array $paths original helper paths array
75
+	 * @return array             new array of paths
76
+	 */
77
+	public function caf_helper_paths($paths)
78
+	{
79
+		$paths[] = EE_CAF_CORE . 'helpers' . DS;
80
+		return $paths;
81
+	}
82
+
83
+
84
+
85
+	/**
86
+	 * Upon brand-new activation, if this is a new activation of CAF, we want to add
87
+	 * some global prices that will show off EE4's capabilities. However, if they're upgrading
88
+	 * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
89
+	 * This action should only be called when EE 4.x.0.P is initially activated.
90
+	 * Right now the only CAF content are these global prices. If there's more in the future, then
91
+	 * we should probably create a caf file to contain it all instead just a function like this.
92
+	 * Right now, we ASSUME the only price types in the system are default ones
93
+	 *
94
+	 * @global wpdb $wpdb
95
+	 */
96
+	public function initialize_caf_db_content()
97
+	{
98
+		global $wpdb;
99
+		//use same method of getting creator id as the version introducing the change
100
+		$default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
101
+		$price_type_table = $wpdb->prefix . "esp_price_type";
102
+		$price_table = $wpdb->prefix . "esp_price";
103
+		if ($this->_get_table_analysis()->tableExists($price_type_table)) {
104
+			$SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
105
+			$tax_price_type_count = $wpdb->get_var($SQL);
106
+			if ($tax_price_type_count <= 1) {
107
+				$wpdb->insert(
108
+					$price_type_table,
109
+					array(
110
+						'PRT_name'       => __("Regional Tax", "event_espresso"),
111
+						'PBT_ID'         => 4,
112
+						'PRT_is_percent' => true,
113
+						'PRT_order'      => 60,
114
+						'PRT_deleted'    => false,
115
+						'PRT_wp_user'    => $default_creator_id,
116
+					),
117
+					array(
118
+						'%s',//PRT_name
119
+						'%d',//PBT_id
120
+						'%d',//PRT_is_percent
121
+						'%d',//PRT_order
122
+						'%d',//PRT_deleted
123
+						'%d', //PRT_wp_user
124
+					)
125
+				);
126
+				//federal tax
127
+				$result = $wpdb->insert(
128
+					$price_type_table,
129
+					array(
130
+						'PRT_name'       => __("Federal Tax", "event_espresso"),
131
+						'PBT_ID'         => 4,
132
+						'PRT_is_percent' => true,
133
+						'PRT_order'      => 70,
134
+						'PRT_deleted'    => false,
135
+						'PRT_wp_user'    => $default_creator_id,
136
+					),
137
+					array(
138
+						'%s',//PRT_name
139
+						'%d',//PBT_id
140
+						'%d',//PRT_is_percent
141
+						'%d',//PRT_order
142
+						'%d',//PRT_deleted
143
+						'%d' //PRT_wp_user
144
+					)
145
+				);
146
+				if ($result) {
147
+					$wpdb->insert(
148
+						$price_table,
149
+						array(
150
+							'PRT_ID'         => $wpdb->insert_id,
151
+							'PRC_amount'     => 15.00,
152
+							'PRC_name'       => __("Sales Tax", "event_espresso"),
153
+							'PRC_desc'       => '',
154
+							'PRC_is_default' => true,
155
+							'PRC_overrides'  => null,
156
+							'PRC_deleted'    => false,
157
+							'PRC_order'      => 50,
158
+							'PRC_parent'     => null,
159
+							'PRC_wp_user'    => $default_creator_id,
160
+						),
161
+						array(
162
+							'%d',//PRT_id
163
+							'%f',//PRC_amount
164
+							'%s',//PRC_name
165
+							'%s',//PRC_desc
166
+							'%d',//PRC_is_default
167
+							'%d',//PRC_overrides
168
+							'%d',//PRC_deleted
169
+							'%d',//PRC_order
170
+							'%d',//PRC_parent
171
+							'%d' //PRC_wp_user
172
+						)
173
+					);
174
+				}
175
+			}
176
+		}
177
+	}
178
+
179
+
180
+
181
+	/**
182
+	 *    caffeinated_modules_to_register
183
+	 *
184
+	 * @access public
185
+	 * @param array $modules_to_register
186
+	 * @return array
187
+	 */
188
+	public function caffeinated_modules_to_register($modules_to_register = array())
189
+	{
190
+		if (is_readable(EE_CAFF_PATH . 'modules')) {
191
+			$caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
192
+			if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
193
+				$modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
194
+			}
195
+		}
196
+		return $modules_to_register;
197
+	}
198
+
199
+
200
+
201
+	public function caffeinated_init()
202
+	{
203
+		// EE_Register_CPTs hooks
204
+		add_filter('FHEE__EE_Register_CPTs__get_taxonomies__taxonomies', array($this, 'filter_taxonomies'), 10);
205
+		add_filter('FHEE__EE_Register_CPTs__get_CPTs__cpts', array($this, 'filter_cpts'), 10);
206
+		add_filter('FHEE__EE_Admin__get_extra_nav_menu_pages_items', array($this, 'nav_metabox_items'), 10);
207
+		EE_Registry::instance()->load_file(EE_CAFF_PATH, 'EE_Caf_Messages', 'class', array(), false);
208
+		// caffeinated_init__complete hook
209
+		do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
210
+	}
211
+
212
+
213
+
214
+	public function enqueue_caffeinated_scripts()
215
+	{
216
+		// sound of crickets...
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * callbacks below here
223
+	 *
224
+	 * @param array $taxonomy_array
225
+	 * @return array
226
+	 */
227
+	public function filter_taxonomies(array $taxonomy_array)
228
+	{
229
+		$taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
230
+		return $taxonomy_array;
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * @param array $cpt_array
237
+	 * @return mixed
238
+	 */
239
+	public function filter_cpts(array $cpt_array)
240
+	{
241
+		$cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
242
+		return $cpt_array;
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * @param array $menuitems
249
+	 * @return array
250
+	 */
251
+	public function nav_metabox_items(array $menuitems)
252
+	{
253
+		$menuitems[] = array(
254
+			'title'       => __('Venue List', 'event_espresso'),
255
+			'url'         => get_post_type_archive_link('espresso_venues'),
256
+			'description' => __('Archive page for all venues.', 'event_espresso'),
257
+		);
258
+		return $menuitems;
259
+	}
260
+
261
+
262
+
263
+	/**
264
+	 * Adds the payment methods in {event-espresso-core}/caffeinated/payment_methods
265
+	 *
266
+	 * @param array $payment_method_paths
267
+	 * @return array values are folder paths to payment method folders
268
+	 */
269
+	public function caf_payment_methods($payment_method_paths)
270
+	{
271
+		$caf_payment_methods_paths = glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
272
+		$payment_method_paths = array_merge($payment_method_paths, $caf_payment_methods_paths);
273
+		return $payment_method_paths;
274
+	}
275
+
276
+
277
+
278
+	/**
279
+	 * Gets the injected table analyzer, or throws an exception
280
+	 *
281
+	 * @return TableAnalysis
282
+	 * @throws \EE_Error
283
+	 */
284
+	protected function _get_table_analysis()
285
+	{
286
+		if ($this->_table_analysis instanceof TableAnalysis) {
287
+			return $this->_table_analysis;
288
+		} else {
289
+			throw new \EE_Error(
290
+				sprintf(
291
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
292
+					get_class($this)
293
+				)
294
+			);
295
+		}
296
+	}
297 297
 }
298 298
 
299 299
 
300 300
 
301 301
 $brewing = new EE_Brewing_Regular(
302
-    EE_Registry::instance()->create('TableAnalysis', array(), true)
302
+	EE_Registry::instance()->create('TableAnalysis', array(), true)
303 303
 );
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -10,10 +10,10 @@  discard block
 block discarded – undo
10 10
  * define and use the hook in a specific caffeinated/whatever class or file.
11 11
  */
12 12
 // defined some new constants related to caffeinated folder
13
-define('EE_CAF_URL', EE_PLUGIN_DIR_URL . 'caffeinated/');
14
-define('EE_CAF_CORE', EE_CAFF_PATH . 'core' . DS);
15
-define('EE_CAF_LIBRARIES', EE_CAF_CORE . 'libraries' . DS);
16
-define('EE_CAF_PAYMENT_METHODS', EE_CAFF_PATH . 'payment_methods' . DS);
13
+define('EE_CAF_URL', EE_PLUGIN_DIR_URL.'caffeinated/');
14
+define('EE_CAF_CORE', EE_CAFF_PATH.'core'.DS);
15
+define('EE_CAF_LIBRARIES', EE_CAF_CORE.'libraries'.DS);
16
+define('EE_CAF_PAYMENT_METHODS', EE_CAFF_PATH.'payment_methods'.DS);
17 17
 
18 18
 
19 19
 
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
      */
77 77
     public function caf_helper_paths($paths)
78 78
     {
79
-        $paths[] = EE_CAF_CORE . 'helpers' . DS;
79
+        $paths[] = EE_CAF_CORE.'helpers'.DS;
80 80
         return $paths;
81 81
     }
82 82
 
@@ -98,10 +98,10 @@  discard block
 block discarded – undo
98 98
         global $wpdb;
99 99
         //use same method of getting creator id as the version introducing the change
100 100
         $default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
101
-        $price_type_table = $wpdb->prefix . "esp_price_type";
102
-        $price_table = $wpdb->prefix . "esp_price";
101
+        $price_type_table = $wpdb->prefix."esp_price_type";
102
+        $price_table = $wpdb->prefix."esp_price";
103 103
         if ($this->_get_table_analysis()->tableExists($price_type_table)) {
104
-            $SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
104
+            $SQL = 'SELECT COUNT(PRT_ID) FROM '.$price_type_table.' WHERE PBT_ID=4'; //include trashed price types
105 105
             $tax_price_type_count = $wpdb->get_var($SQL);
106 106
             if ($tax_price_type_count <= 1) {
107 107
                 $wpdb->insert(
@@ -115,11 +115,11 @@  discard block
 block discarded – undo
115 115
                         'PRT_wp_user'    => $default_creator_id,
116 116
                     ),
117 117
                     array(
118
-                        '%s',//PRT_name
119
-                        '%d',//PBT_id
120
-                        '%d',//PRT_is_percent
121
-                        '%d',//PRT_order
122
-                        '%d',//PRT_deleted
118
+                        '%s', //PRT_name
119
+                        '%d', //PBT_id
120
+                        '%d', //PRT_is_percent
121
+                        '%d', //PRT_order
122
+                        '%d', //PRT_deleted
123 123
                         '%d', //PRT_wp_user
124 124
                     )
125 125
                 );
@@ -135,11 +135,11 @@  discard block
 block discarded – undo
135 135
                         'PRT_wp_user'    => $default_creator_id,
136 136
                     ),
137 137
                     array(
138
-                        '%s',//PRT_name
139
-                        '%d',//PBT_id
140
-                        '%d',//PRT_is_percent
141
-                        '%d',//PRT_order
142
-                        '%d',//PRT_deleted
138
+                        '%s', //PRT_name
139
+                        '%d', //PBT_id
140
+                        '%d', //PRT_is_percent
141
+                        '%d', //PRT_order
142
+                        '%d', //PRT_deleted
143 143
                         '%d' //PRT_wp_user
144 144
                     )
145 145
                 );
@@ -159,15 +159,15 @@  discard block
 block discarded – undo
159 159
                             'PRC_wp_user'    => $default_creator_id,
160 160
                         ),
161 161
                         array(
162
-                            '%d',//PRT_id
163
-                            '%f',//PRC_amount
164
-                            '%s',//PRC_name
165
-                            '%s',//PRC_desc
166
-                            '%d',//PRC_is_default
167
-                            '%d',//PRC_overrides
168
-                            '%d',//PRC_deleted
169
-                            '%d',//PRC_order
170
-                            '%d',//PRC_parent
162
+                            '%d', //PRT_id
163
+                            '%f', //PRC_amount
164
+                            '%s', //PRC_name
165
+                            '%s', //PRC_desc
166
+                            '%d', //PRC_is_default
167
+                            '%d', //PRC_overrides
168
+                            '%d', //PRC_deleted
169
+                            '%d', //PRC_order
170
+                            '%d', //PRC_parent
171 171
                             '%d' //PRC_wp_user
172 172
                         )
173 173
                     );
@@ -187,8 +187,8 @@  discard block
 block discarded – undo
187 187
      */
188 188
     public function caffeinated_modules_to_register($modules_to_register = array())
189 189
     {
190
-        if (is_readable(EE_CAFF_PATH . 'modules')) {
191
-            $caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
190
+        if (is_readable(EE_CAFF_PATH.'modules')) {
191
+            $caffeinated_modules_to_register = glob(EE_CAFF_PATH.'modules'.DS.'*', GLOB_ONLYDIR);
192 192
             if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
193 193
                 $modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
194 194
             }
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
      */
269 269
     public function caf_payment_methods($payment_method_paths)
270 270
     {
271
-        $caf_payment_methods_paths = glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
271
+        $caf_payment_methods_paths = glob(EE_CAF_PAYMENT_METHODS.'*', GLOB_ONLYDIR);
272 272
         $payment_method_paths = array_merge($payment_method_paths, $caf_payment_methods_paths);
273 273
         return $payment_method_paths;
274 274
     }
Please login to merge, or discard this patch.
core/EE_System.core.php 1 patch
Indentation   +1423 added lines, -1423 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -16,1428 +16,1428 @@  discard block
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
21
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
22
-     */
23
-    const req_type_normal = 0;
24
-
25
-    /**
26
-     * Indicates this is a brand new installation of EE so we should install
27
-     * tables and default data etc
28
-     */
29
-    const req_type_new_activation = 1;
30
-
31
-    /**
32
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
33
-     * and we just exited maintenance mode). We MUST check the database is setup properly
34
-     * and that default data is setup too
35
-     */
36
-    const req_type_reactivation = 2;
37
-
38
-    /**
39
-     * indicates that EE has been upgraded since its previous request.
40
-     * We may have data migration scripts to call and will want to trigger maintenance mode
41
-     */
42
-    const req_type_upgrade = 3;
43
-
44
-    /**
45
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
46
-     */
47
-    const req_type_downgrade = 4;
48
-
49
-    /**
50
-     * @deprecated since version 4.6.0.dev.006
51
-     * Now whenever a new_activation is detected the request type is still just
52
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
53
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
54
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
55
-     * (Specifically, when the migration manager indicates migrations are finished
56
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
57
-     */
58
-    const req_type_activation_but_not_installed = 5;
59
-
60
-    /**
61
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
62
-     */
63
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
64
-
65
-
66
-    /**
67
-     *    instance of the EE_System object
68
-     *
69
-     * @var    $_instance
70
-     * @access    private
71
-     */
72
-    private static $_instance = null;
73
-
74
-    /**
75
-     * @type  EE_Registry $Registry
76
-     * @access    protected
77
-     */
78
-    protected $registry;
79
-
80
-    /**
81
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
82
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
83
-     *
84
-     * @var int
85
-     */
86
-    private $_req_type;
87
-
88
-    /**
89
-     * Whether or not there was a non-micro version change in EE core version during this request
90
-     *
91
-     * @var boolean
92
-     */
93
-    private $_major_version_change = false;
94
-
95
-
96
-
97
-    /**
98
-     * @singleton method used to instantiate class object
99
-     * @access    public
100
-     * @param  \EE_Registry $Registry
101
-     * @return \EE_System
102
-     */
103
-    public static function instance(EE_Registry $Registry = null)
104
-    {
105
-        // check if class object is instantiated
106
-        if ( ! self::$_instance instanceof EE_System) {
107
-            self::$_instance = new self($Registry);
108
-        }
109
-        return self::$_instance;
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * resets the instance and returns it
116
-     *
117
-     * @return EE_System
118
-     */
119
-    public static function reset()
120
-    {
121
-        self::$_instance->_req_type = null;
122
-        //make sure none of the old hooks are left hanging around
123
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
124
-        //we need to reset the migration manager in order for it to detect DMSs properly
125
-        EE_Data_Migration_Manager::reset();
126
-        self::instance()->detect_activations_or_upgrades();
127
-        self::instance()->perform_activations_upgrades_and_migrations();
128
-        return self::instance();
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     *    sets hooks for running rest of system
135
-     *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
136
-     *    starting EE Addons from any other point may lead to problems
137
-     *
138
-     * @access private
139
-     * @param  \EE_Registry $Registry
140
-     */
141
-    private function __construct(EE_Registry $Registry)
142
-    {
143
-        $this->registry = $Registry;
144
-        do_action('AHEE__EE_System__construct__begin', $this);
145
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
146
-        add_action('AHEE__EE_Bootstrap__load_espresso_addons', array($this, 'load_espresso_addons'));
147
-        // when an ee addon is activated, we want to call the core hook(s) again
148
-        // because the newly-activated addon didn't get a chance to run at all
149
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
150
-        // detect whether install or upgrade
151
-        add_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades', array($this, 'detect_activations_or_upgrades'),
152
-            3);
153
-        // load EE_Config, EE_Textdomain, etc
154
-        add_action('AHEE__EE_Bootstrap__load_core_configuration', array($this, 'load_core_configuration'), 5);
155
-        // load EE_Config, EE_Textdomain, etc
156
-        add_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
157
-            array($this, 'register_shortcodes_modules_and_widgets'), 7);
158
-        // you wanna get going? I wanna get going... let's get going!
159
-        add_action('AHEE__EE_Bootstrap__brew_espresso', array($this, 'brew_espresso'), 9);
160
-        //other housekeeping
161
-        //exclude EE critical pages from wp_list_pages
162
-        add_filter('wp_list_pages_excludes', array($this, 'remove_pages_from_wp_list_pages'), 10);
163
-        // ALL EE Addons should use the following hook point to attach their initial setup too
164
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
165
-        do_action('AHEE__EE_System__construct__complete', $this);
166
-    }
167
-
168
-
169
-
170
-    /**
171
-     * load_espresso_addons
172
-     * allow addons to load first so that they can set hooks for running DMS's, etc
173
-     * this is hooked into both:
174
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
175
-     *        which runs during the WP 'plugins_loaded' action at priority 5
176
-     *    and the WP 'activate_plugin' hookpoint
177
-     *
178
-     * @access public
179
-     * @return void
180
-     */
181
-    public function load_espresso_addons()
182
-    {
183
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
184
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
185
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
186
-        //load and setup EE_Capabilities
187
-        $this->registry->load_core('Capabilities');
188
-        //caps need to be initialized on every request so that capability maps are set.
189
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
190
-        $this->registry->CAP->init_caps();
191
-        do_action('AHEE__EE_System__load_espresso_addons');
192
-        //if the WP API basic auth plugin isn't already loaded, load it now.
193
-        //We want it for mobile apps. Just include the entire plugin
194
-        //also, don't load the basic auth when a plugin is getting activated, because
195
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
196
-        //and causes a fatal error
197
-        if ( ! function_exists('json_basic_auth_handler')
198
-             && ! function_exists('json_basic_auth_error')
199
-             && ! (
200
-                isset($_GET['action'])
201
-                && in_array($_GET['action'], array('activate', 'activate-selected'))
202
-            )
203
-             && ! (
204
-                isset($_GET['activate'])
205
-                && $_GET['activate'] === 'true'
206
-            )
207
-        ) {
208
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
209
-        }
210
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * detect_activations_or_upgrades
217
-     * Checks for activation or upgrade of core first;
218
-     * then also checks if any registered addons have been activated or upgraded
219
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
220
-     * which runs during the WP 'plugins_loaded' action at priority 3
221
-     *
222
-     * @access public
223
-     * @return void
224
-     */
225
-    public function detect_activations_or_upgrades()
226
-    {
227
-        //first off: let's make sure to handle core
228
-        $this->detect_if_activation_or_upgrade();
229
-        foreach ($this->registry->addons as $addon) {
230
-            //detect teh request type for that addon
231
-            $addon->detect_activation_or_upgrade();
232
-        }
233
-    }
234
-
235
-
236
-
237
-    /**
238
-     * detect_if_activation_or_upgrade
239
-     * Takes care of detecting whether this is a brand new install or code upgrade,
240
-     * and either setting up the DB or setting up maintenance mode etc.
241
-     *
242
-     * @access public
243
-     * @return void
244
-     */
245
-    public function detect_if_activation_or_upgrade()
246
-    {
247
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
248
-        // load M-Mode class
249
-        $this->registry->load_core('Maintenance_Mode');
250
-        // check if db has been updated, or if its a brand-new installation
251
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
252
-        $request_type = $this->detect_req_type($espresso_db_update);
253
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
254
-        switch ($request_type) {
255
-            case EE_System::req_type_new_activation:
256
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
257
-                $this->_handle_core_version_change($espresso_db_update);
258
-                break;
259
-            case EE_System::req_type_reactivation:
260
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
261
-                $this->_handle_core_version_change($espresso_db_update);
262
-                break;
263
-            case EE_System::req_type_upgrade:
264
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
265
-                //migrations may be required now that we've upgraded
266
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
267
-                $this->_handle_core_version_change($espresso_db_update);
268
-                //				echo "done upgrade";die;
269
-                break;
270
-            case EE_System::req_type_downgrade:
271
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
272
-                //its possible migrations are no longer required
273
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
274
-                $this->_handle_core_version_change($espresso_db_update);
275
-                break;
276
-            case EE_System::req_type_normal:
277
-            default:
278
-                //				$this->_maybe_redirect_to_ee_about();
279
-                break;
280
-        }
281
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
282
-    }
283
-
284
-
285
-
286
-    /**
287
-     * Updates the list of installed versions and sets hooks for
288
-     * initializing the database later during the request
289
-     *
290
-     * @param array $espresso_db_update
291
-     */
292
-    protected function _handle_core_version_change($espresso_db_update)
293
-    {
294
-        $this->update_list_of_installed_versions($espresso_db_update);
295
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
296
-        add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
297
-            array($this, 'initialize_db_if_no_migrations_required'));
298
-    }
299
-
300
-
301
-
302
-    /**
303
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
304
-     * information about what versions of EE have been installed and activated,
305
-     * NOT necessarily the state of the database
306
-     *
307
-     * @param null $espresso_db_update
308
-     * @internal param array $espresso_db_update_value the value of the WordPress option. If not supplied, fetches it
309
-     *           from the options table
310
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
311
-     */
312
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
313
-    {
314
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
315
-        if ( ! $espresso_db_update) {
316
-            $espresso_db_update = get_option('espresso_db_update');
317
-        }
318
-        // check that option is an array
319
-        if ( ! is_array($espresso_db_update)) {
320
-            // if option is FALSE, then it never existed
321
-            if ($espresso_db_update === false) {
322
-                // make $espresso_db_update an array and save option with autoload OFF
323
-                $espresso_db_update = array();
324
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
325
-            } else {
326
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
327
-                $espresso_db_update = array($espresso_db_update => array());
328
-                update_option('espresso_db_update', $espresso_db_update);
329
-            }
330
-        } else {
331
-            $corrected_db_update = array();
332
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
333
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
334
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
335
-                    //the key is an int, and the value IS NOT an array
336
-                    //so it must be numerically-indexed, where values are versions installed...
337
-                    //fix it!
338
-                    $version_string = $should_be_array;
339
-                    $corrected_db_update[$version_string] = array('unknown-date');
340
-                } else {
341
-                    //ok it checks out
342
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
343
-                }
344
-            }
345
-            $espresso_db_update = $corrected_db_update;
346
-            update_option('espresso_db_update', $espresso_db_update);
347
-        }
348
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
349
-        return $espresso_db_update;
350
-    }
351
-
352
-
353
-
354
-    /**
355
-     * Does the traditional work of setting up the plugin's database and adding default data.
356
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
357
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
358
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
359
-     * so that it will be done when migrations are finished
360
-     *
361
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
362
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
363
-     *                                       This is a resource-intensive job
364
-     *                                       so we prefer to only do it when necessary
365
-     * @return void
366
-     */
367
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
368
-    {
369
-        $request_type = $this->detect_req_type();
370
-        //only initialize system if we're not in maintenance mode.
371
-        if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
372
-            update_option('ee_flush_rewrite_rules', true);
373
-            if ($verify_schema) {
374
-                EEH_Activation::initialize_db_and_folders();
375
-            }
376
-            EEH_Activation::initialize_db_content();
377
-            EEH_Activation::system_initialization();
378
-            if ($initialize_addons_too) {
379
-                $this->initialize_addons();
380
-            }
381
-        } else {
382
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
383
-        }
384
-        if ($request_type === EE_System::req_type_new_activation
385
-            || $request_type === EE_System::req_type_reactivation
386
-            || (
387
-                $request_type === EE_System::req_type_upgrade
388
-                && $this->is_major_version_change()
389
-            )
390
-        ) {
391
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
392
-        }
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     * Initializes the db for all registered addons
399
-     */
400
-    public function initialize_addons()
401
-    {
402
-        //foreach registered addon, make sure its db is up-to-date too
403
-        foreach ($this->registry->addons as $addon) {
404
-            $addon->initialize_db_if_no_migrations_required();
405
-        }
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
412
-     *
413
-     * @param    array  $version_history
414
-     * @param    string $current_version_to_add version to be added to the version history
415
-     * @return    boolean success as to whether or not this option was changed
416
-     */
417
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
418
-    {
419
-        if ( ! $version_history) {
420
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
421
-        }
422
-        if ($current_version_to_add == null) {
423
-            $current_version_to_add = espresso_version();
424
-        }
425
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
426
-        // re-save
427
-        return update_option('espresso_db_update', $version_history);
428
-    }
429
-
430
-
431
-
432
-    /**
433
-     * Detects if the current version indicated in the has existed in the list of
434
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
435
-     *
436
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
437
-     *                                  If not supplied, fetches it from the options table.
438
-     *                                  Also, caches its result so later parts of the code can also know whether
439
-     *                                  there's been an update or not. This way we can add the current version to
440
-     *                                  espresso_db_update, but still know if this is a new install or not
441
-     * @return int one of the constants on EE_System::req_type_
442
-     */
443
-    public function detect_req_type($espresso_db_update = null)
444
-    {
445
-        if ($this->_req_type === null) {
446
-            $espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
447
-                : $this->fix_espresso_db_upgrade_option();
448
-            $this->_req_type = $this->detect_req_type_given_activation_history($espresso_db_update,
449
-                'ee_espresso_activation', espresso_version());
450
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
451
-        }
452
-        return $this->_req_type;
453
-    }
454
-
455
-
456
-
457
-    /**
458
-     * Returns whether or not there was a non-micro version change (ie, change in either
459
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
460
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
461
-     *
462
-     * @param $activation_history
463
-     * @return bool
464
-     */
465
-    protected function _detect_major_version_change($activation_history)
466
-    {
467
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
468
-        $previous_version_parts = explode('.', $previous_version);
469
-        $current_version_parts = explode('.', espresso_version());
470
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
471
-               && ($previous_version_parts[0] !== $current_version_parts[0]
472
-                   || $previous_version_parts[1] !== $current_version_parts[1]
473
-               );
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * Returns true if either the major or minor version of EE changed during this request.
480
-     * 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
481
-     *
482
-     * @return bool
483
-     */
484
-    public function is_major_version_change()
485
-    {
486
-        return $this->_major_version_change;
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
493
-     * histories (for core that' 'espresso_db_update' wp option); the name of the wordpress option which is temporarily
494
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
495
-     * just activated to (for core that will always be espresso_version())
496
-     *
497
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
498
-     *                                                 ee plugin. for core that's 'espresso_db_update'
499
-     * @param string $activation_indicator_option_name the name of the wordpress option that is temporarily set to
500
-     *                                                 indicate that this plugin was just activated
501
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
502
-     *                                                 espresso_version())
503
-     * @return int one of the constants on EE_System::req_type_*
504
-     */
505
-    public static function detect_req_type_given_activation_history(
506
-        $activation_history_for_addon,
507
-        $activation_indicator_option_name,
508
-        $version_to_upgrade_to
509
-    ) {
510
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
511
-        if ($activation_history_for_addon) {
512
-            //it exists, so this isn't a completely new install
513
-            //check if this version already in that list of previously installed versions
514
-            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
515
-                //it a version we haven't seen before
516
-                if ($version_is_higher === 1) {
517
-                    $req_type = EE_System::req_type_upgrade;
518
-                } else {
519
-                    $req_type = EE_System::req_type_downgrade;
520
-                }
521
-                delete_option($activation_indicator_option_name);
522
-            } else {
523
-                // its not an update. maybe a reactivation?
524
-                if (get_option($activation_indicator_option_name, false)) {
525
-                    if ($version_is_higher === -1) {
526
-                        $req_type = EE_System::req_type_downgrade;
527
-                    } elseif ($version_is_higher === 0) {
528
-                        //we've seen this version before, but it's an activation. must be a reactivation
529
-                        $req_type = EE_System::req_type_reactivation;
530
-                    } else {//$version_is_higher === 1
531
-                        $req_type = EE_System::req_type_upgrade;
532
-                    }
533
-                    delete_option($activation_indicator_option_name);
534
-                } else {
535
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
536
-                    if ($version_is_higher === -1) {
537
-                        $req_type = EE_System::req_type_downgrade;
538
-                    } elseif ($version_is_higher === 0) {
539
-                        //we've seen this version before and it's not an activation. its normal request
540
-                        $req_type = EE_System::req_type_normal;
541
-                    } else {//$version_is_higher === 1
542
-                        $req_type = EE_System::req_type_upgrade;
543
-                    }
544
-                }
545
-            }
546
-        } else {
547
-            //brand new install
548
-            $req_type = EE_System::req_type_new_activation;
549
-            delete_option($activation_indicator_option_name);
550
-        }
551
-        return $req_type;
552
-    }
553
-
554
-
555
-
556
-    /**
557
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
558
-     * the $activation_history_for_addon
559
-     *
560
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
561
-     *                                             sometimes containing 'unknown-date'
562
-     * @param string $version_to_upgrade_to        (current version)
563
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
564
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
565
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
566
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
567
-     */
568
-    protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
569
-    {
570
-        //find the most recently-activated version
571
-        $most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
572
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     * Gets the most recently active version listed in the activation history,
579
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
580
-     *
581
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
582
-     *                                   sometimes containing 'unknown-date'
583
-     * @return string
584
-     */
585
-    protected static function _get_most_recently_active_version_from_activation_history($activation_history)
586
-    {
587
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
588
-        $most_recently_active_version = '0.0.0.dev.000';
589
-        if (is_array($activation_history)) {
590
-            foreach ($activation_history as $version => $times_activated) {
591
-                //check there is a record of when this version was activated. Otherwise,
592
-                //mark it as unknown
593
-                if ( ! $times_activated) {
594
-                    $times_activated = array('unknown-date');
595
-                }
596
-                if (is_string($times_activated)) {
597
-                    $times_activated = array($times_activated);
598
-                }
599
-                foreach ($times_activated as $an_activation) {
600
-                    if ($an_activation != 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
601
-                        $most_recently_active_version = $version;
602
-                        $most_recently_active_version_activation = $an_activation == 'unknown-date'
603
-                            ? '1970-01-01 00:00:00' : $an_activation;
604
-                    }
605
-                }
606
-            }
607
-        }
608
-        return $most_recently_active_version;
609
-    }
610
-
611
-
612
-
613
-    /**
614
-     * This redirects to the about EE page after activation
615
-     *
616
-     * @return void
617
-     */
618
-    public function redirect_to_about_ee()
619
-    {
620
-        $notices = EE_Error::get_notices(false);
621
-        //if current user is an admin and it's not an ajax or rest request
622
-        if (
623
-            ! (defined('DOING_AJAX') && DOING_AJAX)
624
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
625
-            && ! isset($notices['errors'])
626
-            && apply_filters(
627
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
628
-                $this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
629
-            )
630
-        ) {
631
-            $query_params = array('page' => 'espresso_about');
632
-            if (EE_System::instance()->detect_req_type() == EE_System::req_type_new_activation) {
633
-                $query_params['new_activation'] = true;
634
-            }
635
-            if (EE_System::instance()->detect_req_type() == EE_System::req_type_reactivation) {
636
-                $query_params['reactivation'] = true;
637
-            }
638
-            $url = add_query_arg($query_params, admin_url('admin.php'));
639
-            wp_safe_redirect($url);
640
-            exit();
641
-        }
642
-    }
643
-
644
-
645
-
646
-    /**
647
-     * load_core_configuration
648
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
649
-     * which runs during the WP 'plugins_loaded' action at priority 5
650
-     *
651
-     * @return void
652
-     */
653
-    public function load_core_configuration()
654
-    {
655
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
656
-        $this->registry->load_core('EE_Load_Textdomain');
657
-        //load textdomain
658
-        EE_Load_Textdomain::load_textdomain();
659
-        // load and setup EE_Config and EE_Network_Config
660
-        $this->registry->load_core('Config');
661
-        $this->registry->load_core('Network_Config');
662
-        // setup autoloaders
663
-        // enable logging?
664
-        if ($this->registry->CFG->admin->use_full_logging) {
665
-            $this->registry->load_core('Log');
666
-        }
667
-        // check for activation errors
668
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
669
-        if ($activation_errors) {
670
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
671
-            update_option('ee_plugin_activation_errors', false);
672
-        }
673
-        // get model names
674
-        $this->_parse_model_names();
675
-        //load caf stuff a chance to play during the activation process too.
676
-        $this->_maybe_brew_regular();
677
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
678
-    }
679
-
680
-
681
-
682
-    /**
683
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
684
-     *
685
-     * @return void
686
-     */
687
-    private function _parse_model_names()
688
-    {
689
-        //get all the files in the EE_MODELS folder that end in .model.php
690
-        $models = glob(EE_MODELS . '*.model.php');
691
-        $model_names = array();
692
-        $non_abstract_db_models = array();
693
-        foreach ($models as $model) {
694
-            // get model classname
695
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
696
-            $short_name = str_replace('EEM_', '', $classname);
697
-            $reflectionClass = new ReflectionClass($classname);
698
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
699
-                $non_abstract_db_models[$short_name] = $classname;
700
-            }
701
-            $model_names[$short_name] = $classname;
702
-        }
703
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
704
-        $this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
705
-            $non_abstract_db_models);
706
-    }
707
-
708
-
709
-
710
-    /**
711
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
712
-     * that need to be setup before our EE_System launches.
713
-     *
714
-     * @return void
715
-     */
716
-    private function _maybe_brew_regular()
717
-    {
718
-        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
719
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
720
-        }
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * register_shortcodes_modules_and_widgets
727
-     * generate lists of shortcodes and modules, then verify paths and classes
728
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
729
-     * which runs during the WP 'plugins_loaded' action at priority 7
730
-     *
731
-     * @access public
732
-     * @return void
733
-     */
734
-    public function register_shortcodes_modules_and_widgets()
735
-    {
736
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
737
-        // check for addons using old hookpoint
738
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
739
-            $this->_incompatible_addon_error();
740
-        }
741
-    }
742
-
743
-
744
-
745
-    /**
746
-     * _incompatible_addon_error
747
-     *
748
-     * @access public
749
-     * @return void
750
-     */
751
-    private function _incompatible_addon_error()
752
-    {
753
-        // get array of classes hooking into here
754
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
755
-        if ( ! empty($class_names)) {
756
-            $msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
757
-                'event_espresso');
758
-            $msg .= '<ul>';
759
-            foreach ($class_names as $class_name) {
760
-                $msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
761
-                        $class_name) . '</b></li>';
762
-            }
763
-            $msg .= '</ul>';
764
-            $msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
765
-                'event_espresso');
766
-            // save list of incompatible addons to wp-options for later use
767
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
768
-            if (is_admin()) {
769
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
770
-            }
771
-        }
772
-    }
773
-
774
-
775
-
776
-    /**
777
-     * brew_espresso
778
-     * begins the process of setting hooks for initializing EE in the correct order
779
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hookpoint
780
-     * which runs during the WP 'plugins_loaded' action at priority 9
781
-     *
782
-     * @return void
783
-     */
784
-    public function brew_espresso()
785
-    {
786
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
787
-        // load some final core systems
788
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
789
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
790
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
791
-        add_action('init', array($this, 'load_controllers'), 7);
792
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
793
-        add_action('init', array($this, 'initialize'), 10);
794
-        add_action('init', array($this, 'initialize_last'), 100);
795
-        add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 25);
796
-        add_action('admin_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 25);
797
-        add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
798
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
799
-            // pew pew pew
800
-            $this->registry->load_core('PUE');
801
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
802
-        }
803
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
804
-    }
805
-
806
-
807
-
808
-    /**
809
-     *    set_hooks_for_core
810
-     *
811
-     * @access public
812
-     * @return    void
813
-     */
814
-    public function set_hooks_for_core()
815
-    {
816
-        $this->_deactivate_incompatible_addons();
817
-        do_action('AHEE__EE_System__set_hooks_for_core');
818
-    }
819
-
820
-
821
-
822
-    /**
823
-     * Using the information gathered in EE_System::_incompatible_addon_error,
824
-     * deactivates any addons considered incompatible with the current version of EE
825
-     */
826
-    private function _deactivate_incompatible_addons()
827
-    {
828
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
829
-        if ( ! empty($incompatible_addons)) {
830
-            $active_plugins = get_option('active_plugins', array());
831
-            foreach ($active_plugins as $active_plugin) {
832
-                foreach ($incompatible_addons as $incompatible_addon) {
833
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
834
-                        unset($_GET['activate']);
835
-                        espresso_deactivate_plugin($active_plugin);
836
-                    }
837
-                }
838
-            }
839
-        }
840
-    }
841
-
842
-
843
-
844
-    /**
845
-     *    perform_activations_upgrades_and_migrations
846
-     *
847
-     * @access public
848
-     * @return    void
849
-     */
850
-    public function perform_activations_upgrades_and_migrations()
851
-    {
852
-        //first check if we had previously attempted to setup EE's directories but failed
853
-        if (EEH_Activation::upload_directories_incomplete()) {
854
-            EEH_Activation::create_upload_directories();
855
-        }
856
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
857
-    }
858
-
859
-
860
-
861
-    /**
862
-     *    load_CPTs_and_session
863
-     *
864
-     * @access public
865
-     * @return    void
866
-     */
867
-    public function load_CPTs_and_session()
868
-    {
869
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
870
-        // register Custom Post Types
871
-        $this->registry->load_core('Register_CPTs');
872
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
873
-    }
874
-
875
-
876
-
877
-    /**
878
-     * load_controllers
879
-     * this is the best place to load any additional controllers that needs access to EE core.
880
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
881
-     * time
882
-     *
883
-     * @access public
884
-     * @return void
885
-     */
886
-    public function load_controllers()
887
-    {
888
-        do_action('AHEE__EE_System__load_controllers__start');
889
-        // let's get it started
890
-        if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
891
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
892
-            $this->registry->load_core('Front_Controller', array(), false, true);
893
-        } else if ( ! EE_FRONT_AJAX) {
894
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
895
-            EE_Registry::instance()->load_core('Admin');
896
-        }
897
-        do_action('AHEE__EE_System__load_controllers__complete');
898
-    }
899
-
900
-
901
-
902
-    /**
903
-     * core_loaded_and_ready
904
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
905
-     *
906
-     * @access public
907
-     * @return void
908
-     */
909
-    public function core_loaded_and_ready()
910
-    {
911
-        do_action('AHEE__EE_System__core_loaded_and_ready');
912
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
913
-        $this->registry->load_core('Session');
914
-        //		add_action( 'wp_loaded', array( $this, 'set_hooks_for_shortcodes_modules_and_addons' ), 1 );
915
-    }
916
-
917
-
918
-
919
-    /**
920
-     * initialize
921
-     * this is the best place to begin initializing client code
922
-     *
923
-     * @access public
924
-     * @return void
925
-     */
926
-    public function initialize()
927
-    {
928
-        do_action('AHEE__EE_System__initialize');
929
-    }
930
-
931
-
932
-
933
-    /**
934
-     * initialize_last
935
-     * this is run really late during the WP init hookpoint, and ensures that mostly everything else that needs to
936
-     * initialize has done so
937
-     *
938
-     * @access public
939
-     * @return void
940
-     */
941
-    public function initialize_last()
942
-    {
943
-        do_action('AHEE__EE_System__initialize_last');
944
-    }
945
-
946
-
947
-
948
-    /**
949
-     * set_hooks_for_shortcodes_modules_and_addons
950
-     * this is the best place for other systems to set callbacks for hooking into other parts of EE
951
-     * this happens at the very beginning of the wp_loaded hookpoint
952
-     *
953
-     * @access public
954
-     * @return void
955
-     */
956
-    public function set_hooks_for_shortcodes_modules_and_addons()
957
-    {
958
-        //		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
959
-    }
960
-
961
-
962
-
963
-    /**
964
-     * do_not_cache
965
-     * sets no cache headers and defines no cache constants for WP plugins
966
-     *
967
-     * @access public
968
-     * @return void
969
-     */
970
-    public static function do_not_cache()
971
-    {
972
-        // set no cache constants
973
-        if ( ! defined('DONOTCACHEPAGE')) {
974
-            define('DONOTCACHEPAGE', true);
975
-        }
976
-        if ( ! defined('DONOTCACHCEOBJECT')) {
977
-            define('DONOTCACHCEOBJECT', true);
978
-        }
979
-        if ( ! defined('DONOTCACHEDB')) {
980
-            define('DONOTCACHEDB', true);
981
-        }
982
-        // add no cache headers
983
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
984
-        // plus a little extra for nginx and Google Chrome
985
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
986
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
987
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
988
-    }
989
-
990
-
991
-
992
-    /**
993
-     *    extra_nocache_headers
994
-     *
995
-     * @access    public
996
-     * @param $headers
997
-     * @return    array
998
-     */
999
-    public static function extra_nocache_headers($headers)
1000
-    {
1001
-        // for NGINX
1002
-        $headers['X-Accel-Expires'] = 0;
1003
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1004
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1005
-        return $headers;
1006
-    }
1007
-
1008
-
1009
-
1010
-    /**
1011
-     *    nocache_headers
1012
-     *
1013
-     * @access    public
1014
-     * @return    void
1015
-     */
1016
-    public static function nocache_headers()
1017
-    {
1018
-        nocache_headers();
1019
-    }
1020
-
1021
-
1022
-
1023
-    /**
1024
-     *    espresso_toolbar_items
1025
-     *
1026
-     * @access public
1027
-     * @param  WP_Admin_Bar $admin_bar
1028
-     * @return void
1029
-     */
1030
-    public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1031
-    {
1032
-        // if in full M-Mode, or its an AJAX request, or user is NOT an admin
1033
-        if (EE_Maintenance_Mode::instance()->level() == EE_Maintenance_Mode::level_2_complete_maintenance
1034
-            || defined('DOING_AJAX')
1035
-            || ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1036
-        ) {
1037
-            return;
1038
-        }
1039
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1040
-        $menu_class = 'espresso_menu_item_class';
1041
-        //we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1042
-        //because they're only defined in each of their respective constructors
1043
-        //and this might be a frontend request, in which case they aren't available
1044
-        $events_admin_url = admin_url("admin.php?page=espresso_events");
1045
-        $reg_admin_url = admin_url("admin.php?page=espresso_registrations");
1046
-        $extensions_admin_url = admin_url("admin.php?page=espresso_packages");
1047
-        //Top Level
1048
-        $admin_bar->add_menu(array(
1049
-            'id'    => 'espresso-toolbar',
1050
-            'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1051
-                       . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1052
-                       . '</span>',
1053
-            'href'  => $events_admin_url,
1054
-            'meta'  => array(
1055
-                'title' => __('Event Espresso', 'event_espresso'),
1056
-                'class' => $menu_class . 'first',
1057
-            ),
1058
-        ));
1059
-        //Events
1060
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1061
-            $admin_bar->add_menu(array(
1062
-                'id'     => 'espresso-toolbar-events',
1063
-                'parent' => 'espresso-toolbar',
1064
-                'title'  => __('Events', 'event_espresso'),
1065
-                'href'   => $events_admin_url,
1066
-                'meta'   => array(
1067
-                    'title'  => __('Events', 'event_espresso'),
1068
-                    'target' => '',
1069
-                    'class'  => $menu_class,
1070
-                ),
1071
-            ));
1072
-        }
1073
-        if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1074
-            //Events Add New
1075
-            $admin_bar->add_menu(array(
1076
-                'id'     => 'espresso-toolbar-events-new',
1077
-                'parent' => 'espresso-toolbar-events',
1078
-                'title'  => __('Add New', 'event_espresso'),
1079
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1080
-                'meta'   => array(
1081
-                    'title'  => __('Add New', 'event_espresso'),
1082
-                    'target' => '',
1083
-                    'class'  => $menu_class,
1084
-                ),
1085
-            ));
1086
-        }
1087
-        if (is_single() && (get_post_type() == 'espresso_events')) {
1088
-            //Current post
1089
-            global $post;
1090
-            if ($this->registry->CAP->current_user_can('ee_edit_event',
1091
-                'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1092
-            ) {
1093
-                //Events Edit Current Event
1094
-                $admin_bar->add_menu(array(
1095
-                    'id'     => 'espresso-toolbar-events-edit',
1096
-                    'parent' => 'espresso-toolbar-events',
1097
-                    'title'  => __('Edit Event', 'event_espresso'),
1098
-                    'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1099
-                        $events_admin_url),
1100
-                    'meta'   => array(
1101
-                        'title'  => __('Edit Event', 'event_espresso'),
1102
-                        'target' => '',
1103
-                        'class'  => $menu_class,
1104
-                    ),
1105
-                ));
1106
-            }
1107
-        }
1108
-        //Events View
1109
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1110
-            'ee_admin_bar_menu_espresso-toolbar-events-view')
1111
-        ) {
1112
-            $admin_bar->add_menu(array(
1113
-                'id'     => 'espresso-toolbar-events-view',
1114
-                'parent' => 'espresso-toolbar-events',
1115
-                'title'  => __('View', 'event_espresso'),
1116
-                'href'   => $events_admin_url,
1117
-                'meta'   => array(
1118
-                    'title'  => __('View', 'event_espresso'),
1119
-                    'target' => '',
1120
-                    'class'  => $menu_class,
1121
-                ),
1122
-            ));
1123
-        }
1124
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1125
-            //Events View All
1126
-            $admin_bar->add_menu(array(
1127
-                'id'     => 'espresso-toolbar-events-all',
1128
-                'parent' => 'espresso-toolbar-events-view',
1129
-                'title'  => __('All', 'event_espresso'),
1130
-                'href'   => $events_admin_url,
1131
-                'meta'   => array(
1132
-                    'title'  => __('All', 'event_espresso'),
1133
-                    'target' => '',
1134
-                    'class'  => $menu_class,
1135
-                ),
1136
-            ));
1137
-        }
1138
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1139
-            'ee_admin_bar_menu_espresso-toolbar-events-today')
1140
-        ) {
1141
-            //Events View Today
1142
-            $admin_bar->add_menu(array(
1143
-                'id'     => 'espresso-toolbar-events-today',
1144
-                'parent' => 'espresso-toolbar-events-view',
1145
-                'title'  => __('Today', 'event_espresso'),
1146
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1147
-                    $events_admin_url),
1148
-                'meta'   => array(
1149
-                    'title'  => __('Today', 'event_espresso'),
1150
-                    'target' => '',
1151
-                    'class'  => $menu_class,
1152
-                ),
1153
-            ));
1154
-        }
1155
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1156
-            'ee_admin_bar_menu_espresso-toolbar-events-month')
1157
-        ) {
1158
-            //Events View This Month
1159
-            $admin_bar->add_menu(array(
1160
-                'id'     => 'espresso-toolbar-events-month',
1161
-                'parent' => 'espresso-toolbar-events-view',
1162
-                'title'  => __('This Month', 'event_espresso'),
1163
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1164
-                    $events_admin_url),
1165
-                'meta'   => array(
1166
-                    'title'  => __('This Month', 'event_espresso'),
1167
-                    'target' => '',
1168
-                    'class'  => $menu_class,
1169
-                ),
1170
-            ));
1171
-        }
1172
-        //Registration Overview
1173
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1174
-            'ee_admin_bar_menu_espresso-toolbar-registrations')
1175
-        ) {
1176
-            $admin_bar->add_menu(array(
1177
-                'id'     => 'espresso-toolbar-registrations',
1178
-                'parent' => 'espresso-toolbar',
1179
-                'title'  => __('Registrations', 'event_espresso'),
1180
-                'href'   => $reg_admin_url,
1181
-                'meta'   => array(
1182
-                    'title'  => __('Registrations', 'event_espresso'),
1183
-                    'target' => '',
1184
-                    'class'  => $menu_class,
1185
-                ),
1186
-            ));
1187
-        }
1188
-        //Registration Overview Today
1189
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1190
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1191
-        ) {
1192
-            $admin_bar->add_menu(array(
1193
-                'id'     => 'espresso-toolbar-registrations-today',
1194
-                'parent' => 'espresso-toolbar-registrations',
1195
-                'title'  => __('Today', 'event_espresso'),
1196
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1197
-                    $reg_admin_url),
1198
-                'meta'   => array(
1199
-                    'title'  => __('Today', 'event_espresso'),
1200
-                    'target' => '',
1201
-                    'class'  => $menu_class,
1202
-                ),
1203
-            ));
1204
-        }
1205
-        //Registration Overview Today Completed
1206
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1207
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1208
-        ) {
1209
-            $admin_bar->add_menu(array(
1210
-                'id'     => 'espresso-toolbar-registrations-today-approved',
1211
-                'parent' => 'espresso-toolbar-registrations-today',
1212
-                'title'  => __('Approved', 'event_espresso'),
1213
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1214
-                    'action'      => 'default',
1215
-                    'status'      => 'today',
1216
-                    '_reg_status' => EEM_Registration::status_id_approved,
1217
-                ), $reg_admin_url),
1218
-                'meta'   => array(
1219
-                    'title'  => __('Approved', 'event_espresso'),
1220
-                    'target' => '',
1221
-                    'class'  => $menu_class,
1222
-                ),
1223
-            ));
1224
-        }
1225
-        //Registration Overview Today Pending\
1226
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1227
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1228
-        ) {
1229
-            $admin_bar->add_menu(array(
1230
-                'id'     => 'espresso-toolbar-registrations-today-pending',
1231
-                'parent' => 'espresso-toolbar-registrations-today',
1232
-                'title'  => __('Pending', 'event_espresso'),
1233
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1234
-                    'action'     => 'default',
1235
-                    'status'     => 'today',
1236
-                    'reg_status' => EEM_Registration::status_id_pending_payment,
1237
-                ), $reg_admin_url),
1238
-                'meta'   => array(
1239
-                    'title'  => __('Pending Payment', 'event_espresso'),
1240
-                    'target' => '',
1241
-                    'class'  => $menu_class,
1242
-                ),
1243
-            ));
1244
-        }
1245
-        //Registration Overview Today Incomplete
1246
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1247
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1248
-        ) {
1249
-            $admin_bar->add_menu(array(
1250
-                'id'     => 'espresso-toolbar-registrations-today-not-approved',
1251
-                'parent' => 'espresso-toolbar-registrations-today',
1252
-                'title'  => __('Not Approved', 'event_espresso'),
1253
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1254
-                    'action'      => 'default',
1255
-                    'status'      => 'today',
1256
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1257
-                ), $reg_admin_url),
1258
-                'meta'   => array(
1259
-                    'title'  => __('Not Approved', 'event_espresso'),
1260
-                    'target' => '',
1261
-                    'class'  => $menu_class,
1262
-                ),
1263
-            ));
1264
-        }
1265
-        //Registration Overview Today Incomplete
1266
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1267
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1268
-        ) {
1269
-            $admin_bar->add_menu(array(
1270
-                'id'     => 'espresso-toolbar-registrations-today-cancelled',
1271
-                'parent' => 'espresso-toolbar-registrations-today',
1272
-                'title'  => __('Cancelled', 'event_espresso'),
1273
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1274
-                    'action'      => 'default',
1275
-                    'status'      => 'today',
1276
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1277
-                ), $reg_admin_url),
1278
-                'meta'   => array(
1279
-                    'title'  => __('Cancelled', 'event_espresso'),
1280
-                    'target' => '',
1281
-                    'class'  => $menu_class,
1282
-                ),
1283
-            ));
1284
-        }
1285
-        //Registration Overview This Month
1286
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1287
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1288
-        ) {
1289
-            $admin_bar->add_menu(array(
1290
-                'id'     => 'espresso-toolbar-registrations-month',
1291
-                'parent' => 'espresso-toolbar-registrations',
1292
-                'title'  => __('This Month', 'event_espresso'),
1293
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1294
-                    $reg_admin_url),
1295
-                'meta'   => array(
1296
-                    'title'  => __('This Month', 'event_espresso'),
1297
-                    'target' => '',
1298
-                    'class'  => $menu_class,
1299
-                ),
1300
-            ));
1301
-        }
1302
-        //Registration Overview This Month Approved
1303
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1304
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1305
-        ) {
1306
-            $admin_bar->add_menu(array(
1307
-                'id'     => 'espresso-toolbar-registrations-month-approved',
1308
-                'parent' => 'espresso-toolbar-registrations-month',
1309
-                'title'  => __('Approved', 'event_espresso'),
1310
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1311
-                    'action'      => 'default',
1312
-                    'status'      => 'month',
1313
-                    '_reg_status' => EEM_Registration::status_id_approved,
1314
-                ), $reg_admin_url),
1315
-                'meta'   => array(
1316
-                    'title'  => __('Approved', 'event_espresso'),
1317
-                    'target' => '',
1318
-                    'class'  => $menu_class,
1319
-                ),
1320
-            ));
1321
-        }
1322
-        //Registration Overview This Month Pending
1323
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1324
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1325
-        ) {
1326
-            $admin_bar->add_menu(array(
1327
-                'id'     => 'espresso-toolbar-registrations-month-pending',
1328
-                'parent' => 'espresso-toolbar-registrations-month',
1329
-                'title'  => __('Pending', 'event_espresso'),
1330
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1331
-                    'action'      => 'default',
1332
-                    'status'      => 'month',
1333
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1334
-                ), $reg_admin_url),
1335
-                'meta'   => array(
1336
-                    'title'  => __('Pending', 'event_espresso'),
1337
-                    'target' => '',
1338
-                    'class'  => $menu_class,
1339
-                ),
1340
-            ));
1341
-        }
1342
-        //Registration Overview This Month Not Approved
1343
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1344
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1345
-        ) {
1346
-            $admin_bar->add_menu(array(
1347
-                'id'     => 'espresso-toolbar-registrations-month-not-approved',
1348
-                'parent' => 'espresso-toolbar-registrations-month',
1349
-                'title'  => __('Not Approved', 'event_espresso'),
1350
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1351
-                    'action'      => 'default',
1352
-                    'status'      => 'month',
1353
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1354
-                ), $reg_admin_url),
1355
-                'meta'   => array(
1356
-                    'title'  => __('Not Approved', 'event_espresso'),
1357
-                    'target' => '',
1358
-                    'class'  => $menu_class,
1359
-                ),
1360
-            ));
1361
-        }
1362
-        //Registration Overview This Month Cancelled
1363
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1364
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1365
-        ) {
1366
-            $admin_bar->add_menu(array(
1367
-                'id'     => 'espresso-toolbar-registrations-month-cancelled',
1368
-                'parent' => 'espresso-toolbar-registrations-month',
1369
-                'title'  => __('Cancelled', 'event_espresso'),
1370
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1371
-                    'action'      => 'default',
1372
-                    'status'      => 'month',
1373
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1374
-                ), $reg_admin_url),
1375
-                'meta'   => array(
1376
-                    'title'  => __('Cancelled', 'event_espresso'),
1377
-                    'target' => '',
1378
-                    'class'  => $menu_class,
1379
-                ),
1380
-            ));
1381
-        }
1382
-        //Extensions & Services
1383
-        if ($this->registry->CAP->current_user_can('ee_read_ee',
1384
-            'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1385
-        ) {
1386
-            $admin_bar->add_menu(array(
1387
-                'id'     => 'espresso-toolbar-extensions-and-services',
1388
-                'parent' => 'espresso-toolbar',
1389
-                'title'  => __('Extensions & Services', 'event_espresso'),
1390
-                'href'   => $extensions_admin_url,
1391
-                'meta'   => array(
1392
-                    'title'  => __('Extensions & Services', 'event_espresso'),
1393
-                    'target' => '',
1394
-                    'class'  => $menu_class,
1395
-                ),
1396
-            ));
1397
-        }
1398
-    }
1399
-
1400
-
1401
-
1402
-    /**
1403
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1404
-     * never returned with the function.
1405
-     *
1406
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1407
-     * @return array
1408
-     */
1409
-    public function remove_pages_from_wp_list_pages($exclude_array)
1410
-    {
1411
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1412
-    }
1413
-
1414
-
1415
-
1416
-
1417
-
1418
-
1419
-    /***********************************************        WP_ENQUEUE_SCRIPTS HOOK         ***********************************************/
1420
-    /**
1421
-     *    wp_enqueue_scripts
1422
-     *
1423
-     * @access    public
1424
-     * @return    void
1425
-     */
1426
-    public function wp_enqueue_scripts()
1427
-    {
1428
-        // unlike other systems, EE_System_scripts loading is turned ON by default, but prior to the init hook, can be turned off via: add_filter( 'FHEE_load_EE_System_scripts', '__return_false' );
1429
-        if (apply_filters('FHEE_load_EE_System_scripts', true)) {
1430
-            // jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1431
-            if (apply_filters('FHEE_load_jquery_validate', false)) {
1432
-                // register jQuery Validate and additional methods
1433
-                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1434
-                    array('jquery'), '1.15.0', true);
1435
-                wp_register_script('jquery-validate-extra-methods',
1436
-                    EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1437
-                    array('jquery', 'jquery-validate'), '1.15.0', true);
1438
-            }
1439
-        }
1440
-    }
19
+	/**
20
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
21
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
22
+	 */
23
+	const req_type_normal = 0;
24
+
25
+	/**
26
+	 * Indicates this is a brand new installation of EE so we should install
27
+	 * tables and default data etc
28
+	 */
29
+	const req_type_new_activation = 1;
30
+
31
+	/**
32
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
33
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
34
+	 * and that default data is setup too
35
+	 */
36
+	const req_type_reactivation = 2;
37
+
38
+	/**
39
+	 * indicates that EE has been upgraded since its previous request.
40
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
41
+	 */
42
+	const req_type_upgrade = 3;
43
+
44
+	/**
45
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
46
+	 */
47
+	const req_type_downgrade = 4;
48
+
49
+	/**
50
+	 * @deprecated since version 4.6.0.dev.006
51
+	 * Now whenever a new_activation is detected the request type is still just
52
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
53
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
54
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
55
+	 * (Specifically, when the migration manager indicates migrations are finished
56
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
57
+	 */
58
+	const req_type_activation_but_not_installed = 5;
59
+
60
+	/**
61
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
62
+	 */
63
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
64
+
65
+
66
+	/**
67
+	 *    instance of the EE_System object
68
+	 *
69
+	 * @var    $_instance
70
+	 * @access    private
71
+	 */
72
+	private static $_instance = null;
73
+
74
+	/**
75
+	 * @type  EE_Registry $Registry
76
+	 * @access    protected
77
+	 */
78
+	protected $registry;
79
+
80
+	/**
81
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
82
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
83
+	 *
84
+	 * @var int
85
+	 */
86
+	private $_req_type;
87
+
88
+	/**
89
+	 * Whether or not there was a non-micro version change in EE core version during this request
90
+	 *
91
+	 * @var boolean
92
+	 */
93
+	private $_major_version_change = false;
94
+
95
+
96
+
97
+	/**
98
+	 * @singleton method used to instantiate class object
99
+	 * @access    public
100
+	 * @param  \EE_Registry $Registry
101
+	 * @return \EE_System
102
+	 */
103
+	public static function instance(EE_Registry $Registry = null)
104
+	{
105
+		// check if class object is instantiated
106
+		if ( ! self::$_instance instanceof EE_System) {
107
+			self::$_instance = new self($Registry);
108
+		}
109
+		return self::$_instance;
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * resets the instance and returns it
116
+	 *
117
+	 * @return EE_System
118
+	 */
119
+	public static function reset()
120
+	{
121
+		self::$_instance->_req_type = null;
122
+		//make sure none of the old hooks are left hanging around
123
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
124
+		//we need to reset the migration manager in order for it to detect DMSs properly
125
+		EE_Data_Migration_Manager::reset();
126
+		self::instance()->detect_activations_or_upgrades();
127
+		self::instance()->perform_activations_upgrades_and_migrations();
128
+		return self::instance();
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 *    sets hooks for running rest of system
135
+	 *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
136
+	 *    starting EE Addons from any other point may lead to problems
137
+	 *
138
+	 * @access private
139
+	 * @param  \EE_Registry $Registry
140
+	 */
141
+	private function __construct(EE_Registry $Registry)
142
+	{
143
+		$this->registry = $Registry;
144
+		do_action('AHEE__EE_System__construct__begin', $this);
145
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
146
+		add_action('AHEE__EE_Bootstrap__load_espresso_addons', array($this, 'load_espresso_addons'));
147
+		// when an ee addon is activated, we want to call the core hook(s) again
148
+		// because the newly-activated addon didn't get a chance to run at all
149
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
150
+		// detect whether install or upgrade
151
+		add_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades', array($this, 'detect_activations_or_upgrades'),
152
+			3);
153
+		// load EE_Config, EE_Textdomain, etc
154
+		add_action('AHEE__EE_Bootstrap__load_core_configuration', array($this, 'load_core_configuration'), 5);
155
+		// load EE_Config, EE_Textdomain, etc
156
+		add_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
157
+			array($this, 'register_shortcodes_modules_and_widgets'), 7);
158
+		// you wanna get going? I wanna get going... let's get going!
159
+		add_action('AHEE__EE_Bootstrap__brew_espresso', array($this, 'brew_espresso'), 9);
160
+		//other housekeeping
161
+		//exclude EE critical pages from wp_list_pages
162
+		add_filter('wp_list_pages_excludes', array($this, 'remove_pages_from_wp_list_pages'), 10);
163
+		// ALL EE Addons should use the following hook point to attach their initial setup too
164
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
165
+		do_action('AHEE__EE_System__construct__complete', $this);
166
+	}
167
+
168
+
169
+
170
+	/**
171
+	 * load_espresso_addons
172
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
173
+	 * this is hooked into both:
174
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
175
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
176
+	 *    and the WP 'activate_plugin' hookpoint
177
+	 *
178
+	 * @access public
179
+	 * @return void
180
+	 */
181
+	public function load_espresso_addons()
182
+	{
183
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
184
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
185
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
186
+		//load and setup EE_Capabilities
187
+		$this->registry->load_core('Capabilities');
188
+		//caps need to be initialized on every request so that capability maps are set.
189
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
190
+		$this->registry->CAP->init_caps();
191
+		do_action('AHEE__EE_System__load_espresso_addons');
192
+		//if the WP API basic auth plugin isn't already loaded, load it now.
193
+		//We want it for mobile apps. Just include the entire plugin
194
+		//also, don't load the basic auth when a plugin is getting activated, because
195
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
196
+		//and causes a fatal error
197
+		if ( ! function_exists('json_basic_auth_handler')
198
+			 && ! function_exists('json_basic_auth_error')
199
+			 && ! (
200
+				isset($_GET['action'])
201
+				&& in_array($_GET['action'], array('activate', 'activate-selected'))
202
+			)
203
+			 && ! (
204
+				isset($_GET['activate'])
205
+				&& $_GET['activate'] === 'true'
206
+			)
207
+		) {
208
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
209
+		}
210
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * detect_activations_or_upgrades
217
+	 * Checks for activation or upgrade of core first;
218
+	 * then also checks if any registered addons have been activated or upgraded
219
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
220
+	 * which runs during the WP 'plugins_loaded' action at priority 3
221
+	 *
222
+	 * @access public
223
+	 * @return void
224
+	 */
225
+	public function detect_activations_or_upgrades()
226
+	{
227
+		//first off: let's make sure to handle core
228
+		$this->detect_if_activation_or_upgrade();
229
+		foreach ($this->registry->addons as $addon) {
230
+			//detect teh request type for that addon
231
+			$addon->detect_activation_or_upgrade();
232
+		}
233
+	}
234
+
235
+
236
+
237
+	/**
238
+	 * detect_if_activation_or_upgrade
239
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
240
+	 * and either setting up the DB or setting up maintenance mode etc.
241
+	 *
242
+	 * @access public
243
+	 * @return void
244
+	 */
245
+	public function detect_if_activation_or_upgrade()
246
+	{
247
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
248
+		// load M-Mode class
249
+		$this->registry->load_core('Maintenance_Mode');
250
+		// check if db has been updated, or if its a brand-new installation
251
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
252
+		$request_type = $this->detect_req_type($espresso_db_update);
253
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
254
+		switch ($request_type) {
255
+			case EE_System::req_type_new_activation:
256
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
257
+				$this->_handle_core_version_change($espresso_db_update);
258
+				break;
259
+			case EE_System::req_type_reactivation:
260
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
261
+				$this->_handle_core_version_change($espresso_db_update);
262
+				break;
263
+			case EE_System::req_type_upgrade:
264
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
265
+				//migrations may be required now that we've upgraded
266
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
267
+				$this->_handle_core_version_change($espresso_db_update);
268
+				//				echo "done upgrade";die;
269
+				break;
270
+			case EE_System::req_type_downgrade:
271
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
272
+				//its possible migrations are no longer required
273
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
274
+				$this->_handle_core_version_change($espresso_db_update);
275
+				break;
276
+			case EE_System::req_type_normal:
277
+			default:
278
+				//				$this->_maybe_redirect_to_ee_about();
279
+				break;
280
+		}
281
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
282
+	}
283
+
284
+
285
+
286
+	/**
287
+	 * Updates the list of installed versions and sets hooks for
288
+	 * initializing the database later during the request
289
+	 *
290
+	 * @param array $espresso_db_update
291
+	 */
292
+	protected function _handle_core_version_change($espresso_db_update)
293
+	{
294
+		$this->update_list_of_installed_versions($espresso_db_update);
295
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
296
+		add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
297
+			array($this, 'initialize_db_if_no_migrations_required'));
298
+	}
299
+
300
+
301
+
302
+	/**
303
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
304
+	 * information about what versions of EE have been installed and activated,
305
+	 * NOT necessarily the state of the database
306
+	 *
307
+	 * @param null $espresso_db_update
308
+	 * @internal param array $espresso_db_update_value the value of the WordPress option. If not supplied, fetches it
309
+	 *           from the options table
310
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
311
+	 */
312
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
313
+	{
314
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
315
+		if ( ! $espresso_db_update) {
316
+			$espresso_db_update = get_option('espresso_db_update');
317
+		}
318
+		// check that option is an array
319
+		if ( ! is_array($espresso_db_update)) {
320
+			// if option is FALSE, then it never existed
321
+			if ($espresso_db_update === false) {
322
+				// make $espresso_db_update an array and save option with autoload OFF
323
+				$espresso_db_update = array();
324
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
325
+			} else {
326
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
327
+				$espresso_db_update = array($espresso_db_update => array());
328
+				update_option('espresso_db_update', $espresso_db_update);
329
+			}
330
+		} else {
331
+			$corrected_db_update = array();
332
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
333
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
334
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
335
+					//the key is an int, and the value IS NOT an array
336
+					//so it must be numerically-indexed, where values are versions installed...
337
+					//fix it!
338
+					$version_string = $should_be_array;
339
+					$corrected_db_update[$version_string] = array('unknown-date');
340
+				} else {
341
+					//ok it checks out
342
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
343
+				}
344
+			}
345
+			$espresso_db_update = $corrected_db_update;
346
+			update_option('espresso_db_update', $espresso_db_update);
347
+		}
348
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
349
+		return $espresso_db_update;
350
+	}
351
+
352
+
353
+
354
+	/**
355
+	 * Does the traditional work of setting up the plugin's database and adding default data.
356
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
357
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
358
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
359
+	 * so that it will be done when migrations are finished
360
+	 *
361
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
362
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
363
+	 *                                       This is a resource-intensive job
364
+	 *                                       so we prefer to only do it when necessary
365
+	 * @return void
366
+	 */
367
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
368
+	{
369
+		$request_type = $this->detect_req_type();
370
+		//only initialize system if we're not in maintenance mode.
371
+		if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
372
+			update_option('ee_flush_rewrite_rules', true);
373
+			if ($verify_schema) {
374
+				EEH_Activation::initialize_db_and_folders();
375
+			}
376
+			EEH_Activation::initialize_db_content();
377
+			EEH_Activation::system_initialization();
378
+			if ($initialize_addons_too) {
379
+				$this->initialize_addons();
380
+			}
381
+		} else {
382
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
383
+		}
384
+		if ($request_type === EE_System::req_type_new_activation
385
+			|| $request_type === EE_System::req_type_reactivation
386
+			|| (
387
+				$request_type === EE_System::req_type_upgrade
388
+				&& $this->is_major_version_change()
389
+			)
390
+		) {
391
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
392
+		}
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 * Initializes the db for all registered addons
399
+	 */
400
+	public function initialize_addons()
401
+	{
402
+		//foreach registered addon, make sure its db is up-to-date too
403
+		foreach ($this->registry->addons as $addon) {
404
+			$addon->initialize_db_if_no_migrations_required();
405
+		}
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
412
+	 *
413
+	 * @param    array  $version_history
414
+	 * @param    string $current_version_to_add version to be added to the version history
415
+	 * @return    boolean success as to whether or not this option was changed
416
+	 */
417
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
418
+	{
419
+		if ( ! $version_history) {
420
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
421
+		}
422
+		if ($current_version_to_add == null) {
423
+			$current_version_to_add = espresso_version();
424
+		}
425
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
426
+		// re-save
427
+		return update_option('espresso_db_update', $version_history);
428
+	}
429
+
430
+
431
+
432
+	/**
433
+	 * Detects if the current version indicated in the has existed in the list of
434
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
435
+	 *
436
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
437
+	 *                                  If not supplied, fetches it from the options table.
438
+	 *                                  Also, caches its result so later parts of the code can also know whether
439
+	 *                                  there's been an update or not. This way we can add the current version to
440
+	 *                                  espresso_db_update, but still know if this is a new install or not
441
+	 * @return int one of the constants on EE_System::req_type_
442
+	 */
443
+	public function detect_req_type($espresso_db_update = null)
444
+	{
445
+		if ($this->_req_type === null) {
446
+			$espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
447
+				: $this->fix_espresso_db_upgrade_option();
448
+			$this->_req_type = $this->detect_req_type_given_activation_history($espresso_db_update,
449
+				'ee_espresso_activation', espresso_version());
450
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
451
+		}
452
+		return $this->_req_type;
453
+	}
454
+
455
+
456
+
457
+	/**
458
+	 * Returns whether or not there was a non-micro version change (ie, change in either
459
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
460
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
461
+	 *
462
+	 * @param $activation_history
463
+	 * @return bool
464
+	 */
465
+	protected function _detect_major_version_change($activation_history)
466
+	{
467
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
468
+		$previous_version_parts = explode('.', $previous_version);
469
+		$current_version_parts = explode('.', espresso_version());
470
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
471
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
472
+				   || $previous_version_parts[1] !== $current_version_parts[1]
473
+			   );
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * Returns true if either the major or minor version of EE changed during this request.
480
+	 * 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
481
+	 *
482
+	 * @return bool
483
+	 */
484
+	public function is_major_version_change()
485
+	{
486
+		return $this->_major_version_change;
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
493
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the wordpress option which is temporarily
494
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
495
+	 * just activated to (for core that will always be espresso_version())
496
+	 *
497
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
498
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
499
+	 * @param string $activation_indicator_option_name the name of the wordpress option that is temporarily set to
500
+	 *                                                 indicate that this plugin was just activated
501
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
502
+	 *                                                 espresso_version())
503
+	 * @return int one of the constants on EE_System::req_type_*
504
+	 */
505
+	public static function detect_req_type_given_activation_history(
506
+		$activation_history_for_addon,
507
+		$activation_indicator_option_name,
508
+		$version_to_upgrade_to
509
+	) {
510
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
511
+		if ($activation_history_for_addon) {
512
+			//it exists, so this isn't a completely new install
513
+			//check if this version already in that list of previously installed versions
514
+			if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
515
+				//it a version we haven't seen before
516
+				if ($version_is_higher === 1) {
517
+					$req_type = EE_System::req_type_upgrade;
518
+				} else {
519
+					$req_type = EE_System::req_type_downgrade;
520
+				}
521
+				delete_option($activation_indicator_option_name);
522
+			} else {
523
+				// its not an update. maybe a reactivation?
524
+				if (get_option($activation_indicator_option_name, false)) {
525
+					if ($version_is_higher === -1) {
526
+						$req_type = EE_System::req_type_downgrade;
527
+					} elseif ($version_is_higher === 0) {
528
+						//we've seen this version before, but it's an activation. must be a reactivation
529
+						$req_type = EE_System::req_type_reactivation;
530
+					} else {//$version_is_higher === 1
531
+						$req_type = EE_System::req_type_upgrade;
532
+					}
533
+					delete_option($activation_indicator_option_name);
534
+				} else {
535
+					//we've seen this version before and the activation indicate doesn't show it was just activated
536
+					if ($version_is_higher === -1) {
537
+						$req_type = EE_System::req_type_downgrade;
538
+					} elseif ($version_is_higher === 0) {
539
+						//we've seen this version before and it's not an activation. its normal request
540
+						$req_type = EE_System::req_type_normal;
541
+					} else {//$version_is_higher === 1
542
+						$req_type = EE_System::req_type_upgrade;
543
+					}
544
+				}
545
+			}
546
+		} else {
547
+			//brand new install
548
+			$req_type = EE_System::req_type_new_activation;
549
+			delete_option($activation_indicator_option_name);
550
+		}
551
+		return $req_type;
552
+	}
553
+
554
+
555
+
556
+	/**
557
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
558
+	 * the $activation_history_for_addon
559
+	 *
560
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
561
+	 *                                             sometimes containing 'unknown-date'
562
+	 * @param string $version_to_upgrade_to        (current version)
563
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
564
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
565
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
566
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
567
+	 */
568
+	protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
569
+	{
570
+		//find the most recently-activated version
571
+		$most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
572
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 * Gets the most recently active version listed in the activation history,
579
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
580
+	 *
581
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
582
+	 *                                   sometimes containing 'unknown-date'
583
+	 * @return string
584
+	 */
585
+	protected static function _get_most_recently_active_version_from_activation_history($activation_history)
586
+	{
587
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
588
+		$most_recently_active_version = '0.0.0.dev.000';
589
+		if (is_array($activation_history)) {
590
+			foreach ($activation_history as $version => $times_activated) {
591
+				//check there is a record of when this version was activated. Otherwise,
592
+				//mark it as unknown
593
+				if ( ! $times_activated) {
594
+					$times_activated = array('unknown-date');
595
+				}
596
+				if (is_string($times_activated)) {
597
+					$times_activated = array($times_activated);
598
+				}
599
+				foreach ($times_activated as $an_activation) {
600
+					if ($an_activation != 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
601
+						$most_recently_active_version = $version;
602
+						$most_recently_active_version_activation = $an_activation == 'unknown-date'
603
+							? '1970-01-01 00:00:00' : $an_activation;
604
+					}
605
+				}
606
+			}
607
+		}
608
+		return $most_recently_active_version;
609
+	}
610
+
611
+
612
+
613
+	/**
614
+	 * This redirects to the about EE page after activation
615
+	 *
616
+	 * @return void
617
+	 */
618
+	public function redirect_to_about_ee()
619
+	{
620
+		$notices = EE_Error::get_notices(false);
621
+		//if current user is an admin and it's not an ajax or rest request
622
+		if (
623
+			! (defined('DOING_AJAX') && DOING_AJAX)
624
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
625
+			&& ! isset($notices['errors'])
626
+			&& apply_filters(
627
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
628
+				$this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
629
+			)
630
+		) {
631
+			$query_params = array('page' => 'espresso_about');
632
+			if (EE_System::instance()->detect_req_type() == EE_System::req_type_new_activation) {
633
+				$query_params['new_activation'] = true;
634
+			}
635
+			if (EE_System::instance()->detect_req_type() == EE_System::req_type_reactivation) {
636
+				$query_params['reactivation'] = true;
637
+			}
638
+			$url = add_query_arg($query_params, admin_url('admin.php'));
639
+			wp_safe_redirect($url);
640
+			exit();
641
+		}
642
+	}
643
+
644
+
645
+
646
+	/**
647
+	 * load_core_configuration
648
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
649
+	 * which runs during the WP 'plugins_loaded' action at priority 5
650
+	 *
651
+	 * @return void
652
+	 */
653
+	public function load_core_configuration()
654
+	{
655
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
656
+		$this->registry->load_core('EE_Load_Textdomain');
657
+		//load textdomain
658
+		EE_Load_Textdomain::load_textdomain();
659
+		// load and setup EE_Config and EE_Network_Config
660
+		$this->registry->load_core('Config');
661
+		$this->registry->load_core('Network_Config');
662
+		// setup autoloaders
663
+		// enable logging?
664
+		if ($this->registry->CFG->admin->use_full_logging) {
665
+			$this->registry->load_core('Log');
666
+		}
667
+		// check for activation errors
668
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
669
+		if ($activation_errors) {
670
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
671
+			update_option('ee_plugin_activation_errors', false);
672
+		}
673
+		// get model names
674
+		$this->_parse_model_names();
675
+		//load caf stuff a chance to play during the activation process too.
676
+		$this->_maybe_brew_regular();
677
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
678
+	}
679
+
680
+
681
+
682
+	/**
683
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
684
+	 *
685
+	 * @return void
686
+	 */
687
+	private function _parse_model_names()
688
+	{
689
+		//get all the files in the EE_MODELS folder that end in .model.php
690
+		$models = glob(EE_MODELS . '*.model.php');
691
+		$model_names = array();
692
+		$non_abstract_db_models = array();
693
+		foreach ($models as $model) {
694
+			// get model classname
695
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
696
+			$short_name = str_replace('EEM_', '', $classname);
697
+			$reflectionClass = new ReflectionClass($classname);
698
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
699
+				$non_abstract_db_models[$short_name] = $classname;
700
+			}
701
+			$model_names[$short_name] = $classname;
702
+		}
703
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
704
+		$this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
705
+			$non_abstract_db_models);
706
+	}
707
+
708
+
709
+
710
+	/**
711
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
712
+	 * that need to be setup before our EE_System launches.
713
+	 *
714
+	 * @return void
715
+	 */
716
+	private function _maybe_brew_regular()
717
+	{
718
+		if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
719
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
720
+		}
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * register_shortcodes_modules_and_widgets
727
+	 * generate lists of shortcodes and modules, then verify paths and classes
728
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
729
+	 * which runs during the WP 'plugins_loaded' action at priority 7
730
+	 *
731
+	 * @access public
732
+	 * @return void
733
+	 */
734
+	public function register_shortcodes_modules_and_widgets()
735
+	{
736
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
737
+		// check for addons using old hookpoint
738
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
739
+			$this->_incompatible_addon_error();
740
+		}
741
+	}
742
+
743
+
744
+
745
+	/**
746
+	 * _incompatible_addon_error
747
+	 *
748
+	 * @access public
749
+	 * @return void
750
+	 */
751
+	private function _incompatible_addon_error()
752
+	{
753
+		// get array of classes hooking into here
754
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
755
+		if ( ! empty($class_names)) {
756
+			$msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
757
+				'event_espresso');
758
+			$msg .= '<ul>';
759
+			foreach ($class_names as $class_name) {
760
+				$msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
761
+						$class_name) . '</b></li>';
762
+			}
763
+			$msg .= '</ul>';
764
+			$msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
765
+				'event_espresso');
766
+			// save list of incompatible addons to wp-options for later use
767
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
768
+			if (is_admin()) {
769
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
770
+			}
771
+		}
772
+	}
773
+
774
+
775
+
776
+	/**
777
+	 * brew_espresso
778
+	 * begins the process of setting hooks for initializing EE in the correct order
779
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hookpoint
780
+	 * which runs during the WP 'plugins_loaded' action at priority 9
781
+	 *
782
+	 * @return void
783
+	 */
784
+	public function brew_espresso()
785
+	{
786
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
787
+		// load some final core systems
788
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
789
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
790
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
791
+		add_action('init', array($this, 'load_controllers'), 7);
792
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
793
+		add_action('init', array($this, 'initialize'), 10);
794
+		add_action('init', array($this, 'initialize_last'), 100);
795
+		add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 25);
796
+		add_action('admin_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 25);
797
+		add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
798
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
799
+			// pew pew pew
800
+			$this->registry->load_core('PUE');
801
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
802
+		}
803
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
804
+	}
805
+
806
+
807
+
808
+	/**
809
+	 *    set_hooks_for_core
810
+	 *
811
+	 * @access public
812
+	 * @return    void
813
+	 */
814
+	public function set_hooks_for_core()
815
+	{
816
+		$this->_deactivate_incompatible_addons();
817
+		do_action('AHEE__EE_System__set_hooks_for_core');
818
+	}
819
+
820
+
821
+
822
+	/**
823
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
824
+	 * deactivates any addons considered incompatible with the current version of EE
825
+	 */
826
+	private function _deactivate_incompatible_addons()
827
+	{
828
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
829
+		if ( ! empty($incompatible_addons)) {
830
+			$active_plugins = get_option('active_plugins', array());
831
+			foreach ($active_plugins as $active_plugin) {
832
+				foreach ($incompatible_addons as $incompatible_addon) {
833
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
834
+						unset($_GET['activate']);
835
+						espresso_deactivate_plugin($active_plugin);
836
+					}
837
+				}
838
+			}
839
+		}
840
+	}
841
+
842
+
843
+
844
+	/**
845
+	 *    perform_activations_upgrades_and_migrations
846
+	 *
847
+	 * @access public
848
+	 * @return    void
849
+	 */
850
+	public function perform_activations_upgrades_and_migrations()
851
+	{
852
+		//first check if we had previously attempted to setup EE's directories but failed
853
+		if (EEH_Activation::upload_directories_incomplete()) {
854
+			EEH_Activation::create_upload_directories();
855
+		}
856
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
857
+	}
858
+
859
+
860
+
861
+	/**
862
+	 *    load_CPTs_and_session
863
+	 *
864
+	 * @access public
865
+	 * @return    void
866
+	 */
867
+	public function load_CPTs_and_session()
868
+	{
869
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
870
+		// register Custom Post Types
871
+		$this->registry->load_core('Register_CPTs');
872
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
873
+	}
874
+
875
+
876
+
877
+	/**
878
+	 * load_controllers
879
+	 * this is the best place to load any additional controllers that needs access to EE core.
880
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
881
+	 * time
882
+	 *
883
+	 * @access public
884
+	 * @return void
885
+	 */
886
+	public function load_controllers()
887
+	{
888
+		do_action('AHEE__EE_System__load_controllers__start');
889
+		// let's get it started
890
+		if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
891
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
892
+			$this->registry->load_core('Front_Controller', array(), false, true);
893
+		} else if ( ! EE_FRONT_AJAX) {
894
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
895
+			EE_Registry::instance()->load_core('Admin');
896
+		}
897
+		do_action('AHEE__EE_System__load_controllers__complete');
898
+	}
899
+
900
+
901
+
902
+	/**
903
+	 * core_loaded_and_ready
904
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
905
+	 *
906
+	 * @access public
907
+	 * @return void
908
+	 */
909
+	public function core_loaded_and_ready()
910
+	{
911
+		do_action('AHEE__EE_System__core_loaded_and_ready');
912
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
913
+		$this->registry->load_core('Session');
914
+		//		add_action( 'wp_loaded', array( $this, 'set_hooks_for_shortcodes_modules_and_addons' ), 1 );
915
+	}
916
+
917
+
918
+
919
+	/**
920
+	 * initialize
921
+	 * this is the best place to begin initializing client code
922
+	 *
923
+	 * @access public
924
+	 * @return void
925
+	 */
926
+	public function initialize()
927
+	{
928
+		do_action('AHEE__EE_System__initialize');
929
+	}
930
+
931
+
932
+
933
+	/**
934
+	 * initialize_last
935
+	 * this is run really late during the WP init hookpoint, and ensures that mostly everything else that needs to
936
+	 * initialize has done so
937
+	 *
938
+	 * @access public
939
+	 * @return void
940
+	 */
941
+	public function initialize_last()
942
+	{
943
+		do_action('AHEE__EE_System__initialize_last');
944
+	}
945
+
946
+
947
+
948
+	/**
949
+	 * set_hooks_for_shortcodes_modules_and_addons
950
+	 * this is the best place for other systems to set callbacks for hooking into other parts of EE
951
+	 * this happens at the very beginning of the wp_loaded hookpoint
952
+	 *
953
+	 * @access public
954
+	 * @return void
955
+	 */
956
+	public function set_hooks_for_shortcodes_modules_and_addons()
957
+	{
958
+		//		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
959
+	}
960
+
961
+
962
+
963
+	/**
964
+	 * do_not_cache
965
+	 * sets no cache headers and defines no cache constants for WP plugins
966
+	 *
967
+	 * @access public
968
+	 * @return void
969
+	 */
970
+	public static function do_not_cache()
971
+	{
972
+		// set no cache constants
973
+		if ( ! defined('DONOTCACHEPAGE')) {
974
+			define('DONOTCACHEPAGE', true);
975
+		}
976
+		if ( ! defined('DONOTCACHCEOBJECT')) {
977
+			define('DONOTCACHCEOBJECT', true);
978
+		}
979
+		if ( ! defined('DONOTCACHEDB')) {
980
+			define('DONOTCACHEDB', true);
981
+		}
982
+		// add no cache headers
983
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
984
+		// plus a little extra for nginx and Google Chrome
985
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
986
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
987
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
988
+	}
989
+
990
+
991
+
992
+	/**
993
+	 *    extra_nocache_headers
994
+	 *
995
+	 * @access    public
996
+	 * @param $headers
997
+	 * @return    array
998
+	 */
999
+	public static function extra_nocache_headers($headers)
1000
+	{
1001
+		// for NGINX
1002
+		$headers['X-Accel-Expires'] = 0;
1003
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1004
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1005
+		return $headers;
1006
+	}
1007
+
1008
+
1009
+
1010
+	/**
1011
+	 *    nocache_headers
1012
+	 *
1013
+	 * @access    public
1014
+	 * @return    void
1015
+	 */
1016
+	public static function nocache_headers()
1017
+	{
1018
+		nocache_headers();
1019
+	}
1020
+
1021
+
1022
+
1023
+	/**
1024
+	 *    espresso_toolbar_items
1025
+	 *
1026
+	 * @access public
1027
+	 * @param  WP_Admin_Bar $admin_bar
1028
+	 * @return void
1029
+	 */
1030
+	public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1031
+	{
1032
+		// if in full M-Mode, or its an AJAX request, or user is NOT an admin
1033
+		if (EE_Maintenance_Mode::instance()->level() == EE_Maintenance_Mode::level_2_complete_maintenance
1034
+			|| defined('DOING_AJAX')
1035
+			|| ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1036
+		) {
1037
+			return;
1038
+		}
1039
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1040
+		$menu_class = 'espresso_menu_item_class';
1041
+		//we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1042
+		//because they're only defined in each of their respective constructors
1043
+		//and this might be a frontend request, in which case they aren't available
1044
+		$events_admin_url = admin_url("admin.php?page=espresso_events");
1045
+		$reg_admin_url = admin_url("admin.php?page=espresso_registrations");
1046
+		$extensions_admin_url = admin_url("admin.php?page=espresso_packages");
1047
+		//Top Level
1048
+		$admin_bar->add_menu(array(
1049
+			'id'    => 'espresso-toolbar',
1050
+			'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1051
+					   . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1052
+					   . '</span>',
1053
+			'href'  => $events_admin_url,
1054
+			'meta'  => array(
1055
+				'title' => __('Event Espresso', 'event_espresso'),
1056
+				'class' => $menu_class . 'first',
1057
+			),
1058
+		));
1059
+		//Events
1060
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1061
+			$admin_bar->add_menu(array(
1062
+				'id'     => 'espresso-toolbar-events',
1063
+				'parent' => 'espresso-toolbar',
1064
+				'title'  => __('Events', 'event_espresso'),
1065
+				'href'   => $events_admin_url,
1066
+				'meta'   => array(
1067
+					'title'  => __('Events', 'event_espresso'),
1068
+					'target' => '',
1069
+					'class'  => $menu_class,
1070
+				),
1071
+			));
1072
+		}
1073
+		if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1074
+			//Events Add New
1075
+			$admin_bar->add_menu(array(
1076
+				'id'     => 'espresso-toolbar-events-new',
1077
+				'parent' => 'espresso-toolbar-events',
1078
+				'title'  => __('Add New', 'event_espresso'),
1079
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1080
+				'meta'   => array(
1081
+					'title'  => __('Add New', 'event_espresso'),
1082
+					'target' => '',
1083
+					'class'  => $menu_class,
1084
+				),
1085
+			));
1086
+		}
1087
+		if (is_single() && (get_post_type() == 'espresso_events')) {
1088
+			//Current post
1089
+			global $post;
1090
+			if ($this->registry->CAP->current_user_can('ee_edit_event',
1091
+				'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1092
+			) {
1093
+				//Events Edit Current Event
1094
+				$admin_bar->add_menu(array(
1095
+					'id'     => 'espresso-toolbar-events-edit',
1096
+					'parent' => 'espresso-toolbar-events',
1097
+					'title'  => __('Edit Event', 'event_espresso'),
1098
+					'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1099
+						$events_admin_url),
1100
+					'meta'   => array(
1101
+						'title'  => __('Edit Event', 'event_espresso'),
1102
+						'target' => '',
1103
+						'class'  => $menu_class,
1104
+					),
1105
+				));
1106
+			}
1107
+		}
1108
+		//Events View
1109
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1110
+			'ee_admin_bar_menu_espresso-toolbar-events-view')
1111
+		) {
1112
+			$admin_bar->add_menu(array(
1113
+				'id'     => 'espresso-toolbar-events-view',
1114
+				'parent' => 'espresso-toolbar-events',
1115
+				'title'  => __('View', 'event_espresso'),
1116
+				'href'   => $events_admin_url,
1117
+				'meta'   => array(
1118
+					'title'  => __('View', 'event_espresso'),
1119
+					'target' => '',
1120
+					'class'  => $menu_class,
1121
+				),
1122
+			));
1123
+		}
1124
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1125
+			//Events View All
1126
+			$admin_bar->add_menu(array(
1127
+				'id'     => 'espresso-toolbar-events-all',
1128
+				'parent' => 'espresso-toolbar-events-view',
1129
+				'title'  => __('All', 'event_espresso'),
1130
+				'href'   => $events_admin_url,
1131
+				'meta'   => array(
1132
+					'title'  => __('All', 'event_espresso'),
1133
+					'target' => '',
1134
+					'class'  => $menu_class,
1135
+				),
1136
+			));
1137
+		}
1138
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1139
+			'ee_admin_bar_menu_espresso-toolbar-events-today')
1140
+		) {
1141
+			//Events View Today
1142
+			$admin_bar->add_menu(array(
1143
+				'id'     => 'espresso-toolbar-events-today',
1144
+				'parent' => 'espresso-toolbar-events-view',
1145
+				'title'  => __('Today', 'event_espresso'),
1146
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1147
+					$events_admin_url),
1148
+				'meta'   => array(
1149
+					'title'  => __('Today', 'event_espresso'),
1150
+					'target' => '',
1151
+					'class'  => $menu_class,
1152
+				),
1153
+			));
1154
+		}
1155
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1156
+			'ee_admin_bar_menu_espresso-toolbar-events-month')
1157
+		) {
1158
+			//Events View This Month
1159
+			$admin_bar->add_menu(array(
1160
+				'id'     => 'espresso-toolbar-events-month',
1161
+				'parent' => 'espresso-toolbar-events-view',
1162
+				'title'  => __('This Month', 'event_espresso'),
1163
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1164
+					$events_admin_url),
1165
+				'meta'   => array(
1166
+					'title'  => __('This Month', 'event_espresso'),
1167
+					'target' => '',
1168
+					'class'  => $menu_class,
1169
+				),
1170
+			));
1171
+		}
1172
+		//Registration Overview
1173
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1174
+			'ee_admin_bar_menu_espresso-toolbar-registrations')
1175
+		) {
1176
+			$admin_bar->add_menu(array(
1177
+				'id'     => 'espresso-toolbar-registrations',
1178
+				'parent' => 'espresso-toolbar',
1179
+				'title'  => __('Registrations', 'event_espresso'),
1180
+				'href'   => $reg_admin_url,
1181
+				'meta'   => array(
1182
+					'title'  => __('Registrations', 'event_espresso'),
1183
+					'target' => '',
1184
+					'class'  => $menu_class,
1185
+				),
1186
+			));
1187
+		}
1188
+		//Registration Overview Today
1189
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1190
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1191
+		) {
1192
+			$admin_bar->add_menu(array(
1193
+				'id'     => 'espresso-toolbar-registrations-today',
1194
+				'parent' => 'espresso-toolbar-registrations',
1195
+				'title'  => __('Today', 'event_espresso'),
1196
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1197
+					$reg_admin_url),
1198
+				'meta'   => array(
1199
+					'title'  => __('Today', 'event_espresso'),
1200
+					'target' => '',
1201
+					'class'  => $menu_class,
1202
+				),
1203
+			));
1204
+		}
1205
+		//Registration Overview Today Completed
1206
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1207
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1208
+		) {
1209
+			$admin_bar->add_menu(array(
1210
+				'id'     => 'espresso-toolbar-registrations-today-approved',
1211
+				'parent' => 'espresso-toolbar-registrations-today',
1212
+				'title'  => __('Approved', 'event_espresso'),
1213
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1214
+					'action'      => 'default',
1215
+					'status'      => 'today',
1216
+					'_reg_status' => EEM_Registration::status_id_approved,
1217
+				), $reg_admin_url),
1218
+				'meta'   => array(
1219
+					'title'  => __('Approved', 'event_espresso'),
1220
+					'target' => '',
1221
+					'class'  => $menu_class,
1222
+				),
1223
+			));
1224
+		}
1225
+		//Registration Overview Today Pending\
1226
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1227
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1228
+		) {
1229
+			$admin_bar->add_menu(array(
1230
+				'id'     => 'espresso-toolbar-registrations-today-pending',
1231
+				'parent' => 'espresso-toolbar-registrations-today',
1232
+				'title'  => __('Pending', 'event_espresso'),
1233
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1234
+					'action'     => 'default',
1235
+					'status'     => 'today',
1236
+					'reg_status' => EEM_Registration::status_id_pending_payment,
1237
+				), $reg_admin_url),
1238
+				'meta'   => array(
1239
+					'title'  => __('Pending Payment', 'event_espresso'),
1240
+					'target' => '',
1241
+					'class'  => $menu_class,
1242
+				),
1243
+			));
1244
+		}
1245
+		//Registration Overview Today Incomplete
1246
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1247
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1248
+		) {
1249
+			$admin_bar->add_menu(array(
1250
+				'id'     => 'espresso-toolbar-registrations-today-not-approved',
1251
+				'parent' => 'espresso-toolbar-registrations-today',
1252
+				'title'  => __('Not Approved', 'event_espresso'),
1253
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1254
+					'action'      => 'default',
1255
+					'status'      => 'today',
1256
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1257
+				), $reg_admin_url),
1258
+				'meta'   => array(
1259
+					'title'  => __('Not Approved', 'event_espresso'),
1260
+					'target' => '',
1261
+					'class'  => $menu_class,
1262
+				),
1263
+			));
1264
+		}
1265
+		//Registration Overview Today Incomplete
1266
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1267
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1268
+		) {
1269
+			$admin_bar->add_menu(array(
1270
+				'id'     => 'espresso-toolbar-registrations-today-cancelled',
1271
+				'parent' => 'espresso-toolbar-registrations-today',
1272
+				'title'  => __('Cancelled', 'event_espresso'),
1273
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1274
+					'action'      => 'default',
1275
+					'status'      => 'today',
1276
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1277
+				), $reg_admin_url),
1278
+				'meta'   => array(
1279
+					'title'  => __('Cancelled', 'event_espresso'),
1280
+					'target' => '',
1281
+					'class'  => $menu_class,
1282
+				),
1283
+			));
1284
+		}
1285
+		//Registration Overview This Month
1286
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1287
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1288
+		) {
1289
+			$admin_bar->add_menu(array(
1290
+				'id'     => 'espresso-toolbar-registrations-month',
1291
+				'parent' => 'espresso-toolbar-registrations',
1292
+				'title'  => __('This Month', 'event_espresso'),
1293
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1294
+					$reg_admin_url),
1295
+				'meta'   => array(
1296
+					'title'  => __('This Month', 'event_espresso'),
1297
+					'target' => '',
1298
+					'class'  => $menu_class,
1299
+				),
1300
+			));
1301
+		}
1302
+		//Registration Overview This Month Approved
1303
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1304
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1305
+		) {
1306
+			$admin_bar->add_menu(array(
1307
+				'id'     => 'espresso-toolbar-registrations-month-approved',
1308
+				'parent' => 'espresso-toolbar-registrations-month',
1309
+				'title'  => __('Approved', 'event_espresso'),
1310
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1311
+					'action'      => 'default',
1312
+					'status'      => 'month',
1313
+					'_reg_status' => EEM_Registration::status_id_approved,
1314
+				), $reg_admin_url),
1315
+				'meta'   => array(
1316
+					'title'  => __('Approved', 'event_espresso'),
1317
+					'target' => '',
1318
+					'class'  => $menu_class,
1319
+				),
1320
+			));
1321
+		}
1322
+		//Registration Overview This Month Pending
1323
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1324
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1325
+		) {
1326
+			$admin_bar->add_menu(array(
1327
+				'id'     => 'espresso-toolbar-registrations-month-pending',
1328
+				'parent' => 'espresso-toolbar-registrations-month',
1329
+				'title'  => __('Pending', 'event_espresso'),
1330
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1331
+					'action'      => 'default',
1332
+					'status'      => 'month',
1333
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1334
+				), $reg_admin_url),
1335
+				'meta'   => array(
1336
+					'title'  => __('Pending', 'event_espresso'),
1337
+					'target' => '',
1338
+					'class'  => $menu_class,
1339
+				),
1340
+			));
1341
+		}
1342
+		//Registration Overview This Month Not Approved
1343
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1344
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1345
+		) {
1346
+			$admin_bar->add_menu(array(
1347
+				'id'     => 'espresso-toolbar-registrations-month-not-approved',
1348
+				'parent' => 'espresso-toolbar-registrations-month',
1349
+				'title'  => __('Not Approved', 'event_espresso'),
1350
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1351
+					'action'      => 'default',
1352
+					'status'      => 'month',
1353
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1354
+				), $reg_admin_url),
1355
+				'meta'   => array(
1356
+					'title'  => __('Not Approved', 'event_espresso'),
1357
+					'target' => '',
1358
+					'class'  => $menu_class,
1359
+				),
1360
+			));
1361
+		}
1362
+		//Registration Overview This Month Cancelled
1363
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1364
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1365
+		) {
1366
+			$admin_bar->add_menu(array(
1367
+				'id'     => 'espresso-toolbar-registrations-month-cancelled',
1368
+				'parent' => 'espresso-toolbar-registrations-month',
1369
+				'title'  => __('Cancelled', 'event_espresso'),
1370
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1371
+					'action'      => 'default',
1372
+					'status'      => 'month',
1373
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1374
+				), $reg_admin_url),
1375
+				'meta'   => array(
1376
+					'title'  => __('Cancelled', 'event_espresso'),
1377
+					'target' => '',
1378
+					'class'  => $menu_class,
1379
+				),
1380
+			));
1381
+		}
1382
+		//Extensions & Services
1383
+		if ($this->registry->CAP->current_user_can('ee_read_ee',
1384
+			'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1385
+		) {
1386
+			$admin_bar->add_menu(array(
1387
+				'id'     => 'espresso-toolbar-extensions-and-services',
1388
+				'parent' => 'espresso-toolbar',
1389
+				'title'  => __('Extensions & Services', 'event_espresso'),
1390
+				'href'   => $extensions_admin_url,
1391
+				'meta'   => array(
1392
+					'title'  => __('Extensions & Services', 'event_espresso'),
1393
+					'target' => '',
1394
+					'class'  => $menu_class,
1395
+				),
1396
+			));
1397
+		}
1398
+	}
1399
+
1400
+
1401
+
1402
+	/**
1403
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1404
+	 * never returned with the function.
1405
+	 *
1406
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1407
+	 * @return array
1408
+	 */
1409
+	public function remove_pages_from_wp_list_pages($exclude_array)
1410
+	{
1411
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1412
+	}
1413
+
1414
+
1415
+
1416
+
1417
+
1418
+
1419
+	/***********************************************        WP_ENQUEUE_SCRIPTS HOOK         ***********************************************/
1420
+	/**
1421
+	 *    wp_enqueue_scripts
1422
+	 *
1423
+	 * @access    public
1424
+	 * @return    void
1425
+	 */
1426
+	public function wp_enqueue_scripts()
1427
+	{
1428
+		// unlike other systems, EE_System_scripts loading is turned ON by default, but prior to the init hook, can be turned off via: add_filter( 'FHEE_load_EE_System_scripts', '__return_false' );
1429
+		if (apply_filters('FHEE_load_EE_System_scripts', true)) {
1430
+			// jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1431
+			if (apply_filters('FHEE_load_jquery_validate', false)) {
1432
+				// register jQuery Validate and additional methods
1433
+				wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1434
+					array('jquery'), '1.15.0', true);
1435
+				wp_register_script('jquery-validate-extra-methods',
1436
+					EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1437
+					array('jquery', 'jquery-validate'), '1.15.0', true);
1438
+			}
1439
+		}
1440
+	}
1441 1441
 
1442 1442
 
1443 1443
 
Please login to merge, or discard this patch.
core/request_stack/EE_Request.core.php 2 patches
Indentation   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -15,231 +15,231 @@  discard block
 block discarded – undo
15 15
 class EE_Request
16 16
 {
17 17
 
18
-    /**
19
-     * @access private
20
-     * @var    array $_get $_GET parameters
21
-     */
22
-    private $_get = array();
23
-
24
-    /**
25
-     * @access private
26
-     * @var    array $_post $_POST parameters
27
-     */
28
-    private $_post = array();
29
-
30
-    /**
31
-     * @access private
32
-     * @var    array $_cookie $_COOKIE parameters
33
-     */
34
-    private $_cookie = array();
35
-
36
-    /**
37
-     * @access private
38
-     * @var    array $_params $_REQUEST parameters
39
-     */
40
-    private $_params = array();
41
-
42
-    /**
43
-     * whether current request is via AJAX
44
-     *
45
-     * @var    boolean
46
-     * @access public
47
-     */
48
-    public $ajax = false;
49
-
50
-    /**
51
-     * whether current request is via AJAX from the frontend of the site
52
-     *
53
-     * @var    boolean
54
-     * @access public
55
-     */
56
-    public $front_ajax = false;
57
-
58
-    /**
59
-     * IP address for request
60
-     *
61
-     * @var string $_ip_address
62
-     */
63
-    private $_ip_address = '';
64
-
65
-
66
-
67
-    /**
68
-     * class constructor
69
-     *
70
-     * @access    public
71
-     * @param array $get
72
-     * @param array $post
73
-     * @param array $cookie
74
-     */
75
-    public function __construct($get, $post, $cookie)
76
-    {
77
-        // grab request vars
78
-        $this->_get = (array)$get;
79
-        $this->_post = (array)$post;
80
-        $this->_cookie = (array)$cookie;
81
-        $this->_params = array_merge($this->_get, $this->_post);
82
-        // AJAX ???
83
-        $this->ajax = defined('DOING_AJAX') ? true : false;
84
-        $this->front_ajax = $this->is_set('ee_front_ajax') && (int)$this->get('ee_front_ajax') === 1;
85
-        // grab user IP
86
-        $this->_ip_address = $this->_visitor_ip();
87
-    }
88
-
89
-
90
-
91
-    /**
92
-     * @return array
93
-     */
94
-    public function get_params()
95
-    {
96
-        return $this->_get;
97
-    }
98
-
99
-
100
-
101
-    /**
102
-     * @return array
103
-     */
104
-    public function post_params()
105
-    {
106
-        return $this->_post;
107
-    }
108
-
109
-
110
-
111
-    /**
112
-     * @return array
113
-     */
114
-    public function cookie_params()
115
-    {
116
-        return $this->_cookie;
117
-    }
118
-
119
-
120
-
121
-    /**
122
-     * returns contents of $_REQUEST
123
-     *
124
-     * @return array
125
-     */
126
-    public function params()
127
-    {
128
-        return $this->_params;
129
-    }
130
-
131
-
132
-
133
-    /**
134
-     *    setter
135
-     *
136
-     * @access    public
137
-     * @param      $key
138
-     * @param      $value
139
-     * @param bool $override_ee
140
-     * @return    void
141
-     */
142
-    public function set($key, $value, $override_ee = false)
143
-    {
144
-        // don't allow "ee" to be overwritten unless explicitly instructed to do so
145
-        if (
146
-            $key !== 'ee'
147
-            || ($key === 'ee' && empty($this->_params['ee']))
148
-            || ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
149
-        ) {
150
-            $this->_params[$key] = $value;
151
-        }
152
-    }
153
-
154
-
155
-
156
-    /**
157
-     *    getter
158
-     *
159
-     * @access    public
160
-     * @param      $key
161
-     * @param null $default
162
-     * @return    mixed
163
-     */
164
-    public function get($key, $default = null)
165
-    {
166
-        return isset($this->_params[$key]) ? $this->_params[$key] : $default;
167
-    }
168
-
169
-
170
-
171
-    /**
172
-     *    check if param exists
173
-     *
174
-     * @access    public
175
-     * @param $key
176
-     * @return    boolean
177
-     */
178
-    public function is_set($key)
179
-    {
180
-        return isset($this->_params[$key]) ? true : false;
181
-    }
182
-
183
-
184
-
185
-    /**
186
-     *    remove param
187
-     *
188
-     * @access    public
189
-     * @param      $key
190
-     * @param bool $unset_from_global_too
191
-     */
192
-    public function un_set($key, $unset_from_global_too = false)
193
-    {
194
-        unset($this->_params[$key]);
195
-        if ($unset_from_global_too) {
196
-            unset($_REQUEST[$key]);
197
-        }
198
-    }
199
-
200
-
201
-
202
-    /**
203
-     * @return string
204
-     */
205
-    public function ip_address()
206
-    {
207
-        return $this->_ip_address;
208
-    }
209
-
210
-
211
-
212
-    /**
213
-     * _visitor_ip
214
-     *    attempt to get IP address of current visitor from server
215
-     * plz see: http://stackoverflow.com/a/2031935/1475279
216
-     *
217
-     * @access public
218
-     * @return string
219
-     */
220
-    private function _visitor_ip()
221
-    {
222
-        $visitor_ip = '0.0.0.0';
223
-        $server_keys = array(
224
-            'HTTP_CLIENT_IP',
225
-            'HTTP_X_FORWARDED_FOR',
226
-            'HTTP_X_FORWARDED',
227
-            'HTTP_X_CLUSTER_CLIENT_IP',
228
-            'HTTP_FORWARDED_FOR',
229
-            'HTTP_FORWARDED',
230
-            'REMOTE_ADDR',
231
-        );
232
-        foreach ($server_keys as $key) {
233
-            if (isset($_SERVER[$key])) {
234
-                foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
235
-                    if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
236
-                        $visitor_ip = $ip;
237
-                    }
238
-                }
239
-            }
240
-        }
241
-        return $visitor_ip;
242
-    }
18
+	/**
19
+	 * @access private
20
+	 * @var    array $_get $_GET parameters
21
+	 */
22
+	private $_get = array();
23
+
24
+	/**
25
+	 * @access private
26
+	 * @var    array $_post $_POST parameters
27
+	 */
28
+	private $_post = array();
29
+
30
+	/**
31
+	 * @access private
32
+	 * @var    array $_cookie $_COOKIE parameters
33
+	 */
34
+	private $_cookie = array();
35
+
36
+	/**
37
+	 * @access private
38
+	 * @var    array $_params $_REQUEST parameters
39
+	 */
40
+	private $_params = array();
41
+
42
+	/**
43
+	 * whether current request is via AJAX
44
+	 *
45
+	 * @var    boolean
46
+	 * @access public
47
+	 */
48
+	public $ajax = false;
49
+
50
+	/**
51
+	 * whether current request is via AJAX from the frontend of the site
52
+	 *
53
+	 * @var    boolean
54
+	 * @access public
55
+	 */
56
+	public $front_ajax = false;
57
+
58
+	/**
59
+	 * IP address for request
60
+	 *
61
+	 * @var string $_ip_address
62
+	 */
63
+	private $_ip_address = '';
64
+
65
+
66
+
67
+	/**
68
+	 * class constructor
69
+	 *
70
+	 * @access    public
71
+	 * @param array $get
72
+	 * @param array $post
73
+	 * @param array $cookie
74
+	 */
75
+	public function __construct($get, $post, $cookie)
76
+	{
77
+		// grab request vars
78
+		$this->_get = (array)$get;
79
+		$this->_post = (array)$post;
80
+		$this->_cookie = (array)$cookie;
81
+		$this->_params = array_merge($this->_get, $this->_post);
82
+		// AJAX ???
83
+		$this->ajax = defined('DOING_AJAX') ? true : false;
84
+		$this->front_ajax = $this->is_set('ee_front_ajax') && (int)$this->get('ee_front_ajax') === 1;
85
+		// grab user IP
86
+		$this->_ip_address = $this->_visitor_ip();
87
+	}
88
+
89
+
90
+
91
+	/**
92
+	 * @return array
93
+	 */
94
+	public function get_params()
95
+	{
96
+		return $this->_get;
97
+	}
98
+
99
+
100
+
101
+	/**
102
+	 * @return array
103
+	 */
104
+	public function post_params()
105
+	{
106
+		return $this->_post;
107
+	}
108
+
109
+
110
+
111
+	/**
112
+	 * @return array
113
+	 */
114
+	public function cookie_params()
115
+	{
116
+		return $this->_cookie;
117
+	}
118
+
119
+
120
+
121
+	/**
122
+	 * returns contents of $_REQUEST
123
+	 *
124
+	 * @return array
125
+	 */
126
+	public function params()
127
+	{
128
+		return $this->_params;
129
+	}
130
+
131
+
132
+
133
+	/**
134
+	 *    setter
135
+	 *
136
+	 * @access    public
137
+	 * @param      $key
138
+	 * @param      $value
139
+	 * @param bool $override_ee
140
+	 * @return    void
141
+	 */
142
+	public function set($key, $value, $override_ee = false)
143
+	{
144
+		// don't allow "ee" to be overwritten unless explicitly instructed to do so
145
+		if (
146
+			$key !== 'ee'
147
+			|| ($key === 'ee' && empty($this->_params['ee']))
148
+			|| ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
149
+		) {
150
+			$this->_params[$key] = $value;
151
+		}
152
+	}
153
+
154
+
155
+
156
+	/**
157
+	 *    getter
158
+	 *
159
+	 * @access    public
160
+	 * @param      $key
161
+	 * @param null $default
162
+	 * @return    mixed
163
+	 */
164
+	public function get($key, $default = null)
165
+	{
166
+		return isset($this->_params[$key]) ? $this->_params[$key] : $default;
167
+	}
168
+
169
+
170
+
171
+	/**
172
+	 *    check if param exists
173
+	 *
174
+	 * @access    public
175
+	 * @param $key
176
+	 * @return    boolean
177
+	 */
178
+	public function is_set($key)
179
+	{
180
+		return isset($this->_params[$key]) ? true : false;
181
+	}
182
+
183
+
184
+
185
+	/**
186
+	 *    remove param
187
+	 *
188
+	 * @access    public
189
+	 * @param      $key
190
+	 * @param bool $unset_from_global_too
191
+	 */
192
+	public function un_set($key, $unset_from_global_too = false)
193
+	{
194
+		unset($this->_params[$key]);
195
+		if ($unset_from_global_too) {
196
+			unset($_REQUEST[$key]);
197
+		}
198
+	}
199
+
200
+
201
+
202
+	/**
203
+	 * @return string
204
+	 */
205
+	public function ip_address()
206
+	{
207
+		return $this->_ip_address;
208
+	}
209
+
210
+
211
+
212
+	/**
213
+	 * _visitor_ip
214
+	 *    attempt to get IP address of current visitor from server
215
+	 * plz see: http://stackoverflow.com/a/2031935/1475279
216
+	 *
217
+	 * @access public
218
+	 * @return string
219
+	 */
220
+	private function _visitor_ip()
221
+	{
222
+		$visitor_ip = '0.0.0.0';
223
+		$server_keys = array(
224
+			'HTTP_CLIENT_IP',
225
+			'HTTP_X_FORWARDED_FOR',
226
+			'HTTP_X_FORWARDED',
227
+			'HTTP_X_CLUSTER_CLIENT_IP',
228
+			'HTTP_FORWARDED_FOR',
229
+			'HTTP_FORWARDED',
230
+			'REMOTE_ADDR',
231
+		);
232
+		foreach ($server_keys as $key) {
233
+			if (isset($_SERVER[$key])) {
234
+				foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
235
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
236
+						$visitor_ip = $ip;
237
+					}
238
+				}
239
+			}
240
+		}
241
+		return $visitor_ip;
242
+	}
243 243
 
244 244
 
245 245
 
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -75,13 +75,13 @@
 block discarded – undo
75 75
     public function __construct($get, $post, $cookie)
76 76
     {
77 77
         // grab request vars
78
-        $this->_get = (array)$get;
79
-        $this->_post = (array)$post;
80
-        $this->_cookie = (array)$cookie;
78
+        $this->_get = (array) $get;
79
+        $this->_post = (array) $post;
80
+        $this->_cookie = (array) $cookie;
81 81
         $this->_params = array_merge($this->_get, $this->_post);
82 82
         // AJAX ???
83 83
         $this->ajax = defined('DOING_AJAX') ? true : false;
84
-        $this->front_ajax = $this->is_set('ee_front_ajax') && (int)$this->get('ee_front_ajax') === 1;
84
+        $this->front_ajax = $this->is_set('ee_front_ajax') && (int) $this->get('ee_front_ajax') === 1;
85 85
         // grab user IP
86 86
         $this->_ip_address = $this->_visitor_ip();
87 87
     }
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 2 patches
Indentation   +725 added lines, -725 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
 EE_Registry::instance()->load_class('Processor_Base');
5 5
 
@@ -16,728 +16,728 @@  discard block
 block discarded – undo
16 16
 class EE_Payment_Processor extends EE_Processor_Base
17 17
 {
18 18
 
19
-    /**
20
-     * @var EE_Payment_Processor $_instance
21
-     * @access    private
22
-     */
23
-    private static $_instance;
24
-
25
-
26
-
27
-    /**
28
-     * @singleton method used to instantiate class object
29
-     * @access    public
30
-     * @return EE_Payment_Processor instance
31
-     */
32
-    public static function instance()
33
-    {
34
-        // check if class object is instantiated
35
-        if ( ! self::$_instance instanceof EE_Payment_Processor) {
36
-            self::$_instance = new self();
37
-        }
38
-        return self::$_instance;
39
-    }
40
-
41
-
42
-
43
-    /**
44
-     *private constructor to prevent direct creation
45
-     *
46
-     * @Constructor
47
-     * @access private
48
-     */
49
-    private function __construct()
50
-    {
51
-        do_action('AHEE__EE_Payment_Processor__construct');
52
-        add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction appropriately.
59
-     * Saves the payment that is generated
60
-     *
61
-     * @param EE_Payment_Method    $payment_method
62
-     * @param EE_Transaction       $transaction
63
-     * @param float                $amount       if only part of the transaction is to be paid for, how much.
64
-     *                                           Leave null if payment is for the full amount owing
65
-     * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
66
-     *                                           Receive_form_submission() should have
67
-     *                                           already been called on the billing form
68
-     *                                           (ie, its inputs should have their normalized values set).
69
-     * @param string               $return_url   string used mostly by offsite gateways to specify
70
-     *                                           where to go AFTER the offsite gateway
71
-     * @param string               $method       like 'CART', indicates who the client who called this was
72
-     * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
73
-     * @param boolean              $update_txn   whether or not to call
74
-     *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
75
-     * @param string               $cancel_url   URL to return to if off-site payments are cancelled
76
-     * @return \EE_Payment
77
-     * @throws \EE_Error
78
-     */
79
-    public function process_payment(
80
-        EE_Payment_Method $payment_method,
81
-        EE_Transaction $transaction,
82
-        $amount = null,
83
-        $billing_form = null,
84
-        $return_url = null,
85
-        $method = 'CART',
86
-        $by_admin = false,
87
-        $update_txn = true,
88
-        $cancel_url = ''
89
-    ) {
90
-        if ((float)$amount < 0) {
91
-            throw new EE_Error(
92
-                sprintf(
93
-                    __(
94
-                        'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
95
-                        'event_espresso'
96
-                    ),
97
-                    $amount,
98
-                    $transaction->ID()
99
-                )
100
-            );
101
-        }
102
-        // verify payment method
103
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
104
-        // verify transaction
105
-        EEM_Transaction::instance()->ensure_is_obj($transaction);
106
-        $transaction->set_payment_method_ID($payment_method->ID());
107
-        // verify payment method type
108
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109
-            $payment = $payment_method->type_obj()->process_payment(
110
-                $transaction,
111
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
112
-                $billing_form,
113
-                $return_url,
114
-                add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
115
-                $method,
116
-                $by_admin
117
-            );
118
-            // check if payment method uses an off-site gateway
119
-            if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
120
-                // don't process payments for off-site gateways yet because no payment has occurred yet
121
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
122
-            }
123
-            return $payment;
124
-        } else {
125
-            EE_Error::add_error(
126
-                sprintf(
127
-                    __('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
128
-                    '<br/>',
129
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
130
-                ), __FILE__, __FUNCTION__, __LINE__
131
-            );
132
-            return null;
133
-        }
134
-    }
135
-
136
-
137
-
138
-    /**
139
-     * @param EE_Transaction|int $transaction
140
-     * @param EE_Payment_Method  $payment_method
141
-     * @throws EE_Error
142
-     * @return string
143
-     */
144
-    public function get_ipn_url_for_payment_method($transaction, $payment_method)
145
-    {
146
-        /** @type \EE_Transaction $transaction */
147
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
148
-        $primary_reg = $transaction->primary_registration();
149
-        if ( ! $primary_reg instanceof EE_Registration) {
150
-            throw new EE_Error(
151
-                sprintf(
152
-                    __(
153
-                        "Cannot get IPN URL for transaction with ID %d because it has no primary registration",
154
-                        "event_espresso"
155
-                    ),
156
-                    $transaction->ID()
157
-                )
158
-            );
159
-        }
160
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
161
-        $url = add_query_arg(
162
-            array(
163
-                'e_reg_url_link'    => $primary_reg->reg_url_link(),
164
-                'ee_payment_method' => $payment_method->slug(),
165
-            ),
166
-            EE_Registry::instance()->CFG->core->txn_page_url()
167
-        );
168
-        return $url;
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
175
-     * we can easily find what registration the IPN is for and what payment method.
176
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
177
-     * If a payment is found for the IPN info, it is saved.
178
-     *
179
-     * @param array              $_req_data            eg $_REQUEST
180
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
181
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
182
-     * @param boolean            $update_txn           whether or not to call
183
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
184
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
185
-     *                                                 or is processed manually ( false like Mijireh )
186
-     * @throws EE_Error
187
-     * @throws Exception
188
-     * @return EE_Payment
189
-     */
190
-    public function process_ipn(
191
-        $_req_data,
192
-        $transaction = null,
193
-        $payment_method = null,
194
-        $update_txn = true,
195
-        $separate_IPN_request = true
196
-    ) {
197
-        EE_Registry::instance()->load_model('Change_Log');
198
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
199
-        EE_Processor_Base::set_IPN($separate_IPN_request);
200
-        $obj_for_log = null;
201
-        if ($transaction instanceof EE_Transaction) {
202
-            $obj_for_log = $transaction;
203
-            if ($payment_method instanceof EE_Payment_Method) {
204
-                $obj_for_log = EEM_Payment::instance()->get_one(
205
-                    array(
206
-                        array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
207
-                        'order_by' => array('PAY_timestamp' => 'desc'),
208
-                    )
209
-                );
210
-            }
211
-        } else if ($payment_method instanceof EE_Payment) {
212
-            $obj_for_log = $payment_method;
213
-        }
214
-        $log = EEM_Change_Log::instance()->log(
215
-            EEM_Change_Log::type_gateway,
216
-            array('IPN data received' => $_req_data),
217
-            $obj_for_log
218
-        );
219
-        try {
220
-            /**
221
-             * @var EE_Payment $payment
222
-             */
223
-            $payment = null;
224
-            if ($transaction && $payment_method) {
225
-                /** @type EE_Transaction $transaction */
226
-                $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
227
-                /** @type EE_Payment_Method $payment_method */
228
-                $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
229
-                if ($payment_method->type_obj() instanceof EE_PMT_Base) {
230
-                    try {
231
-                        $payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
232
-                        $log->set_object($payment);
233
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
234
-                        EEM_Change_Log::instance()->log(
235
-                            EEM_Change_Log::type_gateway,
236
-                            array(
237
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
238
-                                'current_url' => EEH_URL::current_url(),
239
-                                'payment'     => $e->getPaymentProperties(),
240
-                                'IPN_data'    => $e->getIpnData(),
241
-                            ),
242
-                            $obj_for_log
243
-                        );
244
-                        return $e->getPayment();
245
-                    }
246
-                } else {
247
-                    // not a payment
248
-                    EE_Error::add_error(
249
-                        sprintf(
250
-                            __('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
251
-                            '<br/>',
252
-                            EE_Registry::instance()->CFG->organization->get_pretty('email')
253
-                        ),
254
-                        __FILE__, __FUNCTION__, __LINE__
255
-                    );
256
-                }
257
-            } else {
258
-                //that's actually pretty ok. The IPN just wasn't able
259
-                //to identify which transaction or payment method this was for
260
-                // give all active payment methods a chance to claim it
261
-                $active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
262
-                foreach ($active_payment_methods as $active_payment_method) {
263
-                    try {
264
-                        $payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
265
-                        $payment_method = $active_payment_method;
266
-                        EEM_Change_Log::instance()->log(
267
-                            EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
268
-                        );
269
-                        break;
270
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
271
-                        EEM_Change_Log::instance()->log(
272
-                            EEM_Change_Log::type_gateway,
273
-                            array(
274
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
275
-                                'current_url' => EEH_URL::current_url(),
276
-                                'payment'     => $e->getPaymentProperties(),
277
-                                'IPN_data'    => $e->getIpnData(),
278
-                            ),
279
-                            $obj_for_log
280
-                        );
281
-                        return $e->getPayment();
282
-                    } catch (EE_Error $e) {
283
-                        //that's fine- it apparently couldn't handle the IPN
284
-                    }
285
-                }
286
-            }
287
-            // 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
288
-            if ($payment instanceof EE_Payment) {
289
-                $payment->save();
290
-                //  update the TXN
291
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
292
-            } else {
293
-                //we couldn't find the payment for this IPN... let's try and log at least SOMETHING
294
-                if ($payment_method) {
295
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
296
-                } elseif ($transaction) {
297
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
298
-                }
299
-            }
300
-            return $payment;
301
-        } catch (EE_Error $e) {
302
-            do_action(
303
-                'AHEE__log', __FILE__, __FUNCTION__, sprintf(
304
-                    __('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
305
-                    print_r($transaction, true),
306
-                    print_r($_req_data, true),
307
-                    $e->getMessage()
308
-                )
309
-            );
310
-            throw $e;
311
-        }
312
-    }
313
-
314
-
315
-
316
-    /**
317
-     * Removes any non-printable illegal characters from the input,
318
-     * which might cause a raucous when trying to insert into the database
319
-     *
320
-     * @param  array $request_data
321
-     * @return array
322
-     */
323
-    protected function _remove_unusable_characters_from_array(array $request_data)
324
-    {
325
-        $return_data = array();
326
-        foreach ($request_data as $key => $value) {
327
-            $return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
328
-        }
329
-        return $return_data;
330
-    }
331
-
332
-
333
-
334
-    /**
335
-     * Removes any non-printable illegal characters from the input,
336
-     * which might cause a raucous when trying to insert into the database
337
-     *
338
-     * @param string $request_data
339
-     * @return string
340
-     */
341
-    protected function _remove_unusable_characters($request_data)
342
-    {
343
-        return preg_replace('/[^[:print:]]/', '', $request_data);
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * Should be called just before displaying the payment attempt results to the user,
350
-     * when the payment attempt has finished. Some payment methods may have special
351
-     * logic to perform here. For example, if process_payment() happens on a special request
352
-     * and then the user is redirected to a page that displays the payment's status, this
353
-     * should be called while loading the page that displays the payment's status. If the user is
354
-     * sent to an offsite payment provider, this should be called upon returning from that offsite payment
355
-     * provider.
356
-     *
357
-     * @param EE_Transaction|int $transaction
358
-     * @param bool               $update_txn whether or not to call
359
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
360
-     * @throws \EE_Error
361
-     * @return EE_Payment
362
-     * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
363
-     *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
364
-     */
365
-    public function finalize_payment_for($transaction, $update_txn = true)
366
-    {
367
-        /** @var $transaction EE_Transaction */
368
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
369
-        $last_payment_method = $transaction->payment_method();
370
-        if ($last_payment_method instanceof EE_Payment_Method) {
371
-            $payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
372
-            $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
373
-            return $payment;
374
-        } else {
375
-            return null;
376
-        }
377
-    }
378
-
379
-
380
-
381
-    /**
382
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
383
-     *
384
-     * @param EE_Payment_Method $payment_method
385
-     * @param EE_Payment        $payment_to_refund
386
-     * @param array             $refund_info
387
-     * @return EE_Payment
388
-     * @throws \EE_Error
389
-     */
390
-    public function process_refund(
391
-        EE_Payment_Method $payment_method,
392
-        EE_Payment $payment_to_refund,
393
-        $refund_info = array()
394
-    ) {
395
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
396
-            $payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
397
-            $this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
398
-        }
399
-        return $payment_to_refund;
400
-    }
401
-
402
-
403
-
404
-    /**
405
-     * This should be called each time there may have been an update to a
406
-     * payment on a transaction (ie, we asked for a payment to process a
407
-     * payment for a transaction, or we told a payment method about an IPN, or
408
-     * we told a payment method to
409
-     * "finalize_payment_for" (a transaction), or we told a payment method to
410
-     * process a refund. This should handle firing the correct hooks to
411
-     * indicate
412
-     * what exactly happened and updating the transaction appropriately). This
413
-     * could be integrated directly into EE_Transaction upon save, but we want
414
-     * this logic to be separate from 'normal' plain-jane saving and updating
415
-     * of transactions and payments, and to be tied to payment processing.
416
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
417
-     * of previous code to decide whether or not to save (because the payment passed into
418
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
419
-     * in which case we only want that payment object for some temporary usage during this request,
420
-     * but we don't want it to be saved).
421
-     *
422
-     * @param EE_Transaction|int $transaction
423
-     * @param EE_Payment         $payment
424
-     * @param boolean            $update_txn
425
-     *                        whether or not to call
426
-     *                        EE_Transaction_Processor::
427
-     *                        update_transaction_and_registrations_after_checkout_or_payment()
428
-     *                        (you can save 1 DB query if you know you're going
429
-     *                        to save it later instead)
430
-     * @param bool               $IPN
431
-     *                        if processing IPNs or other similar payment
432
-     *                        related activities that occur in alternate
433
-     *                        requests than the main one that is processing the
434
-     *                        TXN, then set this to true to check whether the
435
-     *                        TXN is locked before updating
436
-     * @throws \EE_Error
437
-     */
438
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
439
-    {
440
-        $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
441
-        /** @type EE_Transaction $transaction */
442
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
443
-        // can we freely update the TXN at this moment?
444
-        if ($IPN && $transaction->is_locked()) {
445
-            // don't update the transaction at this exact moment
446
-            // because the TXN is active in another request
447
-            EE_Cron_Tasks::schedule_update_transaction_with_payment(
448
-                time(),
449
-                $transaction->ID(),
450
-                $payment->ID()
451
-            );
452
-        } else {
453
-            // verify payment and that it has been saved
454
-            if ($payment instanceof EE_Payment && $payment->ID()) {
455
-                if (
456
-                    $payment->payment_method() instanceof EE_Payment_Method
457
-                    && $payment->payment_method()->type_obj() instanceof EE_PMT_Base
458
-                ) {
459
-                    $payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
460
-                    // update TXN registrations with payment info
461
-                    $this->process_registration_payments($transaction, $payment);
462
-                }
463
-                $do_action = $payment->just_approved()
464
-                    ? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
465
-                    : $do_action;
466
-            } else {
467
-                // send out notifications
468
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
469
-                $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
470
-            }
471
-            if ($payment->status() !== EEM_Payment::status_id_failed) {
472
-                /** @type EE_Transaction_Payments $transaction_payments */
473
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
474
-                // set new value for total paid
475
-                $transaction_payments->calculate_total_payments_and_update_status($transaction);
476
-                // call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
477
-                if ($update_txn) {
478
-                    $this->_post_payment_processing($transaction, $payment, $IPN);
479
-                }
480
-            }
481
-            // granular hook for others to use.
482
-            do_action($do_action, $transaction, $payment);
483
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
484
-            //global hook for others to use.
485
-            do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
486
-        }
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * update registrations REG_paid field after successful payment and link registrations with payment
493
-     *
494
-     * @param EE_Transaction    $transaction
495
-     * @param EE_Payment        $payment
496
-     * @param EE_Registration[] $registrations
497
-     * @throws \EE_Error
498
-     */
499
-    public function process_registration_payments(
500
-        EE_Transaction $transaction,
501
-        EE_Payment $payment,
502
-        $registrations = array()
503
-    ) {
504
-        // only process if payment was successful
505
-        if ($payment->status() !== EEM_Payment::status_id_approved) {
506
-            return;
507
-        }
508
-        //EEM_Registration::instance()->show_next_x_db_queries();
509
-        if (empty($registrations)) {
510
-            // find registrations with monies owing that can receive a payment
511
-            $registrations = $transaction->registrations(
512
-                array(
513
-                    array(
514
-                        // only these reg statuses can receive payments
515
-                        'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
516
-                        'REG_final_price'  => array('!=', 0),
517
-                        'REG_final_price*' => array('!=', 'REG_paid', true),
518
-                    ),
519
-                )
520
-            );
521
-        }
522
-        // still nothing ??!??
523
-        if (empty($registrations)) {
524
-            return;
525
-        }
526
-        // todo: break out the following logic into a separate strategy class
527
-        // todo: named something like "Sequential_Reg_Payment_Strategy"
528
-        // todo: which would apply payments using the capitalist "first come first paid" approach
529
-        // todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
530
-        // todo: which would be the socialist "everybody gets a piece of pie" approach,
531
-        // todo: which would be better for deposits, where you want a bit of the payment applied to each registration
532
-        $refund = $payment->is_a_refund();
533
-        // how much is available to apply to registrations?
534
-        $available_payment_amount = abs($payment->amount());
535
-        foreach ($registrations as $registration) {
536
-            if ($registration instanceof EE_Registration) {
537
-                // nothing left?
538
-                if ($available_payment_amount <= 0) {
539
-                    break;
540
-                }
541
-                if ($refund) {
542
-                    $available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
543
-                } else {
544
-                    $available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
545
-                }
546
-            }
547
-        }
548
-        if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
549
-            EE_Error::add_attention(
550
-                sprintf(
551
-                    __('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
552
-                        'event_espresso'),
553
-                    EEH_Template::format_currency($available_payment_amount),
554
-                    implode(', ', array_keys($registrations)),
555
-                    '<br/>',
556
-                    EEH_Template::format_currency($payment->amount())
557
-                ),
558
-                __FILE__, __FUNCTION__, __LINE__
559
-            );
560
-        }
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     * update registration REG_paid field after successful payment and link registration with payment
567
-     *
568
-     * @param EE_Registration $registration
569
-     * @param EE_Payment      $payment
570
-     * @param float           $available_payment_amount
571
-     * @return float
572
-     * @throws \EE_Error
573
-     */
574
-    public function process_registration_payment(EE_Registration $registration, EE_Payment $payment, $available_payment_amount = 0.00)
575
-    {
576
-        $owing = $registration->final_price() - $registration->paid();
577
-        if ($owing > 0) {
578
-            // don't allow payment amount to exceed the available payment amount, OR the amount owing
579
-            $payment_amount = min($available_payment_amount, $owing);
580
-            // update $available_payment_amount
581
-            $available_payment_amount -= $payment_amount;
582
-            //calculate and set new REG_paid
583
-            $registration->set_paid($registration->paid() + $payment_amount);
584
-            // now save it
585
-            $this->_apply_registration_payment($registration, $payment, $payment_amount);
586
-        }
587
-        return $available_payment_amount;
588
-    }
589
-
590
-
591
-
592
-    /**
593
-     * update registration REG_paid field after successful payment and link registration with payment
594
-     *
595
-     * @param EE_Registration $registration
596
-     * @param EE_Payment      $payment
597
-     * @param float           $payment_amount
598
-     * @return void
599
-     * @throws \EE_Error
600
-     */
601
-    protected function _apply_registration_payment(EE_Registration $registration, EE_Payment $payment, $payment_amount = 0.00)
602
-    {
603
-        // find any existing reg payment records for this registration and payment
604
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
605
-            array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
606
-        );
607
-        // if existing registration payment exists
608
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
609
-            // then update that record
610
-            $existing_reg_payment->set_amount($payment_amount);
611
-            $existing_reg_payment->save();
612
-        } else {
613
-            // or add new relation between registration and payment and set amount
614
-            $registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
615
-            // make it stick
616
-            $registration->save();
617
-        }
618
-    }
619
-
620
-
621
-
622
-    /**
623
-     * update registration REG_paid field after refund and link registration with payment
624
-     *
625
-     * @param EE_Registration $registration
626
-     * @param EE_Payment      $payment
627
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
628
-     * @return float
629
-     * @throws \EE_Error
630
-     */
631
-    public function process_registration_refund(EE_Registration $registration, EE_Payment $payment, $available_refund_amount = 0.00)
632
-    {
633
-        //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
634
-        if ($registration->paid() > 0) {
635
-            // ensure $available_refund_amount is NOT negative
636
-            $available_refund_amount = (float)abs($available_refund_amount);
637
-            // don't allow refund amount to exceed the available payment amount, OR the amount paid
638
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
639
-            // update $available_payment_amount
640
-            $available_refund_amount -= $refund_amount;
641
-            //calculate and set new REG_paid
642
-            $registration->set_paid($registration->paid() - $refund_amount);
643
-            // convert payment amount back to a negative value for storage in the db
644
-            $refund_amount = (float)abs($refund_amount) * -1;
645
-            // now save it
646
-            $this->_apply_registration_payment($registration, $payment, $refund_amount);
647
-        }
648
-        return $available_refund_amount;
649
-    }
650
-
651
-
652
-
653
-    /**
654
-     * Process payments and transaction after payment process completed.
655
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
656
-     * if this request happens to be processing an IPN,
657
-     * then we will also set the Payment Options Reg Step to completed,
658
-     * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
659
-     *
660
-     * @param EE_Transaction $transaction
661
-     * @param EE_Payment     $payment
662
-     * @param bool           $IPN
663
-     * @throws \EE_Error
664
-     */
665
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
666
-    {
667
-        /** @type EE_Transaction_Processor $transaction_processor */
668
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
669
-        // is the Payment Options Reg Step completed ?
670
-        $payment_options_step_completed = $transaction->reg_step_completed('payment_options');
671
-        // if the Payment Options Reg Step is completed...
672
-        $revisit = $payment_options_step_completed === true ? true : false;
673
-        // then this is kinda sorta a revisit with regards to payments at least
674
-        $transaction_processor->set_revisit($revisit);
675
-        // if this is an IPN, let's consider the Payment Options Reg Step completed if not already
676
-        if (
677
-            $IPN
678
-            && $payment_options_step_completed !== true
679
-            && ($payment->is_approved() || $payment->is_pending())
680
-        ) {
681
-            $payment_options_step_completed = $transaction->set_reg_step_completed(
682
-                'payment_options'
683
-            );
684
-        }
685
-        // maybe update status, but don't save transaction just yet
686
-        $transaction->update_status_based_on_total_paid(false);
687
-        // check if 'finalize_registration' step has been completed...
688
-        $finalized = $transaction->reg_step_completed('finalize_registration');
689
-        //  if this is an IPN and the final step has not been initiated
690
-        if ($IPN && $payment_options_step_completed && $finalized === false) {
691
-            // and if it hasn't already been set as being started...
692
-            $finalized = $transaction->set_reg_step_initiated('finalize_registration');
693
-        }
694
-        $transaction->save();
695
-        // because the above will return false if the final step was not fully completed, we need to check again...
696
-        if ($IPN && $finalized !== false) {
697
-            // and if we are all good to go, then send out notifications
698
-            add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
699
-            //ok, now process the transaction according to the payment
700
-            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
701
-        }
702
-        // DEBUG LOG
703
-        $payment_method = $payment->payment_method();
704
-        if ($payment_method instanceof EE_Payment_Method) {
705
-            $payment_method_type_obj = $payment_method->type_obj();
706
-            if ($payment_method_type_obj instanceof EE_PMT_Base) {
707
-                $gateway = $payment_method_type_obj->get_gateway();
708
-                if ($gateway instanceof EE_Gateway) {
709
-                    $gateway->log(
710
-                        array(
711
-                            'message'               => __('Post Payment Transaction Details', 'event_espresso'),
712
-                            'transaction'           => $transaction->model_field_array(),
713
-                            'finalized'             => $finalized,
714
-                            'IPN'                   => $IPN,
715
-                            'deliver_notifications' => has_filter(
716
-                                'FHEE__EED_Messages___maybe_registration__deliver_notifications'
717
-                            ),
718
-                        ),
719
-                        $payment
720
-                    );
721
-                }
722
-            }
723
-        }
724
-    }
725
-
726
-
727
-
728
-    /**
729
-     * Force posts to PayPal to use TLS v1.2. See:
730
-     * https://core.trac.wordpress.org/ticket/36320
731
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
732
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
733
-     * This will affect paypal standard, pro, express, and payflow.
734
-     */
735
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
736
-    {
737
-        if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
738
-            //Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
739
-            //instead of the constant because it might not be defined
740
-            curl_setopt($handle, CURLOPT_SSLVERSION, 1);
741
-        }
742
-    }
19
+	/**
20
+	 * @var EE_Payment_Processor $_instance
21
+	 * @access    private
22
+	 */
23
+	private static $_instance;
24
+
25
+
26
+
27
+	/**
28
+	 * @singleton method used to instantiate class object
29
+	 * @access    public
30
+	 * @return EE_Payment_Processor instance
31
+	 */
32
+	public static function instance()
33
+	{
34
+		// check if class object is instantiated
35
+		if ( ! self::$_instance instanceof EE_Payment_Processor) {
36
+			self::$_instance = new self();
37
+		}
38
+		return self::$_instance;
39
+	}
40
+
41
+
42
+
43
+	/**
44
+	 *private constructor to prevent direct creation
45
+	 *
46
+	 * @Constructor
47
+	 * @access private
48
+	 */
49
+	private function __construct()
50
+	{
51
+		do_action('AHEE__EE_Payment_Processor__construct');
52
+		add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction appropriately.
59
+	 * Saves the payment that is generated
60
+	 *
61
+	 * @param EE_Payment_Method    $payment_method
62
+	 * @param EE_Transaction       $transaction
63
+	 * @param float                $amount       if only part of the transaction is to be paid for, how much.
64
+	 *                                           Leave null if payment is for the full amount owing
65
+	 * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
66
+	 *                                           Receive_form_submission() should have
67
+	 *                                           already been called on the billing form
68
+	 *                                           (ie, its inputs should have their normalized values set).
69
+	 * @param string               $return_url   string used mostly by offsite gateways to specify
70
+	 *                                           where to go AFTER the offsite gateway
71
+	 * @param string               $method       like 'CART', indicates who the client who called this was
72
+	 * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
73
+	 * @param boolean              $update_txn   whether or not to call
74
+	 *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
75
+	 * @param string               $cancel_url   URL to return to if off-site payments are cancelled
76
+	 * @return \EE_Payment
77
+	 * @throws \EE_Error
78
+	 */
79
+	public function process_payment(
80
+		EE_Payment_Method $payment_method,
81
+		EE_Transaction $transaction,
82
+		$amount = null,
83
+		$billing_form = null,
84
+		$return_url = null,
85
+		$method = 'CART',
86
+		$by_admin = false,
87
+		$update_txn = true,
88
+		$cancel_url = ''
89
+	) {
90
+		if ((float)$amount < 0) {
91
+			throw new EE_Error(
92
+				sprintf(
93
+					__(
94
+						'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
95
+						'event_espresso'
96
+					),
97
+					$amount,
98
+					$transaction->ID()
99
+				)
100
+			);
101
+		}
102
+		// verify payment method
103
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
104
+		// verify transaction
105
+		EEM_Transaction::instance()->ensure_is_obj($transaction);
106
+		$transaction->set_payment_method_ID($payment_method->ID());
107
+		// verify payment method type
108
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109
+			$payment = $payment_method->type_obj()->process_payment(
110
+				$transaction,
111
+				min($amount, $transaction->remaining()),//make sure we don't overcharge
112
+				$billing_form,
113
+				$return_url,
114
+				add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
115
+				$method,
116
+				$by_admin
117
+			);
118
+			// check if payment method uses an off-site gateway
119
+			if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
120
+				// don't process payments for off-site gateways yet because no payment has occurred yet
121
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
122
+			}
123
+			return $payment;
124
+		} else {
125
+			EE_Error::add_error(
126
+				sprintf(
127
+					__('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
128
+					'<br/>',
129
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
130
+				), __FILE__, __FUNCTION__, __LINE__
131
+			);
132
+			return null;
133
+		}
134
+	}
135
+
136
+
137
+
138
+	/**
139
+	 * @param EE_Transaction|int $transaction
140
+	 * @param EE_Payment_Method  $payment_method
141
+	 * @throws EE_Error
142
+	 * @return string
143
+	 */
144
+	public function get_ipn_url_for_payment_method($transaction, $payment_method)
145
+	{
146
+		/** @type \EE_Transaction $transaction */
147
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
148
+		$primary_reg = $transaction->primary_registration();
149
+		if ( ! $primary_reg instanceof EE_Registration) {
150
+			throw new EE_Error(
151
+				sprintf(
152
+					__(
153
+						"Cannot get IPN URL for transaction with ID %d because it has no primary registration",
154
+						"event_espresso"
155
+					),
156
+					$transaction->ID()
157
+				)
158
+			);
159
+		}
160
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
161
+		$url = add_query_arg(
162
+			array(
163
+				'e_reg_url_link'    => $primary_reg->reg_url_link(),
164
+				'ee_payment_method' => $payment_method->slug(),
165
+			),
166
+			EE_Registry::instance()->CFG->core->txn_page_url()
167
+		);
168
+		return $url;
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
175
+	 * we can easily find what registration the IPN is for and what payment method.
176
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
177
+	 * If a payment is found for the IPN info, it is saved.
178
+	 *
179
+	 * @param array              $_req_data            eg $_REQUEST
180
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
181
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
182
+	 * @param boolean            $update_txn           whether or not to call
183
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
184
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
185
+	 *                                                 or is processed manually ( false like Mijireh )
186
+	 * @throws EE_Error
187
+	 * @throws Exception
188
+	 * @return EE_Payment
189
+	 */
190
+	public function process_ipn(
191
+		$_req_data,
192
+		$transaction = null,
193
+		$payment_method = null,
194
+		$update_txn = true,
195
+		$separate_IPN_request = true
196
+	) {
197
+		EE_Registry::instance()->load_model('Change_Log');
198
+		$_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
199
+		EE_Processor_Base::set_IPN($separate_IPN_request);
200
+		$obj_for_log = null;
201
+		if ($transaction instanceof EE_Transaction) {
202
+			$obj_for_log = $transaction;
203
+			if ($payment_method instanceof EE_Payment_Method) {
204
+				$obj_for_log = EEM_Payment::instance()->get_one(
205
+					array(
206
+						array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
207
+						'order_by' => array('PAY_timestamp' => 'desc'),
208
+					)
209
+				);
210
+			}
211
+		} else if ($payment_method instanceof EE_Payment) {
212
+			$obj_for_log = $payment_method;
213
+		}
214
+		$log = EEM_Change_Log::instance()->log(
215
+			EEM_Change_Log::type_gateway,
216
+			array('IPN data received' => $_req_data),
217
+			$obj_for_log
218
+		);
219
+		try {
220
+			/**
221
+			 * @var EE_Payment $payment
222
+			 */
223
+			$payment = null;
224
+			if ($transaction && $payment_method) {
225
+				/** @type EE_Transaction $transaction */
226
+				$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
227
+				/** @type EE_Payment_Method $payment_method */
228
+				$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
229
+				if ($payment_method->type_obj() instanceof EE_PMT_Base) {
230
+					try {
231
+						$payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
232
+						$log->set_object($payment);
233
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
234
+						EEM_Change_Log::instance()->log(
235
+							EEM_Change_Log::type_gateway,
236
+							array(
237
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
238
+								'current_url' => EEH_URL::current_url(),
239
+								'payment'     => $e->getPaymentProperties(),
240
+								'IPN_data'    => $e->getIpnData(),
241
+							),
242
+							$obj_for_log
243
+						);
244
+						return $e->getPayment();
245
+					}
246
+				} else {
247
+					// not a payment
248
+					EE_Error::add_error(
249
+						sprintf(
250
+							__('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
251
+							'<br/>',
252
+							EE_Registry::instance()->CFG->organization->get_pretty('email')
253
+						),
254
+						__FILE__, __FUNCTION__, __LINE__
255
+					);
256
+				}
257
+			} else {
258
+				//that's actually pretty ok. The IPN just wasn't able
259
+				//to identify which transaction or payment method this was for
260
+				// give all active payment methods a chance to claim it
261
+				$active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
262
+				foreach ($active_payment_methods as $active_payment_method) {
263
+					try {
264
+						$payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
265
+						$payment_method = $active_payment_method;
266
+						EEM_Change_Log::instance()->log(
267
+							EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
268
+						);
269
+						break;
270
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
271
+						EEM_Change_Log::instance()->log(
272
+							EEM_Change_Log::type_gateway,
273
+							array(
274
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
275
+								'current_url' => EEH_URL::current_url(),
276
+								'payment'     => $e->getPaymentProperties(),
277
+								'IPN_data'    => $e->getIpnData(),
278
+							),
279
+							$obj_for_log
280
+						);
281
+						return $e->getPayment();
282
+					} catch (EE_Error $e) {
283
+						//that's fine- it apparently couldn't handle the IPN
284
+					}
285
+				}
286
+			}
287
+			// 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
288
+			if ($payment instanceof EE_Payment) {
289
+				$payment->save();
290
+				//  update the TXN
291
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
292
+			} else {
293
+				//we couldn't find the payment for this IPN... let's try and log at least SOMETHING
294
+				if ($payment_method) {
295
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
296
+				} elseif ($transaction) {
297
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
298
+				}
299
+			}
300
+			return $payment;
301
+		} catch (EE_Error $e) {
302
+			do_action(
303
+				'AHEE__log', __FILE__, __FUNCTION__, sprintf(
304
+					__('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
305
+					print_r($transaction, true),
306
+					print_r($_req_data, true),
307
+					$e->getMessage()
308
+				)
309
+			);
310
+			throw $e;
311
+		}
312
+	}
313
+
314
+
315
+
316
+	/**
317
+	 * Removes any non-printable illegal characters from the input,
318
+	 * which might cause a raucous when trying to insert into the database
319
+	 *
320
+	 * @param  array $request_data
321
+	 * @return array
322
+	 */
323
+	protected function _remove_unusable_characters_from_array(array $request_data)
324
+	{
325
+		$return_data = array();
326
+		foreach ($request_data as $key => $value) {
327
+			$return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
328
+		}
329
+		return $return_data;
330
+	}
331
+
332
+
333
+
334
+	/**
335
+	 * Removes any non-printable illegal characters from the input,
336
+	 * which might cause a raucous when trying to insert into the database
337
+	 *
338
+	 * @param string $request_data
339
+	 * @return string
340
+	 */
341
+	protected function _remove_unusable_characters($request_data)
342
+	{
343
+		return preg_replace('/[^[:print:]]/', '', $request_data);
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * Should be called just before displaying the payment attempt results to the user,
350
+	 * when the payment attempt has finished. Some payment methods may have special
351
+	 * logic to perform here. For example, if process_payment() happens on a special request
352
+	 * and then the user is redirected to a page that displays the payment's status, this
353
+	 * should be called while loading the page that displays the payment's status. If the user is
354
+	 * sent to an offsite payment provider, this should be called upon returning from that offsite payment
355
+	 * provider.
356
+	 *
357
+	 * @param EE_Transaction|int $transaction
358
+	 * @param bool               $update_txn whether or not to call
359
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
360
+	 * @throws \EE_Error
361
+	 * @return EE_Payment
362
+	 * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
363
+	 *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
364
+	 */
365
+	public function finalize_payment_for($transaction, $update_txn = true)
366
+	{
367
+		/** @var $transaction EE_Transaction */
368
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
369
+		$last_payment_method = $transaction->payment_method();
370
+		if ($last_payment_method instanceof EE_Payment_Method) {
371
+			$payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
372
+			$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
373
+			return $payment;
374
+		} else {
375
+			return null;
376
+		}
377
+	}
378
+
379
+
380
+
381
+	/**
382
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
383
+	 *
384
+	 * @param EE_Payment_Method $payment_method
385
+	 * @param EE_Payment        $payment_to_refund
386
+	 * @param array             $refund_info
387
+	 * @return EE_Payment
388
+	 * @throws \EE_Error
389
+	 */
390
+	public function process_refund(
391
+		EE_Payment_Method $payment_method,
392
+		EE_Payment $payment_to_refund,
393
+		$refund_info = array()
394
+	) {
395
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
396
+			$payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
397
+			$this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
398
+		}
399
+		return $payment_to_refund;
400
+	}
401
+
402
+
403
+
404
+	/**
405
+	 * This should be called each time there may have been an update to a
406
+	 * payment on a transaction (ie, we asked for a payment to process a
407
+	 * payment for a transaction, or we told a payment method about an IPN, or
408
+	 * we told a payment method to
409
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
410
+	 * process a refund. This should handle firing the correct hooks to
411
+	 * indicate
412
+	 * what exactly happened and updating the transaction appropriately). This
413
+	 * could be integrated directly into EE_Transaction upon save, but we want
414
+	 * this logic to be separate from 'normal' plain-jane saving and updating
415
+	 * of transactions and payments, and to be tied to payment processing.
416
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
417
+	 * of previous code to decide whether or not to save (because the payment passed into
418
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
419
+	 * in which case we only want that payment object for some temporary usage during this request,
420
+	 * but we don't want it to be saved).
421
+	 *
422
+	 * @param EE_Transaction|int $transaction
423
+	 * @param EE_Payment         $payment
424
+	 * @param boolean            $update_txn
425
+	 *                        whether or not to call
426
+	 *                        EE_Transaction_Processor::
427
+	 *                        update_transaction_and_registrations_after_checkout_or_payment()
428
+	 *                        (you can save 1 DB query if you know you're going
429
+	 *                        to save it later instead)
430
+	 * @param bool               $IPN
431
+	 *                        if processing IPNs or other similar payment
432
+	 *                        related activities that occur in alternate
433
+	 *                        requests than the main one that is processing the
434
+	 *                        TXN, then set this to true to check whether the
435
+	 *                        TXN is locked before updating
436
+	 * @throws \EE_Error
437
+	 */
438
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
439
+	{
440
+		$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
441
+		/** @type EE_Transaction $transaction */
442
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
443
+		// can we freely update the TXN at this moment?
444
+		if ($IPN && $transaction->is_locked()) {
445
+			// don't update the transaction at this exact moment
446
+			// because the TXN is active in another request
447
+			EE_Cron_Tasks::schedule_update_transaction_with_payment(
448
+				time(),
449
+				$transaction->ID(),
450
+				$payment->ID()
451
+			);
452
+		} else {
453
+			// verify payment and that it has been saved
454
+			if ($payment instanceof EE_Payment && $payment->ID()) {
455
+				if (
456
+					$payment->payment_method() instanceof EE_Payment_Method
457
+					&& $payment->payment_method()->type_obj() instanceof EE_PMT_Base
458
+				) {
459
+					$payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
460
+					// update TXN registrations with payment info
461
+					$this->process_registration_payments($transaction, $payment);
462
+				}
463
+				$do_action = $payment->just_approved()
464
+					? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
465
+					: $do_action;
466
+			} else {
467
+				// send out notifications
468
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
469
+				$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
470
+			}
471
+			if ($payment->status() !== EEM_Payment::status_id_failed) {
472
+				/** @type EE_Transaction_Payments $transaction_payments */
473
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
474
+				// set new value for total paid
475
+				$transaction_payments->calculate_total_payments_and_update_status($transaction);
476
+				// call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
477
+				if ($update_txn) {
478
+					$this->_post_payment_processing($transaction, $payment, $IPN);
479
+				}
480
+			}
481
+			// granular hook for others to use.
482
+			do_action($do_action, $transaction, $payment);
483
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
484
+			//global hook for others to use.
485
+			do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
486
+		}
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * update registrations REG_paid field after successful payment and link registrations with payment
493
+	 *
494
+	 * @param EE_Transaction    $transaction
495
+	 * @param EE_Payment        $payment
496
+	 * @param EE_Registration[] $registrations
497
+	 * @throws \EE_Error
498
+	 */
499
+	public function process_registration_payments(
500
+		EE_Transaction $transaction,
501
+		EE_Payment $payment,
502
+		$registrations = array()
503
+	) {
504
+		// only process if payment was successful
505
+		if ($payment->status() !== EEM_Payment::status_id_approved) {
506
+			return;
507
+		}
508
+		//EEM_Registration::instance()->show_next_x_db_queries();
509
+		if (empty($registrations)) {
510
+			// find registrations with monies owing that can receive a payment
511
+			$registrations = $transaction->registrations(
512
+				array(
513
+					array(
514
+						// only these reg statuses can receive payments
515
+						'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
516
+						'REG_final_price'  => array('!=', 0),
517
+						'REG_final_price*' => array('!=', 'REG_paid', true),
518
+					),
519
+				)
520
+			);
521
+		}
522
+		// still nothing ??!??
523
+		if (empty($registrations)) {
524
+			return;
525
+		}
526
+		// todo: break out the following logic into a separate strategy class
527
+		// todo: named something like "Sequential_Reg_Payment_Strategy"
528
+		// todo: which would apply payments using the capitalist "first come first paid" approach
529
+		// todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
530
+		// todo: which would be the socialist "everybody gets a piece of pie" approach,
531
+		// todo: which would be better for deposits, where you want a bit of the payment applied to each registration
532
+		$refund = $payment->is_a_refund();
533
+		// how much is available to apply to registrations?
534
+		$available_payment_amount = abs($payment->amount());
535
+		foreach ($registrations as $registration) {
536
+			if ($registration instanceof EE_Registration) {
537
+				// nothing left?
538
+				if ($available_payment_amount <= 0) {
539
+					break;
540
+				}
541
+				if ($refund) {
542
+					$available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
543
+				} else {
544
+					$available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
545
+				}
546
+			}
547
+		}
548
+		if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
549
+			EE_Error::add_attention(
550
+				sprintf(
551
+					__('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
552
+						'event_espresso'),
553
+					EEH_Template::format_currency($available_payment_amount),
554
+					implode(', ', array_keys($registrations)),
555
+					'<br/>',
556
+					EEH_Template::format_currency($payment->amount())
557
+				),
558
+				__FILE__, __FUNCTION__, __LINE__
559
+			);
560
+		}
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 * update registration REG_paid field after successful payment and link registration with payment
567
+	 *
568
+	 * @param EE_Registration $registration
569
+	 * @param EE_Payment      $payment
570
+	 * @param float           $available_payment_amount
571
+	 * @return float
572
+	 * @throws \EE_Error
573
+	 */
574
+	public function process_registration_payment(EE_Registration $registration, EE_Payment $payment, $available_payment_amount = 0.00)
575
+	{
576
+		$owing = $registration->final_price() - $registration->paid();
577
+		if ($owing > 0) {
578
+			// don't allow payment amount to exceed the available payment amount, OR the amount owing
579
+			$payment_amount = min($available_payment_amount, $owing);
580
+			// update $available_payment_amount
581
+			$available_payment_amount -= $payment_amount;
582
+			//calculate and set new REG_paid
583
+			$registration->set_paid($registration->paid() + $payment_amount);
584
+			// now save it
585
+			$this->_apply_registration_payment($registration, $payment, $payment_amount);
586
+		}
587
+		return $available_payment_amount;
588
+	}
589
+
590
+
591
+
592
+	/**
593
+	 * update registration REG_paid field after successful payment and link registration with payment
594
+	 *
595
+	 * @param EE_Registration $registration
596
+	 * @param EE_Payment      $payment
597
+	 * @param float           $payment_amount
598
+	 * @return void
599
+	 * @throws \EE_Error
600
+	 */
601
+	protected function _apply_registration_payment(EE_Registration $registration, EE_Payment $payment, $payment_amount = 0.00)
602
+	{
603
+		// find any existing reg payment records for this registration and payment
604
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
605
+			array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
606
+		);
607
+		// if existing registration payment exists
608
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
609
+			// then update that record
610
+			$existing_reg_payment->set_amount($payment_amount);
611
+			$existing_reg_payment->save();
612
+		} else {
613
+			// or add new relation between registration and payment and set amount
614
+			$registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
615
+			// make it stick
616
+			$registration->save();
617
+		}
618
+	}
619
+
620
+
621
+
622
+	/**
623
+	 * update registration REG_paid field after refund and link registration with payment
624
+	 *
625
+	 * @param EE_Registration $registration
626
+	 * @param EE_Payment      $payment
627
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
628
+	 * @return float
629
+	 * @throws \EE_Error
630
+	 */
631
+	public function process_registration_refund(EE_Registration $registration, EE_Payment $payment, $available_refund_amount = 0.00)
632
+	{
633
+		//EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
634
+		if ($registration->paid() > 0) {
635
+			// ensure $available_refund_amount is NOT negative
636
+			$available_refund_amount = (float)abs($available_refund_amount);
637
+			// don't allow refund amount to exceed the available payment amount, OR the amount paid
638
+			$refund_amount = min($available_refund_amount, (float)$registration->paid());
639
+			// update $available_payment_amount
640
+			$available_refund_amount -= $refund_amount;
641
+			//calculate and set new REG_paid
642
+			$registration->set_paid($registration->paid() - $refund_amount);
643
+			// convert payment amount back to a negative value for storage in the db
644
+			$refund_amount = (float)abs($refund_amount) * -1;
645
+			// now save it
646
+			$this->_apply_registration_payment($registration, $payment, $refund_amount);
647
+		}
648
+		return $available_refund_amount;
649
+	}
650
+
651
+
652
+
653
+	/**
654
+	 * Process payments and transaction after payment process completed.
655
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
656
+	 * if this request happens to be processing an IPN,
657
+	 * then we will also set the Payment Options Reg Step to completed,
658
+	 * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
659
+	 *
660
+	 * @param EE_Transaction $transaction
661
+	 * @param EE_Payment     $payment
662
+	 * @param bool           $IPN
663
+	 * @throws \EE_Error
664
+	 */
665
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
666
+	{
667
+		/** @type EE_Transaction_Processor $transaction_processor */
668
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
669
+		// is the Payment Options Reg Step completed ?
670
+		$payment_options_step_completed = $transaction->reg_step_completed('payment_options');
671
+		// if the Payment Options Reg Step is completed...
672
+		$revisit = $payment_options_step_completed === true ? true : false;
673
+		// then this is kinda sorta a revisit with regards to payments at least
674
+		$transaction_processor->set_revisit($revisit);
675
+		// if this is an IPN, let's consider the Payment Options Reg Step completed if not already
676
+		if (
677
+			$IPN
678
+			&& $payment_options_step_completed !== true
679
+			&& ($payment->is_approved() || $payment->is_pending())
680
+		) {
681
+			$payment_options_step_completed = $transaction->set_reg_step_completed(
682
+				'payment_options'
683
+			);
684
+		}
685
+		// maybe update status, but don't save transaction just yet
686
+		$transaction->update_status_based_on_total_paid(false);
687
+		// check if 'finalize_registration' step has been completed...
688
+		$finalized = $transaction->reg_step_completed('finalize_registration');
689
+		//  if this is an IPN and the final step has not been initiated
690
+		if ($IPN && $payment_options_step_completed && $finalized === false) {
691
+			// and if it hasn't already been set as being started...
692
+			$finalized = $transaction->set_reg_step_initiated('finalize_registration');
693
+		}
694
+		$transaction->save();
695
+		// because the above will return false if the final step was not fully completed, we need to check again...
696
+		if ($IPN && $finalized !== false) {
697
+			// and if we are all good to go, then send out notifications
698
+			add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
699
+			//ok, now process the transaction according to the payment
700
+			$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
701
+		}
702
+		// DEBUG LOG
703
+		$payment_method = $payment->payment_method();
704
+		if ($payment_method instanceof EE_Payment_Method) {
705
+			$payment_method_type_obj = $payment_method->type_obj();
706
+			if ($payment_method_type_obj instanceof EE_PMT_Base) {
707
+				$gateway = $payment_method_type_obj->get_gateway();
708
+				if ($gateway instanceof EE_Gateway) {
709
+					$gateway->log(
710
+						array(
711
+							'message'               => __('Post Payment Transaction Details', 'event_espresso'),
712
+							'transaction'           => $transaction->model_field_array(),
713
+							'finalized'             => $finalized,
714
+							'IPN'                   => $IPN,
715
+							'deliver_notifications' => has_filter(
716
+								'FHEE__EED_Messages___maybe_registration__deliver_notifications'
717
+							),
718
+						),
719
+						$payment
720
+					);
721
+				}
722
+			}
723
+		}
724
+	}
725
+
726
+
727
+
728
+	/**
729
+	 * Force posts to PayPal to use TLS v1.2. See:
730
+	 * https://core.trac.wordpress.org/ticket/36320
731
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
732
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
733
+	 * This will affect paypal standard, pro, express, and payflow.
734
+	 */
735
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
736
+	{
737
+		if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
738
+			//Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
739
+			//instead of the constant because it might not be defined
740
+			curl_setopt($handle, CURLOPT_SSLVERSION, 1);
741
+		}
742
+	}
743 743
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
         $update_txn = true,
88 88
         $cancel_url = ''
89 89
     ) {
90
-        if ((float)$amount < 0) {
90
+        if ((float) $amount < 0) {
91 91
             throw new EE_Error(
92 92
                 sprintf(
93 93
                     __(
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
         if ($payment_method->type_obj() instanceof EE_PMT_Base) {
109 109
             $payment = $payment_method->type_obj()->process_payment(
110 110
                 $transaction,
111
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
111
+                min($amount, $transaction->remaining()), //make sure we don't overcharge
112 112
                 $billing_form,
113 113
                 $return_url,
114 114
                 add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
         $separate_IPN_request = true
196 196
     ) {
197 197
         EE_Registry::instance()->load_model('Change_Log');
198
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
198
+        $_req_data = $this->_remove_unusable_characters_from_array((array) $_req_data);
199 199
         EE_Processor_Base::set_IPN($separate_IPN_request);
200 200
         $obj_for_log = null;
201 201
         if ($transaction instanceof EE_Transaction) {
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
                         EEM_Change_Log::instance()->log(
235 235
                             EEM_Change_Log::type_gateway,
236 236
                             array(
237
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
237
+                                'message'     => 'IPN Exception: '.$e->getMessage(),
238 238
                                 'current_url' => EEH_URL::current_url(),
239 239
                                 'payment'     => $e->getPaymentProperties(),
240 240
                                 'IPN_data'    => $e->getIpnData(),
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
                         EEM_Change_Log::instance()->log(
272 272
                             EEM_Change_Log::type_gateway,
273 273
                             array(
274
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
274
+                                'message'     => 'IPN Exception: '.$e->getMessage(),
275 275
                                 'current_url' => EEH_URL::current_url(),
276 276
                                 'payment'     => $e->getPaymentProperties(),
277 277
                                 'IPN_data'    => $e->getIpnData(),
@@ -633,15 +633,15 @@  discard block
 block discarded – undo
633 633
         //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
634 634
         if ($registration->paid() > 0) {
635 635
             // ensure $available_refund_amount is NOT negative
636
-            $available_refund_amount = (float)abs($available_refund_amount);
636
+            $available_refund_amount = (float) abs($available_refund_amount);
637 637
             // don't allow refund amount to exceed the available payment amount, OR the amount paid
638
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
638
+            $refund_amount = min($available_refund_amount, (float) $registration->paid());
639 639
             // update $available_payment_amount
640 640
             $available_refund_amount -= $refund_amount;
641 641
             //calculate and set new REG_paid
642 642
             $registration->set_paid($registration->paid() - $refund_amount);
643 643
             // convert payment amount back to a negative value for storage in the db
644
-            $refund_amount = (float)abs($refund_amount) * -1;
644
+            $refund_amount = (float) abs($refund_amount) * -1;
645 645
             // now save it
646 646
             $this->_apply_registration_payment($registration, $payment, $refund_amount);
647 647
         }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +5538 added lines, -5538 removed lines patch added patch discarded remove patch
@@ -29,5546 +29,5546 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    //admin posty
33
-    //basic -> grants access to mine -> if they don't have it, select none
34
-    //*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
-    //*_published -> grants access to published -> if they dont have it, select non-published
37
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
39
-    //frontend posty
40
-    //by default has access to published
41
-    //basic -> grants access to mine that arent published, and all published
42
-    //*_others ->grants access to others that arent private, all mine
43
-    //*_private -> grants full access
44
-    //frontend non-posty
45
-    //like admin posty
46
-    //category-y
47
-    //assign -> grants access to join-table
48
-    //(delete, edit)
49
-    //payment-method-y
50
-    //for each registered payment method,
51
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
-    /**
53
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
-     * They almost always WILL NOT, but it's not necessarily a requirement.
56
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_values_already_prepared_by_model_object = 0;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the data is just like form input that needs to have the model fields'
65
-     * prepare_for_set and prepare_for_use_in_db called on it
66
-     */
67
-    const not_prepared_by_model_object = 0;
68
-
69
-    /**
70
-     * when $_values_already_prepared_by_model_object equals this, we
71
-     * assume this value is coming from a model object and doesn't need to have
72
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
73
-     */
74
-    const prepared_by_model_object = 1;
75
-
76
-    /**
77
-     * when $_values_already_prepared_by_model_object equals this, we assume
78
-     * the values are already to be used in the database (ie no processing is done
79
-     * on them by the model's fields)
80
-     */
81
-    const prepared_for_use_in_db = 2;
82
-
83
-
84
-    protected $singular_item = 'Item';
85
-
86
-    protected $plural_item   = 'Items';
87
-
88
-    /**
89
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
-     */
91
-    protected $_tables;
92
-
93
-    /**
94
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
-     *
98
-     * @var \EE_Model_Field_Base[] $_fields
99
-     */
100
-    protected $_fields;
101
-
102
-    /**
103
-     * array of different kinds of relations
104
-     *
105
-     * @var \EE_Model_Relation_Base[] $_model_relations
106
-     */
107
-    protected $_model_relations;
108
-
109
-    /**
110
-     * @var \EE_Index[] $_indexes
111
-     */
112
-    protected $_indexes = array();
113
-
114
-    /**
115
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
116
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
-     * by setting the same columns as used in these queries in the query yourself.
118
-     *
119
-     * @var EE_Default_Where_Conditions
120
-     */
121
-    protected $_default_where_conditions_strategy;
122
-
123
-    /**
124
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
-     * This is particularly useful when you want something between 'none' and 'default'
126
-     *
127
-     * @var EE_Default_Where_Conditions
128
-     */
129
-    protected $_minimum_where_conditions_strategy;
130
-
131
-    /**
132
-     * String describing how to find the "owner" of this model's objects.
133
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
-     * But when there isn't, this indicates which related model, or transiently-related model,
135
-     * has the foreign key to the wp_users table.
136
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
-     * related to events, and events have a foreign key to wp_users.
138
-     * On EEM_Transaction, this would be 'Transaction.Event'
139
-     *
140
-     * @var string
141
-     */
142
-    protected $_model_chain_to_wp_user = '';
143
-
144
-    /**
145
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
-     * don't need it (particularly CPT models)
147
-     *
148
-     * @var bool
149
-     */
150
-    protected $_ignore_where_strategy = false;
151
-
152
-    /**
153
-     * String used in caps relating to this model. Eg, if the caps relating to this
154
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
-     *
156
-     * @var string. If null it hasn't been initialized yet. If false then we
157
-     * have indicated capabilities don't apply to this
158
-     */
159
-    protected $_caps_slug = null;
160
-
161
-    /**
162
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
-     * and next-level keys are capability names, and each's value is a
164
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
-     * they specify which context to use (ie, frontend, backend, edit or delete)
166
-     * and then each capability in the corresponding sub-array that they're missing
167
-     * adds the where conditions onto the query.
168
-     *
169
-     * @var array
170
-     */
171
-    protected $_cap_restrictions = array(
172
-        self::caps_read       => array(),
173
-        self::caps_read_admin => array(),
174
-        self::caps_edit       => array(),
175
-        self::caps_delete     => array(),
176
-    );
177
-
178
-    /**
179
-     * Array defining which cap restriction generators to use to create default
180
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
181
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
-     * automatically set this to false (not just null).
184
-     *
185
-     * @var EE_Restriction_Generator_Base[]
186
-     */
187
-    protected $_cap_restriction_generators = array();
188
-
189
-    /**
190
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
-     */
192
-    const caps_read       = 'read';
193
-
194
-    const caps_read_admin = 'read_admin';
195
-
196
-    const caps_edit       = 'edit';
197
-
198
-    const caps_delete     = 'delete';
199
-
200
-    /**
201
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
-     * maps to 'read' because when looking for relevant permissions we're going to use
204
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_cap_contexts_to_cap_action_map = array(
209
-        self::caps_read       => 'read',
210
-        self::caps_read_admin => 'read',
211
-        self::caps_edit       => 'edit',
212
-        self::caps_delete     => 'delete',
213
-    );
214
-
215
-    /**
216
-     * Timezone
217
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
-     * EE_Datetime_Field data type will have access to it.
221
-     *
222
-     * @var string
223
-     */
224
-    protected $_timezone;
225
-
226
-
227
-    /**
228
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
-     * multisite.
230
-     *
231
-     * @var int
232
-     */
233
-    protected static $_model_query_blog_id;
234
-
235
-    /**
236
-     * A copy of _fields, except the array keys are the model names pointed to by
237
-     * the field
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cache_foreign_key_to_fields = array();
242
-
243
-    /**
244
-     * Cached list of all the fields on the model, indexed by their name
245
-     *
246
-     * @var EE_Model_Field_Base[]
247
-     */
248
-    private $_cached_fields = null;
249
-
250
-    /**
251
-     * Cached list of all the fields on the model, except those that are
252
-     * marked as only pertinent to the database
253
-     *
254
-     * @var EE_Model_Field_Base[]
255
-     */
256
-    private $_cached_fields_non_db_only = null;
257
-
258
-    /**
259
-     * A cached reference to the primary key for quick lookup
260
-     *
261
-     * @var EE_Model_Field_Base
262
-     */
263
-    private $_primary_key_field = null;
264
-
265
-    /**
266
-     * Flag indicating whether this model has a primary key or not
267
-     *
268
-     * @var boolean
269
-     */
270
-    protected $_has_primary_key_field = null;
271
-
272
-    /**
273
-     * Whether or not this model is based off a table in WP core only (CPTs should set
274
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
-     *
276
-     * @var boolean
277
-     */
278
-    protected $_wp_core_model = false;
279
-
280
-    /**
281
-     *    List of valid operators that can be used for querying.
282
-     * The keys are all operators we'll accept, the values are the real SQL
283
-     * operators used
284
-     *
285
-     * @var array
286
-     */
287
-    protected $_valid_operators = array(
288
-        '='           => '=',
289
-        '<='          => '<=',
290
-        '<'           => '<',
291
-        '>='          => '>=',
292
-        '>'           => '>',
293
-        '!='          => '!=',
294
-        'LIKE'        => 'LIKE',
295
-        'like'        => 'LIKE',
296
-        'NOT_LIKE'    => 'NOT LIKE',
297
-        'not_like'    => 'NOT LIKE',
298
-        'NOT LIKE'    => 'NOT LIKE',
299
-        'not like'    => 'NOT LIKE',
300
-        'IN'          => 'IN',
301
-        'in'          => 'IN',
302
-        'NOT_IN'      => 'NOT IN',
303
-        'not_in'      => 'NOT IN',
304
-        'NOT IN'      => 'NOT IN',
305
-        'not in'      => 'NOT IN',
306
-        'between'     => 'BETWEEN',
307
-        'BETWEEN'     => 'BETWEEN',
308
-        'IS_NOT_NULL' => 'IS NOT NULL',
309
-        'is_not_null' => 'IS NOT NULL',
310
-        'IS NOT NULL' => 'IS NOT NULL',
311
-        'is not null' => 'IS NOT NULL',
312
-        'IS_NULL'     => 'IS NULL',
313
-        'is_null'     => 'IS NULL',
314
-        'IS NULL'     => 'IS NULL',
315
-        'is null'     => 'IS NULL',
316
-        'REGEXP'      => 'REGEXP',
317
-        'regexp'      => 'REGEXP',
318
-        'NOT_REGEXP'  => 'NOT REGEXP',
319
-        'not_regexp'  => 'NOT REGEXP',
320
-        'NOT REGEXP'  => 'NOT REGEXP',
321
-        'not regexp'  => 'NOT REGEXP',
322
-    );
323
-
324
-    /**
325
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
-     *
327
-     * @var array
328
-     */
329
-    protected $_in_style_operators = array('IN', 'NOT IN');
330
-
331
-    /**
332
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
-     * '12-31-2012'"
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_between_style_operators = array('BETWEEN');
338
-
339
-    /**
340
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
-     * on a join table.
342
-     *
343
-     * @var array
344
-     */
345
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
-
347
-    /**
348
-     * Allowed values for $query_params['order'] for ordering in queries
349
-     *
350
-     * @var array
351
-     */
352
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
-
354
-    /**
355
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
357
-     *
358
-     * @var array
359
-     */
360
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
-
362
-    /**
363
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
365
-     *
366
-     * @var array
367
-     */
368
-    private $_allowed_query_params = array(
369
-        0,
370
-        'limit',
371
-        'order_by',
372
-        'group_by',
373
-        'having',
374
-        'force_join',
375
-        'order',
376
-        'on_join_limit',
377
-        'default_where_conditions',
378
-        'caps',
379
-    );
380
-
381
-    /**
382
-     * All the data types that can be used in $wpdb->prepare statements.
383
-     *
384
-     * @var array
385
-     */
386
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
-
388
-    /**
389
-     *    EE_Registry Object
390
-     *
391
-     * @var    object
392
-     * @access    protected
393
-     */
394
-    protected $EE = null;
395
-
396
-
397
-    /**
398
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
-     *
400
-     * @var int
401
-     */
402
-    protected $_show_next_x_db_queries = 0;
403
-
404
-    /**
405
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
-     *
408
-     * @var array
409
-     */
410
-    protected $_custom_selections = array();
411
-
412
-    /**
413
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
-     * caches every model object we've fetched from the DB on this request
415
-     *
416
-     * @var array
417
-     */
418
-    protected $_entity_map;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has not yet verified the db on this http request
422
-     */
423
-    const db_verified_none = 0;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the EE core db on this http request,
427
-     * but not the addons' dbs
428
-     */
429
-    const db_verified_core = 1;
430
-
431
-    /**
432
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
-     * the EE core db too)
434
-     */
435
-    const db_verified_addons = 2;
436
-
437
-    /**
438
-     * indicates whether an EEM_Base child has already re-verified the DB
439
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
440
-     * looking like EEM_Base::db_verified_*
441
-     *
442
-     * @var int - 0 = none, 1 = core, 2 = addons
443
-     */
444
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
445
-
446
-
447
-
448
-    /**
449
-     * About all child constructors:
450
-     * they should define the _tables, _fields and _model_relations arrays.
451
-     * Should ALWAYS be called after child constructor.
452
-     * In order to make the child constructors to be as simple as possible, this parent constructor
453
-     * finalizes constructing all the object's attributes.
454
-     * Generally, rather than requiring a child to code
455
-     * $this->_tables = array(
456
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
457
-     *        ...);
458
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
459
-     * each EE_Table has a function to set the table's alias after the constructor, using
460
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
461
-     * do something similar.
462
-     *
463
-     * @param null $timezone
464
-     * @throws \EE_Error
465
-     */
466
-    protected function __construct($timezone = null)
467
-    {
468
-        // check that the model has not been loaded too soon
469
-        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
-            throw new EE_Error (
471
-                sprintf(
472
-                    __('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.',
473
-                        'event_espresso'),
474
-                    get_class($this)
475
-                )
476
-            );
477
-        }
478
-        /**
479
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
480
-         */
481
-        if (empty(EEM_Base::$_model_query_blog_id)) {
482
-            EEM_Base::set_model_query_blog_id();
483
-        }
484
-        /**
485
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
486
-         * just use EE_Register_Model_Extension
487
-         *
488
-         * @var EE_Table_Base[] $_tables
489
-         */
490
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
491
-        foreach ($this->_tables as $table_alias => $table_obj) {
492
-            /** @var $table_obj EE_Table_Base */
493
-            $table_obj->_construct_finalize_with_alias($table_alias);
494
-            if ($table_obj instanceof EE_Secondary_Table) {
495
-                /** @var $table_obj EE_Secondary_Table */
496
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
497
-            }
498
-        }
499
-        /**
500
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
501
-         * EE_Register_Model_Extension
502
-         *
503
-         * @param EE_Model_Field_Base[] $_fields
504
-         */
505
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
506
-        $this->_invalidate_field_caches();
507
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
508
-            if ( ! array_key_exists($table_alias, $this->_tables)) {
509
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
511
-            }
512
-            foreach ($fields_for_table as $field_name => $field_obj) {
513
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
514
-                //primary key field base has a slightly different _construct_finalize
515
-                /** @var $field_obj EE_Model_Field_Base */
516
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
517
-            }
518
-        }
519
-        // everything is related to Extra_Meta
520
-        if (get_class($this) !== 'EEM_Extra_Meta') {
521
-            //make extra meta related to everything, but don't block deleting things just
522
-            //because they have related extra meta info. For now just orphan those extra meta
523
-            //in the future we should automatically delete them
524
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
525
-        }
526
-        //and change logs
527
-        if (get_class($this) !== 'EEM_Change_Log') {
528
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
529
-        }
530
-        /**
531
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
532
-         * EE_Register_Model_Extension
533
-         *
534
-         * @param EE_Model_Relation_Base[] $_model_relations
535
-         */
536
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
537
-            $this->_model_relations);
538
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
539
-            /** @var $relation_obj EE_Model_Relation_Base */
540
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
541
-        }
542
-        foreach ($this->_indexes as $index_name => $index_obj) {
543
-            /** @var $index_obj EE_Index */
544
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
545
-        }
546
-        $this->set_timezone($timezone);
547
-        //finalize default where condition strategy, or set default
548
-        if ( ! $this->_default_where_conditions_strategy) {
549
-            //nothing was set during child constructor, so set default
550
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551
-        }
552
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
553
-        if ( ! $this->_minimum_where_conditions_strategy) {
554
-            //nothing was set during child constructor, so set default
555
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556
-        }
557
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
558
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
559
-        //to indicate to NOT set it, set it to the logical default
560
-        if ($this->_caps_slug === null) {
561
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
562
-        }
563
-        //initialize the standard cap restriction generators if none were specified by the child constructor
564
-        if ($this->_cap_restriction_generators !== false) {
565
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
-                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
568
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569
-                        new EE_Restriction_Generator_Protected(),
570
-                        $cap_context,
571
-                        $this
572
-                    );
573
-                }
574
-            }
575
-        }
576
-        //if there are cap restriction generators, use them to make the default cap restrictions
577
-        if ($this->_cap_restriction_generators !== false) {
578
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
-                if ( ! $generator_object) {
580
-                    continue;
581
-                }
582
-                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583
-                    throw new EE_Error(
584
-                        sprintf(
585
-                            __('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.',
586
-                                'event_espresso'),
587
-                            $context,
588
-                            $this->get_this_model_name()
589
-                        )
590
-                    );
591
-                }
592
-                $action = $this->cap_action_for_context($context);
593
-                if ( ! $generator_object->construction_finalized()) {
594
-                    $generator_object->_construct_finalize($this, $action);
595
-                }
596
-            }
597
-        }
598
-        do_action('AHEE__' . get_class($this) . '__construct__end');
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * Generates the cap restrictions for the given context, or if they were
605
-     * already generated just gets what's cached
606
-     *
607
-     * @param string $context one of EEM_Base::valid_cap_contexts()
608
-     * @return EE_Default_Where_Conditions[]
609
-     */
610
-    protected function _generate_cap_restrictions($context)
611
-    {
612
-        if (isset($this->_cap_restriction_generators[$context])
613
-            && $this->_cap_restriction_generators[$context]
614
-               instanceof
615
-               EE_Restriction_Generator_Base
616
-        ) {
617
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
618
-        } else {
619
-            return array();
620
-        }
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * Used to set the $_model_query_blog_id static property.
627
-     *
628
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
629
-     *                      value for get_current_blog_id() will be used.
630
-     */
631
-    public static function set_model_query_blog_id($blog_id = 0)
632
-    {
633
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
634
-    }
635
-
636
-
637
-
638
-    /**
639
-     * Returns whatever is set as the internal $model_query_blog_id.
640
-     *
641
-     * @return int
642
-     */
643
-    public static function get_model_query_blog_id()
644
-    {
645
-        return EEM_Base::$_model_query_blog_id;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     *        This function is a singleton method used to instantiate the Espresso_model object
652
-     *
653
-     * @access public
654
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
655
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
656
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
657
-     *                         timezone in the 'timezone_string' wp option)
658
-     * @return static (as in the concrete child class)
659
-     */
660
-    public static function instance($timezone = null)
661
-    {
662
-        // check if instance of Espresso_model already exists
663
-        if ( ! static::$_instance instanceof static) {
664
-            // instantiate Espresso_model
665
-            static::$_instance = new static($timezone);
666
-        }
667
-        //we might have a timezone set, let set_timezone decide what to do with it
668
-        static::$_instance->set_timezone($timezone);
669
-        // Espresso_model object
670
-        return static::$_instance;
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * resets the model and returns it
677
-     *
678
-     * @param null | string $timezone
679
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
680
-     * all its properties reset; if it wasn't instantiated, returns null)
681
-     */
682
-    public static function reset($timezone = null)
683
-    {
684
-        if (static::$_instance instanceof EEM_Base) {
685
-            //let's try to NOT swap out the current instance for a new one
686
-            //because if someone has a reference to it, we can't remove their reference
687
-            //so it's best to keep using the same reference, but change the original object
688
-            //reset all its properties to their original values as defined in the class
689
-            $r = new ReflectionClass(get_class(static::$_instance));
690
-            $static_properties = $r->getStaticProperties();
691
-            foreach ($r->getDefaultProperties() as $property => $value) {
692
-                //don't set instance to null like it was originally,
693
-                //but it's static anyways, and we're ignoring static properties (for now at least)
694
-                if ( ! isset($static_properties[$property])) {
695
-                    static::$_instance->{$property} = $value;
696
-                }
697
-            }
698
-            //and then directly call its constructor again, like we would if we
699
-            //were creating a new one
700
-            static::$_instance->__construct($timezone);
701
-            return self::instance();
702
-        }
703
-        return null;
704
-    }
705
-
706
-
707
-
708
-    /**
709
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
710
-     *
711
-     * @param  boolean $translated return localized strings or JUST the array.
712
-     * @return array
713
-     * @throws \EE_Error
714
-     */
715
-    public function status_array($translated = false)
716
-    {
717
-        if ( ! array_key_exists('Status', $this->_model_relations)) {
718
-            return array();
719
-        }
720
-        $model_name = $this->get_this_model_name();
721
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
722
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
723
-        $status_array = array();
724
-        foreach ($stati as $status) {
725
-            $status_array[$status->ID()] = $status->get('STS_code');
726
-        }
727
-        return $translated
728
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
729
-            : $status_array;
730
-    }
731
-
732
-
733
-
734
-    /**
735
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
736
-     *
737
-     * @param array $query_params             {
738
-     * @var array $0 (where) array {
739
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
740
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
741
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
742
-     *                                        conditions based on related models (and even
743
-     *                                        models-related-to-related-models) prepend the model's name onto the field
744
-     *                                        name. Eg,
745
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
746
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
747
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
748
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
749
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically
750
-     *                                        took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having
751
-     *                                        "Venue.VNU_ID", you could have
752
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
753
-     *                                        events are related to Registrations, which are related to Attendees). You
754
-     *                                        can take it even further with
755
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
756
-     *                                        (from the default of '='), change the value to an numerically-indexed
757
-     *                                        array, where the first item in the list is the operator. eg: array(
758
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
759
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
760
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
761
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
762
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can
763
-     *                                        also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
764
-     *                                        eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field
765
-     *                                        name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default
766
-     *                                        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__>' =>
767
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' =>
768
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
769
-     *                                        but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND.
770
-     *                                        eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
771
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes
772
-     *                                        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
773
-     *                                        place two or more where conditions applying to the same field. eg:
774
-     *                                        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
775
-     *                                        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 '*'
776
-     *                                        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
777
-     *                                        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 >>
778
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg:
779
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
780
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
781
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
782
-     *                                        and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
783
-     *                                        the OFFSET, the 2nd is the LIMIT
784
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
785
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
786
-     *                                        => array( 'table_alias', array(1,2) ) ).
787
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
788
-     *                                        values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
789
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
790
-     *                                        'where' conditions, these fields can be on related models. Eg
791
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
792
-     *                                        to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
793
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
794
-     *                                        'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
795
-     *                                        Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
796
-     *                                        want to order by the primary key. Eg,
797
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
798
-     *                                        with the Datetime model's table(s) and order by its field DTT_EVT_start) or
799
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
800
-     *                                        wp_esp_registration ORDER BY REG_ID ASC"
801
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
802
-     *                                        'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
803
-     *                                        $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
804
-     *                                        primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
805
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
806
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
807
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped results)
808
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
809
-     *                                        array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
810
-     *                                        join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
811
-     *                                        to do this in hopes of increasing efficiency, as related models which belongs to the current model
812
-     *                                        (ie, the current model has a foreign key to them, like how Registration
813
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
814
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
815
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
816
-     *                                        filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
817
-     *                                        model's default where conditions set it to 'other_models_only'. If you only want this model's default where
818
-     *                                        conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
819
-     *                                        (default), set to 'all'.
820
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
821
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
822
-     *                                        the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
823
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
824
-     *                                        }
825
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
826
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
827
-     *                                        are object IDs (if there is a primary key on the model. if not, numerically indexed)
828
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
829
-     *                                        EEM_Transaction::instance()->get_all( array( array(
830
-     *                                        'OR'=>array(
831
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
832
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
833
-     *                                        )
834
-     *                                        ),
835
-     *                                        'limit'=>10,
836
-     *                                        'group_by'=>'TXN_ID'
837
-     *                                        ));
838
-     *                                        get all the answers to the question titled "shirt size" for event with id
839
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
840
-     *                                        'Question.QST_display_text'=>'shirt size',
841
-     *                                        'Registration.Event.EVT_ID'=>12
842
-     *                                        ),
843
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
844
-     *                                        ));
845
-     * @throws \EE_Error
846
-     */
847
-    public function get_all($query_params = array())
848
-    {
849
-        if (isset($query_params['limit'])
850
-            && ! isset($query_params['group_by'])
851
-        ) {
852
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
853
-        }
854
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
855
-    }
856
-
857
-
858
-
859
-    /**
860
-     * Modifies the query parameters so we only get back model objects
861
-     * that "belong" to the current user
862
-     *
863
-     * @param array $query_params @see EEM_Base::get_all()
864
-     * @return array like EEM_Base::get_all
865
-     */
866
-    public function alter_query_params_to_only_include_mine($query_params = array())
867
-    {
868
-        $wp_user_field_name = $this->wp_user_field_name();
869
-        if ($wp_user_field_name) {
870
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
871
-        }
872
-        return $query_params;
873
-    }
874
-
875
-
876
-
877
-    /**
878
-     * Returns the name of the field's name that points to the WP_User table
879
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
880
-     * foreign key to the WP_User table)
881
-     *
882
-     * @return string|boolean string on success, boolean false when there is no
883
-     * foreign key to the WP_User table
884
-     */
885
-    public function wp_user_field_name()
886
-    {
887
-        try {
888
-            if ( ! empty($this->_model_chain_to_wp_user)) {
889
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
890
-                $last_model_name = end($models_to_follow_to_wp_users);
891
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
892
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
893
-            } else {
894
-                $model_with_fk_to_wp_users = $this;
895
-                $model_chain_to_wp_user = '';
896
-            }
897
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
898
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
899
-        } catch (EE_Error $e) {
900
-            return false;
901
-        }
902
-    }
903
-
904
-
905
-
906
-    /**
907
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
908
-     * (or transiently-related model) has a foreign key to the wp_users table;
909
-     * useful for finding if model objects of this type are 'owned' by the current user.
910
-     * This is an empty string when the foreign key is on this model and when it isn't,
911
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
912
-     * (or transiently-related model)
913
-     *
914
-     * @return string
915
-     */
916
-    public function model_chain_to_wp_user()
917
-    {
918
-        return $this->_model_chain_to_wp_user;
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
925
-     * like how registrations don't have a foreign key to wp_users, but the
926
-     * events they are for are), or is unrelated to wp users.
927
-     * generally available
928
-     *
929
-     * @return boolean
930
-     */
931
-    public function is_owned()
932
-    {
933
-        if ($this->model_chain_to_wp_user()) {
934
-            return true;
935
-        } else {
936
-            try {
937
-                $this->get_foreign_key_to('WP_User');
938
-                return true;
939
-            } catch (EE_Error $e) {
940
-                return false;
941
-            }
942
-        }
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
949
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
950
-     * the model)
951
-     *
952
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
953
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
954
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
955
-     *                                  fields on the model, and the models we joined to in the query. However, you can
956
-     *                                  override this and set the select to "*", or a specific column name, like
957
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
958
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
959
-     *                                  the aliases used to refer to this selection, and values are to be
960
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
961
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
962
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
963
-     * @throws \EE_Error
964
-     */
965
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
966
-    {
967
-        // remember the custom selections, if any, and type cast as array
968
-        // (unless $columns_to_select is an object, then just set as an empty array)
969
-        // Note: (array) 'some string' === array( 'some string' )
970
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
971
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
972
-        $select_expressions = $columns_to_select !== null
973
-            ? $this->_construct_select_from_input($columns_to_select)
974
-            : $this->_construct_default_select_sql($model_query_info);
975
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
976
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
977
-    }
978
-
979
-
980
-
981
-    /**
982
-     * Gets an array of rows from the database just like $wpdb->get_results would,
983
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
984
-     * take care of joins, field preparation etc.
985
-     *
986
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
987
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
988
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
989
-     *                                  fields on the model, and the models we joined to in the query. However, you can
990
-     *                                  override this and set the select to "*", or a specific column name, like
991
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
992
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
993
-     *                                  the aliases used to refer to this selection, and values are to be
994
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
995
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
996
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
997
-     * @throws \EE_Error
998
-     */
999
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1000
-    {
1001
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1002
-    }
1003
-
1004
-
1005
-
1006
-    /**
1007
-     * For creating a custom select statement
1008
-     *
1009
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1010
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1011
-     *                                 SQL, and 1=>is the datatype
1012
-     * @throws EE_Error
1013
-     * @return string
1014
-     */
1015
-    private function _construct_select_from_input($columns_to_select)
1016
-    {
1017
-        if (is_array($columns_to_select)) {
1018
-            $select_sql_array = array();
1019
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1020
-                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1021
-                    throw new EE_Error(
1022
-                        sprintf(
1023
-                            __(
1024
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1025
-                                "event_espresso"
1026
-                            ),
1027
-                            $selection_and_datatype,
1028
-                            $alias
1029
-                        )
1030
-                    );
1031
-                }
1032
-                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1033
-                    throw new EE_Error(
1034
-                        sprintf(
1035
-                            __(
1036
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1037
-                                "event_espresso"
1038
-                            ),
1039
-                            $selection_and_datatype[1],
1040
-                            $selection_and_datatype[0],
1041
-                            $alias,
1042
-                            implode(",", $this->_valid_wpdb_data_types)
1043
-                        )
1044
-                    );
1045
-                }
1046
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1047
-            }
1048
-            $columns_to_select_string = implode(", ", $select_sql_array);
1049
-        } else {
1050
-            $columns_to_select_string = $columns_to_select;
1051
-        }
1052
-        return $columns_to_select_string;
1053
-    }
1054
-
1055
-
1056
-
1057
-    /**
1058
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1059
-     *
1060
-     * @return string
1061
-     * @throws \EE_Error
1062
-     */
1063
-    public function primary_key_name()
1064
-    {
1065
-        return $this->get_primary_key_field()->get_name();
1066
-    }
1067
-
1068
-
1069
-
1070
-    /**
1071
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1072
-     * If there is no primary key on this model, $id is treated as primary key string
1073
-     *
1074
-     * @param mixed $id int or string, depending on the type of the model's primary key
1075
-     * @return EE_Base_Class
1076
-     */
1077
-    public function get_one_by_ID($id)
1078
-    {
1079
-        if ($this->get_from_entity_map($id)) {
1080
-            return $this->get_from_entity_map($id);
1081
-        }
1082
-        return $this->get_one(
1083
-            $this->alter_query_params_to_restrict_by_ID(
1084
-                $id,
1085
-                array('default_where_conditions' => 'minimum')
1086
-            )
1087
-        );
1088
-    }
1089
-
1090
-
1091
-
1092
-    /**
1093
-     * Alters query parameters to only get items with this ID are returned.
1094
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1095
-     * or could just be a simple primary key ID
1096
-     *
1097
-     * @param int   $id
1098
-     * @param array $query_params
1099
-     * @return array of normal query params, @see EEM_Base::get_all
1100
-     * @throws \EE_Error
1101
-     */
1102
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1103
-    {
1104
-        if ( ! isset($query_params[0])) {
1105
-            $query_params[0] = array();
1106
-        }
1107
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1108
-        if ($conditions_from_id === null) {
1109
-            $query_params[0][$this->primary_key_name()] = $id;
1110
-        } else {
1111
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1112
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1113
-        }
1114
-        return $query_params;
1115
-    }
1116
-
1117
-
1118
-
1119
-    /**
1120
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1121
-     * array. If no item is found, null is returned.
1122
-     *
1123
-     * @param array $query_params like EEM_Base's $query_params variable.
1124
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1125
-     * @throws \EE_Error
1126
-     */
1127
-    public function get_one($query_params = array())
1128
-    {
1129
-        if ( ! is_array($query_params)) {
1130
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1131
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1132
-                    gettype($query_params)), '4.6.0');
1133
-            $query_params = array();
1134
-        }
1135
-        $query_params['limit'] = 1;
1136
-        $items = $this->get_all($query_params);
1137
-        if (empty($items)) {
1138
-            return null;
1139
-        } else {
1140
-            return array_shift($items);
1141
-        }
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * Returns the next x number of items in sequence from the given value as
1148
-     * found in the database matching the given query conditions.
1149
-     *
1150
-     * @param mixed $current_field_value    Value used for the reference point.
1151
-     * @param null  $field_to_order_by      What field is used for the
1152
-     *                                      reference point.
1153
-     * @param int   $limit                  How many to return.
1154
-     * @param array $query_params           Extra conditions on the query.
1155
-     * @param null  $columns_to_select      If left null, then an array of
1156
-     *                                      EE_Base_Class objects is returned,
1157
-     *                                      otherwise you can indicate just the
1158
-     *                                      columns you want returned.
1159
-     * @return EE_Base_Class[]|array
1160
-     * @throws \EE_Error
1161
-     */
1162
-    public function next_x(
1163
-        $current_field_value,
1164
-        $field_to_order_by = null,
1165
-        $limit = 1,
1166
-        $query_params = array(),
1167
-        $columns_to_select = null
1168
-    ) {
1169
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1170
-            $columns_to_select);
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Returns the previous x number of items in sequence from the given value
1177
-     * as found in the database matching the given query conditions.
1178
-     *
1179
-     * @param mixed $current_field_value    Value used for the reference point.
1180
-     * @param null  $field_to_order_by      What field is used for the
1181
-     *                                      reference point.
1182
-     * @param int   $limit                  How many to return.
1183
-     * @param array $query_params           Extra conditions on the query.
1184
-     * @param null  $columns_to_select      If left null, then an array of
1185
-     *                                      EE_Base_Class objects is returned,
1186
-     *                                      otherwise you can indicate just the
1187
-     *                                      columns you want returned.
1188
-     * @return EE_Base_Class[]|array
1189
-     * @throws \EE_Error
1190
-     */
1191
-    public function previous_x(
1192
-        $current_field_value,
1193
-        $field_to_order_by = null,
1194
-        $limit = 1,
1195
-        $query_params = array(),
1196
-        $columns_to_select = null
1197
-    ) {
1198
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1199
-            $columns_to_select);
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Returns the next item in sequence from the given value as found in the
1206
-     * database matching the given query conditions.
1207
-     *
1208
-     * @param mixed $current_field_value    Value used for the reference point.
1209
-     * @param null  $field_to_order_by      What field is used for the
1210
-     *                                      reference point.
1211
-     * @param array $query_params           Extra conditions on the query.
1212
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1213
-     *                                      object is returned, otherwise you
1214
-     *                                      can indicate just the columns you
1215
-     *                                      want and a single array indexed by
1216
-     *                                      the columns will be returned.
1217
-     * @return EE_Base_Class|null|array()
1218
-     * @throws \EE_Error
1219
-     */
1220
-    public function next(
1221
-        $current_field_value,
1222
-        $field_to_order_by = null,
1223
-        $query_params = array(),
1224
-        $columns_to_select = null
1225
-    ) {
1226
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1227
-            $columns_to_select);
1228
-        return empty($results) ? null : reset($results);
1229
-    }
1230
-
1231
-
1232
-
1233
-    /**
1234
-     * Returns the previous item in sequence from the given value as found in
1235
-     * the database matching the given query conditions.
1236
-     *
1237
-     * @param mixed $current_field_value    Value used for the reference point.
1238
-     * @param null  $field_to_order_by      What field is used for the
1239
-     *                                      reference point.
1240
-     * @param array $query_params           Extra conditions on the query.
1241
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1242
-     *                                      object is returned, otherwise you
1243
-     *                                      can indicate just the columns you
1244
-     *                                      want and a single array indexed by
1245
-     *                                      the columns will be returned.
1246
-     * @return EE_Base_Class|null|array()
1247
-     * @throws EE_Error
1248
-     */
1249
-    public function previous(
1250
-        $current_field_value,
1251
-        $field_to_order_by = null,
1252
-        $query_params = array(),
1253
-        $columns_to_select = null
1254
-    ) {
1255
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1256
-            $columns_to_select);
1257
-        return empty($results) ? null : reset($results);
1258
-    }
1259
-
1260
-
1261
-
1262
-    /**
1263
-     * Returns the a consecutive number of items in sequence from the given
1264
-     * value as found in the database matching the given query conditions.
1265
-     *
1266
-     * @param mixed  $current_field_value   Value used for the reference point.
1267
-     * @param string $operand               What operand is used for the sequence.
1268
-     * @param string $field_to_order_by     What field is used for the reference point.
1269
-     * @param int    $limit                 How many to return.
1270
-     * @param array  $query_params          Extra conditions on the query.
1271
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1272
-     *                                      otherwise you can indicate just the columns you want returned.
1273
-     * @return EE_Base_Class[]|array
1274
-     * @throws EE_Error
1275
-     */
1276
-    protected function _get_consecutive(
1277
-        $current_field_value,
1278
-        $operand = '>',
1279
-        $field_to_order_by = null,
1280
-        $limit = 1,
1281
-        $query_params = array(),
1282
-        $columns_to_select = null
1283
-    ) {
1284
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1285
-        if (empty($field_to_order_by)) {
1286
-            if ($this->has_primary_key_field()) {
1287
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1288
-            } else {
1289
-                if (WP_DEBUG) {
1290
-                    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).',
1291
-                        'event_espresso'));
1292
-                }
1293
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1294
-                return array();
1295
-            }
1296
-        }
1297
-        if ( ! is_array($query_params)) {
1298
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1299
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1300
-                    gettype($query_params)), '4.6.0');
1301
-            $query_params = array();
1302
-        }
1303
-        //let's add the where query param for consecutive look up.
1304
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1305
-        $query_params['limit'] = $limit;
1306
-        //set direction
1307
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1308
-        $query_params['order_by'] = $operand === '>'
1309
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1310
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1311
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1312
-        if (empty($columns_to_select)) {
1313
-            return $this->get_all($query_params);
1314
-        } else {
1315
-            //getting just the fields
1316
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1317
-        }
1318
-    }
1319
-
1320
-
1321
-
1322
-    /**
1323
-     * This sets the _timezone property after model object has been instantiated.
1324
-     *
1325
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1326
-     */
1327
-    public function set_timezone($timezone)
1328
-    {
1329
-        if ($timezone !== null) {
1330
-            $this->_timezone = $timezone;
1331
-        }
1332
-        //note we need to loop through relations and set the timezone on those objects as well.
1333
-        foreach ($this->_model_relations as $relation) {
1334
-            $relation->set_timezone($timezone);
1335
-        }
1336
-        //and finally we do the same for any datetime fields
1337
-        foreach ($this->_fields as $field) {
1338
-            if ($field instanceof EE_Datetime_Field) {
1339
-                $field->set_timezone($timezone);
1340
-            }
1341
-        }
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * This just returns whatever is set for the current timezone.
1348
-     *
1349
-     * @access public
1350
-     * @return string
1351
-     */
1352
-    public function get_timezone()
1353
-    {
1354
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1355
-        if (empty($this->_timezone)) {
1356
-            foreach ($this->_fields as $field) {
1357
-                if ($field instanceof EE_Datetime_Field) {
1358
-                    $this->set_timezone($field->get_timezone());
1359
-                    break;
1360
-                }
1361
-            }
1362
-        }
1363
-        //if timezone STILL empty then return the default timezone for the site.
1364
-        if (empty($this->_timezone)) {
1365
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1366
-        }
1367
-        return $this->_timezone;
1368
-    }
1369
-
1370
-
1371
-
1372
-    /**
1373
-     * This returns the date formats set for the given field name and also ensures that
1374
-     * $this->_timezone property is set correctly.
1375
-     *
1376
-     * @since 4.6.x
1377
-     * @param string $field_name The name of the field the formats are being retrieved for.
1378
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1379
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1380
-     * @return array formats in an array with the date format first, and the time format last.
1381
-     */
1382
-    public function get_formats_for($field_name, $pretty = false)
1383
-    {
1384
-        $field_settings = $this->field_settings_for($field_name);
1385
-        //if not a valid EE_Datetime_Field then throw error
1386
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1387
-            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.',
1388
-                'event_espresso'), $field_name));
1389
-        }
1390
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1391
-        //the field.
1392
-        $this->_timezone = $field_settings->get_timezone();
1393
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1394
-    }
1395
-
1396
-
1397
-
1398
-    /**
1399
-     * This returns the current time in a format setup for a query on this model.
1400
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1401
-     * it will return:
1402
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1403
-     *  NOW
1404
-     *  - or a unix timestamp (equivalent to time())
1405
-     *
1406
-     * @since 4.6.x
1407
-     * @param string $field_name       The field the current time is needed for.
1408
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1409
-     *                                 formatted string matching the set format for the field in the set timezone will
1410
-     *                                 be returned.
1411
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1412
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1413
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1414
-     *                                 exception is triggered.
1415
-     */
1416
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1417
-    {
1418
-        $formats = $this->get_formats_for($field_name);
1419
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1420
-        if ($timestamp) {
1421
-            return $DateTime->format('U');
1422
-        }
1423
-        //not returning timestamp, so return formatted string in timezone.
1424
-        switch ($what) {
1425
-            case 'time' :
1426
-                return $DateTime->format($formats[1]);
1427
-                break;
1428
-            case 'date' :
1429
-                return $DateTime->format($formats[0]);
1430
-                break;
1431
-            default :
1432
-                return $DateTime->format(implode(' ', $formats));
1433
-                break;
1434
-        }
1435
-    }
1436
-
1437
-
1438
-
1439
-    /**
1440
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1441
-     * for the model are.  Returns a DateTime object.
1442
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1443
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1444
-     * ignored.
1445
-     *
1446
-     * @param string $field_name      The field being setup.
1447
-     * @param string $timestring      The date time string being used.
1448
-     * @param string $incoming_format The format for the time string.
1449
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1450
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1451
-     *                                format is
1452
-     *                                'U', this is ignored.
1453
-     * @return DateTime
1454
-     * @throws \EE_Error
1455
-     */
1456
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1457
-    {
1458
-        //just using this to ensure the timezone is set correctly internally
1459
-        $this->get_formats_for($field_name);
1460
-        //load EEH_DTT_Helper
1461
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1462
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1463
-        return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1464
-    }
1465
-
1466
-
1467
-
1468
-    /**
1469
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1470
-     *
1471
-     * @return EE_Table_Base[]
1472
-     */
1473
-    public function get_tables()
1474
-    {
1475
-        return $this->_tables;
1476
-    }
1477
-
1478
-
1479
-
1480
-    /**
1481
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1482
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1483
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1484
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1485
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1486
-     * model object with EVT_ID = 1
1487
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1488
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1489
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1490
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1491
-     * are not specified)
1492
-     *
1493
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1494
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1495
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1496
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1497
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1498
-     *                                         ID=34, we'd use this method as follows:
1499
-     *                                         EEM_Transaction::instance()->update(
1500
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1501
-     *                                         array(array('TXN_ID'=>34)));
1502
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1503
-     *                                         in client code into what's expected to be stored on each field. Eg,
1504
-     *                                         consider updating Question's QST_admin_label field is of type
1505
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1506
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1507
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1508
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1509
-     *                                         TRUE, it is assumed that you've already called
1510
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1511
-     *                                         malicious javascript. However, if
1512
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1513
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set
1514
-     *                                         function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1515
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1516
-     *                                         in this model's entity map according to $fields_n_values that match
1517
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1518
-     *                                         by setting this to FALSE, but be aware that model objects being used
1519
-     *                                         could get out-of-sync with the database
1520
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1521
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was bad)
1522
-     * @throws \EE_Error
1523
-     */
1524
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1525
-    {
1526
-        if ( ! is_array($query_params)) {
1527
-            EE_Error::doing_it_wrong('EEM_Base::update',
1528
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1529
-                    gettype($query_params)), '4.6.0');
1530
-            $query_params = array();
1531
-        }
1532
-        /**
1533
-         * Action called before a model update call has been made.
1534
-         *
1535
-         * @param EEM_Base $model
1536
-         * @param array    $fields_n_values the updated fields and their new values
1537
-         * @param array    $query_params    @see EEM_Base::get_all()
1538
-         */
1539
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1540
-        /**
1541
-         * Filters the fields about to be updated given the query parameters. You can provide the
1542
-         * $query_params to $this->get_all() to find exactly which records will be updated
1543
-         *
1544
-         * @param array    $fields_n_values fields and their new values
1545
-         * @param EEM_Base $model           the model being queried
1546
-         * @param array    $query_params    see EEM_Base::get_all()
1547
-         */
1548
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1549
-            $query_params);
1550
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1551
-        //to do that, for each table, verify that it's PK isn't null.
1552
-        $tables = $this->get_tables();
1553
-        //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
1554
-        //NOTE: we should make this code more efficient by NOT querying twice
1555
-        //before the real update, but that needs to first go through ALPHA testing
1556
-        //as it's dangerous. says Mike August 8 2014
1557
-        //we want to make sure the default_where strategy is ignored
1558
-        $this->_ignore_where_strategy = true;
1559
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1560
-        foreach ($wpdb_select_results as $wpdb_result) {
1561
-            // type cast stdClass as array
1562
-            $wpdb_result = (array)$wpdb_result;
1563
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1564
-            if ($this->has_primary_key_field()) {
1565
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1566
-            } else {
1567
-                //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)
1568
-                $main_table_pk_value = null;
1569
-            }
1570
-            //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
1571
-            //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
1572
-            if (count($tables) > 1) {
1573
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1574
-                //in that table, and so we'll want to insert one
1575
-                foreach ($tables as $table_obj) {
1576
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1577
-                    //if there is no private key for this table on the results, it means there's no entry
1578
-                    //in this table, right? so insert a row in the current table, using any fields available
1579
-                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1580
-                            && $wpdb_result[$this_table_pk_column])
1581
-                    ) {
1582
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1583
-                            $main_table_pk_value);
1584
-                        //if we died here, report the error
1585
-                        if ( ! $success) {
1586
-                            return false;
1587
-                        }
1588
-                    }
1589
-                }
1590
-            }
1591
-            //				//and now check that if we have cached any models by that ID on the model, that
1592
-            //				//they also get updated properly
1593
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1594
-            //				if( $model_object ){
1595
-            //					foreach( $fields_n_values as $field => $value ){
1596
-            //						$model_object->set($field, $value);
1597
-            //let's make sure default_where strategy is followed now
1598
-            $this->_ignore_where_strategy = false;
1599
-        }
1600
-        //if we want to keep model objects in sync, AND
1601
-        //if this wasn't called from a model object (to update itself)
1602
-        //then we want to make sure we keep all the existing
1603
-        //model objects in sync with the db
1604
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1605
-            if ($this->has_primary_key_field()) {
1606
-                $model_objs_affected_ids = $this->get_col($query_params);
1607
-            } else {
1608
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1609
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1610
-                $model_objs_affected_ids = array();
1611
-                foreach ($models_affected_key_columns as $row) {
1612
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1613
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1614
-                }
1615
-            }
1616
-            if ( ! $model_objs_affected_ids) {
1617
-                //wait wait wait- if nothing was affected let's stop here
1618
-                return 0;
1619
-            }
1620
-            foreach ($model_objs_affected_ids as $id) {
1621
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1622
-                if ($model_obj_in_entity_map) {
1623
-                    foreach ($fields_n_values as $field => $new_value) {
1624
-                        $model_obj_in_entity_map->set($field, $new_value);
1625
-                    }
1626
-                }
1627
-            }
1628
-            //if there is a primary key on this model, we can now do a slight optimization
1629
-            if ($this->has_primary_key_field()) {
1630
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1631
-                $query_params = array(
1632
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1633
-                    'limit'                    => count($model_objs_affected_ids),
1634
-                    'default_where_conditions' => 'none',
1635
-                );
1636
-            }
1637
-        }
1638
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1639
-        $SQL = "UPDATE "
1640
-               . $model_query_info->get_full_join_sql()
1641
-               . " SET "
1642
-               . $this->_construct_update_sql($fields_n_values)
1643
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1644
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1645
-        /**
1646
-         * Action called after a model update call has been made.
1647
-         *
1648
-         * @param EEM_Base $model
1649
-         * @param array    $fields_n_values the updated fields and their new values
1650
-         * @param array    $query_params    @see EEM_Base::get_all()
1651
-         * @param int      $rows_affected
1652
-         */
1653
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1654
-        return $rows_affected;//how many supposedly got updated
1655
-    }
1656
-
1657
-
1658
-
1659
-    /**
1660
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1661
-     * are teh values of the field specified (or by default the primary key field)
1662
-     * that matched the query params. Note that you should pass the name of the
1663
-     * model FIELD, not the database table's column name.
1664
-     *
1665
-     * @param array  $query_params @see EEM_Base::get_all()
1666
-     * @param string $field_to_select
1667
-     * @return array just like $wpdb->get_col()
1668
-     * @throws \EE_Error
1669
-     */
1670
-    public function get_col($query_params = array(), $field_to_select = null)
1671
-    {
1672
-        if ($field_to_select) {
1673
-            $field = $this->field_settings_for($field_to_select);
1674
-        } elseif ($this->has_primary_key_field()) {
1675
-            $field = $this->get_primary_key_field();
1676
-        } else {
1677
-            //no primary key, just grab the first column
1678
-            $field = reset($this->field_settings());
1679
-        }
1680
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1681
-        $select_expressions = $field->get_qualified_column();
1682
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1683
-        return $this->_do_wpdb_query('get_col', array($SQL));
1684
-    }
1685
-
1686
-
1687
-
1688
-    /**
1689
-     * Returns a single column value for a single row from the database
1690
-     *
1691
-     * @param array  $query_params    @see EEM_Base::get_all()
1692
-     * @param string $field_to_select @see EEM_Base::get_col()
1693
-     * @return string
1694
-     * @throws \EE_Error
1695
-     */
1696
-    public function get_var($query_params = array(), $field_to_select = null)
1697
-    {
1698
-        $query_params['limit'] = 1;
1699
-        $col = $this->get_col($query_params, $field_to_select);
1700
-        if ( ! empty($col)) {
1701
-            return reset($col);
1702
-        } else {
1703
-            return null;
1704
-        }
1705
-    }
1706
-
1707
-
1708
-
1709
-    /**
1710
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1711
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1712
-     * injection, but currently no further filtering is done
1713
-     *
1714
-     * @global      $wpdb
1715
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1716
-     *                               be updated to in the DB
1717
-     * @return string of SQL
1718
-     * @throws \EE_Error
1719
-     */
1720
-    public function _construct_update_sql($fields_n_values)
1721
-    {
1722
-        /** @type WPDB $wpdb */
1723
-        global $wpdb;
1724
-        $cols_n_values = array();
1725
-        foreach ($fields_n_values as $field_name => $value) {
1726
-            $field_obj = $this->field_settings_for($field_name);
1727
-            //if the value is NULL, we want to assign the value to that.
1728
-            //wpdb->prepare doesn't really handle that properly
1729
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1730
-            $value_sql = $prepared_value === null ? 'NULL'
1731
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1732
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1733
-        }
1734
-        return implode(",", $cols_n_values);
1735
-    }
1736
-
1737
-
1738
-
1739
-    /**
1740
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1741
-     * Performs a HARD delete, meaning the database row should always be removed,
1742
-     * not just have a flag field on it switched
1743
-     * Wrapper for EEM_Base::delete_permanently()
1744
-     *
1745
-     * @param mixed $id
1746
-     * @return boolean whether the row got deleted or not
1747
-     * @throws \EE_Error
1748
-     */
1749
-    public function delete_permanently_by_ID($id)
1750
-    {
1751
-        return $this->delete_permanently(
1752
-            array(
1753
-                array($this->get_primary_key_field()->get_name() => $id),
1754
-                'limit' => 1,
1755
-            )
1756
-        );
1757
-    }
1758
-
1759
-
1760
-
1761
-    /**
1762
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1763
-     * Wrapper for EEM_Base::delete()
1764
-     *
1765
-     * @param mixed $id
1766
-     * @return boolean whether the row got deleted or not
1767
-     * @throws \EE_Error
1768
-     */
1769
-    public function delete_by_ID($id)
1770
-    {
1771
-        return $this->delete(
1772
-            array(
1773
-                array($this->get_primary_key_field()->get_name() => $id),
1774
-                'limit' => 1,
1775
-            )
1776
-        );
1777
-    }
1778
-
1779
-
1780
-
1781
-    /**
1782
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1783
-     * meaning if the model has a field that indicates its been "trashed" or
1784
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1785
-     *
1786
-     * @see EEM_Base::delete_permanently
1787
-     * @param array   $query_params
1788
-     * @param boolean $allow_blocking
1789
-     * @return int how many rows got deleted
1790
-     * @throws \EE_Error
1791
-     */
1792
-    public function delete($query_params, $allow_blocking = true)
1793
-    {
1794
-        return $this->delete_permanently($query_params, $allow_blocking);
1795
-    }
1796
-
1797
-
1798
-
1799
-    /**
1800
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1801
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1802
-     * as archived, not actually deleted
1803
-     *
1804
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1805
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1806
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1807
-     *                                deletes regardless of other objects which may depend on it. Its generally
1808
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1809
-     *                                DB
1810
-     * @return int how many rows got deleted
1811
-     * @throws \EE_Error
1812
-     */
1813
-    public function delete_permanently($query_params, $allow_blocking = true)
1814
-    {
1815
-        /**
1816
-         * Action called just before performing a real deletion query. You can use the
1817
-         * model and its $query_params to find exactly which items will be deleted
1818
-         *
1819
-         * @param EEM_Base $model
1820
-         * @param array    $query_params   @see EEM_Base::get_all()
1821
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1822
-         *                                 to block (prevent) this deletion
1823
-         */
1824
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1825
-        //some MySQL databases may be running safe mode, which may restrict
1826
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1827
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1828
-        //to delete them
1829
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1830
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1831
-        if ($deletion_where) {
1832
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1833
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1834
-            $table_aliases = array_keys($this->_tables);
1835
-            $SQL = "DELETE "
1836
-                   . implode(", ", $table_aliases)
1837
-                   . " FROM "
1838
-                   . $model_query_info->get_full_join_sql()
1839
-                   . " WHERE "
1840
-                   . $deletion_where;
1841
-            //		/echo "delete sql:$SQL";
1842
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1843
-        } else {
1844
-            $rows_deleted = 0;
1845
-        }
1846
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1847
-        if ($this->has_primary_key_field()) {
1848
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1849
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1850
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1851
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1852
-                }
1853
-            }
1854
-        }
1855
-        /**
1856
-         * Action called just after performing a real deletion query. Although at this point the
1857
-         * items should have been deleted
1858
-         *
1859
-         * @param EEM_Base $model
1860
-         * @param array    $query_params @see EEM_Base::get_all()
1861
-         * @param int      $rows_deleted
1862
-         */
1863
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1864
-        return $rows_deleted;//how many supposedly got deleted
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Checks all the relations that throw error messages when there are blocking related objects
1871
-     * for related model objects. If there are any related model objects on those relations,
1872
-     * adds an EE_Error, and return true
1873
-     *
1874
-     * @param EE_Base_Class|int $this_model_obj_or_id
1875
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1876
-     *                                                 should be ignored when determining whether there are related
1877
-     *                                                 model objects which block this model object's deletion. Useful
1878
-     *                                                 if you know A is related to B and are considering deleting A,
1879
-     *                                                 but want to see if A has any other objects blocking its deletion
1880
-     *                                                 before removing the relation between A and B
1881
-     * @return boolean
1882
-     * @throws \EE_Error
1883
-     */
1884
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1885
-    {
1886
-        //first, if $ignore_this_model_obj was supplied, get its model
1887
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1888
-            $ignored_model = $ignore_this_model_obj->get_model();
1889
-        } else {
1890
-            $ignored_model = null;
1891
-        }
1892
-        //now check all the relations of $this_model_obj_or_id and see if there
1893
-        //are any related model objects blocking it?
1894
-        $is_blocked = false;
1895
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1896
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1897
-                //if $ignore_this_model_obj was supplied, then for the query
1898
-                //on that model needs to be told to ignore $ignore_this_model_obj
1899
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1900
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1901
-                        array(
1902
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1903
-                                '!=',
1904
-                                $ignore_this_model_obj->ID(),
1905
-                            ),
1906
-                        ),
1907
-                    ));
1908
-                } else {
1909
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1910
-                }
1911
-                if ($related_model_objects) {
1912
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1913
-                    $is_blocked = true;
1914
-                }
1915
-            }
1916
-        }
1917
-        return $is_blocked;
1918
-    }
1919
-
1920
-
1921
-
1922
-    /**
1923
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1924
-     * well.
1925
-     *
1926
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1927
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1928
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
1929
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
1930
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
1931
-     *                                      easily corrupt your DB
1932
-     * @throws EE_Error
1933
-     * @return string    everything that comes after the WHERE statement.
1934
-     */
1935
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1936
-    {
1937
-        if ($this->has_primary_key_field()) {
1938
-            $primary_table = $this->_get_main_table();
1939
-            $other_tables = $this->_get_other_tables();
1940
-            $deletes = $query = array();
1941
-            foreach ($objects_for_deletion as $delete_object) {
1942
-                //before we mark this object for deletion,
1943
-                //make sure there's no related objects blocking its deletion (if we're checking)
1944
-                if (
1945
-                    $allow_blocking
1946
-                    && $this->delete_is_blocked_by_related_models(
1947
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
1948
-                    )
1949
-                ) {
1950
-                    continue;
1951
-                }
1952
-                //primary table deletes
1953
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1954
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1955
-                }
1956
-                //other tables
1957
-                if ( ! empty($other_tables)) {
1958
-                    foreach ($other_tables as $ot) {
1959
-                        //first check if we've got the foreign key column here.
1960
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
1961
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1962
-                        }
1963
-                        // wait! it's entirely possible that we'll have a the primary key
1964
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
1965
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
1966
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1967
-                        }
1968
-                        // finally, it is possible that the fk for this table is found
1969
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
1970
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
1971
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1972
-                        }
1973
-                    }
1974
-                }
1975
-            }
1976
-            //we should have deletes now, so let's just go through and setup the where statement
1977
-            foreach ($deletes as $column => $values) {
1978
-                //make sure we have unique $values;
1979
-                $values = array_unique($values);
1980
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
1981
-            }
1982
-            return ! empty($query) ? implode(' AND ', $query) : '';
1983
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
1984
-            $ways_to_identify_a_row = array();
1985
-            $fields = $this->get_combined_primary_key_fields();
1986
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1987
-            foreach ($objects_for_deletion as $delete_object) {
1988
-                $values_for_each_cpk_for_a_row = array();
1989
-                foreach ($fields as $cpk_field) {
1990
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
1991
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1992
-                                                           . "="
1993
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
1994
-                    }
1995
-                }
1996
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1997
-            }
1998
-            return implode(" OR ", $ways_to_identify_a_row);
1999
-        } else {
2000
-            //so there's no primary key and no combined key...
2001
-            //sorry, can't help you
2002
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2003
-                "event_espresso"), get_class($this)));
2004
-        }
2005
-    }
2006
-
2007
-
2008
-
2009
-    /**
2010
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2011
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2012
-     * column
2013
-     *
2014
-     * @param array  $query_params   like EEM_Base::get_all's
2015
-     * @param string $field_to_count field on model to count by (not column name)
2016
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2017
-     *                               that by the setting $distinct to TRUE;
2018
-     * @return int
2019
-     * @throws \EE_Error
2020
-     */
2021
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2022
-    {
2023
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2024
-        if ($field_to_count) {
2025
-            $field_obj = $this->field_settings_for($field_to_count);
2026
-            $column_to_count = $field_obj->get_qualified_column();
2027
-        } elseif ($this->has_primary_key_field()) {
2028
-            $pk_field_obj = $this->get_primary_key_field();
2029
-            $column_to_count = $pk_field_obj->get_qualified_column();
2030
-        } else {
2031
-            //there's no primary key
2032
-            //if we're counting distinct items, and there's no primary key,
2033
-            //we need to list out the columns for distinction;
2034
-            //otherwise we can just use star
2035
-            if ($distinct) {
2036
-                $columns_to_use = array();
2037
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2038
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2039
-                }
2040
-                $column_to_count = implode(',', $columns_to_use);
2041
-            } else {
2042
-                $column_to_count = '*';
2043
-            }
2044
-        }
2045
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2046
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2047
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2048
-    }
2049
-
2050
-
2051
-
2052
-    /**
2053
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2054
-     *
2055
-     * @param array  $query_params like EEM_Base::get_all
2056
-     * @param string $field_to_sum name of field (array key in $_fields array)
2057
-     * @return float
2058
-     * @throws \EE_Error
2059
-     */
2060
-    public function sum($query_params, $field_to_sum = null)
2061
-    {
2062
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2063
-        if ($field_to_sum) {
2064
-            $field_obj = $this->field_settings_for($field_to_sum);
2065
-        } else {
2066
-            $field_obj = $this->get_primary_key_field();
2067
-        }
2068
-        $column_to_count = $field_obj->get_qualified_column();
2069
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2070
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2071
-        $data_type = $field_obj->get_wpdb_data_type();
2072
-        if ($data_type === '%d' || $data_type === '%s') {
2073
-            return (float)$return_value;
2074
-        } else {//must be %f
2075
-            return (float)$return_value;
2076
-        }
2077
-    }
2078
-
2079
-
2080
-
2081
-    /**
2082
-     * Just calls the specified method on $wpdb with the given arguments
2083
-     * Consolidates a little extra error handling code
2084
-     *
2085
-     * @param string $wpdb_method
2086
-     * @param array  $arguments_to_provide
2087
-     * @throws EE_Error
2088
-     * @global wpdb  $wpdb
2089
-     * @return mixed
2090
-     */
2091
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2092
-    {
2093
-        //if we're in maintenance mode level 2, DON'T run any queries
2094
-        //because level 2 indicates the database needs updating and
2095
-        //is probably out of sync with the code
2096
-        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2097
-            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.",
2098
-                "event_espresso")));
2099
-        }
2100
-        /** @type WPDB $wpdb */
2101
-        global $wpdb;
2102
-        if ( ! method_exists($wpdb, $wpdb_method)) {
2103
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2104
-                'event_espresso'), $wpdb_method));
2105
-        }
2106
-        if (WP_DEBUG) {
2107
-            $old_show_errors_value = $wpdb->show_errors;
2108
-            $wpdb->show_errors(false);
2109
-        }
2110
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2111
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2112
-        if (WP_DEBUG) {
2113
-            $wpdb->show_errors($old_show_errors_value);
2114
-            if ( ! empty($wpdb->last_error)) {
2115
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2116
-            } elseif ($result === false) {
2117
-                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"',
2118
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2119
-            }
2120
-        } elseif ($result === false) {
2121
-            EE_Error::add_error(
2122
-                sprintf(
2123
-                    __('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"',
2124
-                        'event_espresso'),
2125
-                    $wpdb_method,
2126
-                    var_export($arguments_to_provide, true),
2127
-                    $wpdb->last_error
2128
-                ),
2129
-                __FILE__,
2130
-                __FUNCTION__,
2131
-                __LINE__
2132
-            );
2133
-        }
2134
-        return $result;
2135
-    }
2136
-
2137
-
2138
-
2139
-    /**
2140
-     * Attempts to run the indicated WPDB method with the provided arguments,
2141
-     * and if there's an error tries to verify the DB is correct. Uses
2142
-     * the static property EEM_Base::$_db_verification_level to determine whether
2143
-     * we should try to fix the EE core db, the addons, or just give up
2144
-     *
2145
-     * @param string $wpdb_method
2146
-     * @param array  $arguments_to_provide
2147
-     * @return mixed
2148
-     */
2149
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2150
-    {
2151
-        /** @type WPDB $wpdb */
2152
-        global $wpdb;
2153
-        $wpdb->last_error = null;
2154
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2155
-        // was there an error running the query? but we don't care on new activations
2156
-        // (we're going to setup the DB anyway on new activations)
2157
-        if (($result === false || ! empty($wpdb->last_error))
2158
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2159
-        ) {
2160
-            switch (EEM_Base::$_db_verification_level) {
2161
-                case EEM_Base::db_verified_none :
2162
-                    // let's double-check core's DB
2163
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2164
-                    break;
2165
-                case EEM_Base::db_verified_core :
2166
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2167
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2168
-                    break;
2169
-                case EEM_Base::db_verified_addons :
2170
-                    // ummmm... you in trouble
2171
-                    return $result;
2172
-                    break;
2173
-            }
2174
-            if ( ! empty($error_message)) {
2175
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2176
-                trigger_error($error_message);
2177
-            }
2178
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2179
-        }
2180
-        return $result;
2181
-    }
2182
-
2183
-
2184
-
2185
-    /**
2186
-     * Verifies the EE core database is up-to-date and records that we've done it on
2187
-     * EEM_Base::$_db_verification_level
2188
-     *
2189
-     * @param string $wpdb_method
2190
-     * @param array  $arguments_to_provide
2191
-     * @return string
2192
-     */
2193
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2194
-    {
2195
-        /** @type WPDB $wpdb */
2196
-        global $wpdb;
2197
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2198
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2199
-        $error_message = sprintf(
2200
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2201
-                'event_espresso'),
2202
-            $wpdb->last_error,
2203
-            $wpdb_method,
2204
-            json_encode($arguments_to_provide)
2205
-        );
2206
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2207
-        return $error_message;
2208
-    }
2209
-
2210
-
2211
-
2212
-    /**
2213
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2214
-     * EEM_Base::$_db_verification_level
2215
-     *
2216
-     * @param $wpdb_method
2217
-     * @param $arguments_to_provide
2218
-     * @return string
2219
-     */
2220
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2221
-    {
2222
-        /** @type WPDB $wpdb */
2223
-        global $wpdb;
2224
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2225
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2226
-        $error_message = sprintf(
2227
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2228
-                'event_espresso'),
2229
-            $wpdb->last_error,
2230
-            $wpdb_method,
2231
-            json_encode($arguments_to_provide)
2232
-        );
2233
-        EE_System::instance()->initialize_addons();
2234
-        return $error_message;
2235
-    }
2236
-
2237
-
2238
-
2239
-    /**
2240
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2241
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2242
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2243
-     * ..."
2244
-     *
2245
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2246
-     * @return string
2247
-     */
2248
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2249
-    {
2250
-        return " FROM " . $model_query_info->get_full_join_sql() .
2251
-               $model_query_info->get_where_sql() .
2252
-               $model_query_info->get_group_by_sql() .
2253
-               $model_query_info->get_having_sql() .
2254
-               $model_query_info->get_order_by_sql() .
2255
-               $model_query_info->get_limit_sql();
2256
-    }
2257
-
2258
-
2259
-
2260
-    /**
2261
-     * Set to easily debug the next X queries ran from this model.
2262
-     *
2263
-     * @param int $count
2264
-     */
2265
-    public function show_next_x_db_queries($count = 1)
2266
-    {
2267
-        $this->_show_next_x_db_queries = $count;
2268
-    }
2269
-
2270
-
2271
-
2272
-    /**
2273
-     * @param $sql_query
2274
-     */
2275
-    public function show_db_query_if_previously_requested($sql_query)
2276
-    {
2277
-        if ($this->_show_next_x_db_queries > 0) {
2278
-            echo $sql_query;
2279
-            $this->_show_next_x_db_queries--;
2280
-        }
2281
-    }
2282
-
2283
-
2284
-
2285
-    /**
2286
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2287
-     * There are the 3 cases:
2288
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2289
-     * $otherModelObject has no ID, it is first saved.
2290
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2291
-     * has no ID, it is first saved.
2292
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2293
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2294
-     * join table
2295
-     *
2296
-     * @param        EE_Base_Class                     /int $thisModelObject
2297
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2298
-     * @param string $relationName                     , key in EEM_Base::_relations
2299
-     *                                                 an attendee to a group, you also want to specify which role they
2300
-     *                                                 will have in that group. So you would use this parameter to
2301
-     *                                                 specify array('role-column-name'=>'role-id')
2302
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2303
-     *                                                 to for relation to methods that allow you to further specify
2304
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2305
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2306
-     *                                                 because these will be inserted in any new rows created as well.
2307
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2308
-     * @throws \EE_Error
2309
-     */
2310
-    public function add_relationship_to(
2311
-        $id_or_obj,
2312
-        $other_model_id_or_obj,
2313
-        $relationName,
2314
-        $extra_join_model_fields_n_values = array()
2315
-    ) {
2316
-        $relation_obj = $this->related_settings_for($relationName);
2317
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2318
-    }
2319
-
2320
-
2321
-
2322
-    /**
2323
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2324
-     * There are the 3 cases:
2325
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2326
-     * error
2327
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2328
-     * an error
2329
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2330
-     *
2331
-     * @param        EE_Base_Class /int $id_or_obj
2332
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2333
-     * @param string $relationName key in EEM_Base::_relations
2334
-     * @return boolean of success
2335
-     * @throws \EE_Error
2336
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2337
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2338
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2339
-     *                             because these will be inserted in any new rows created as well.
2340
-     */
2341
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2342
-    {
2343
-        $relation_obj = $this->related_settings_for($relationName);
2344
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2345
-    }
2346
-
2347
-
2348
-
2349
-    /**
2350
-     * @param mixed           $id_or_obj
2351
-     * @param string          $relationName
2352
-     * @param array           $where_query_params
2353
-     * @param EE_Base_Class[] objects to which relations were removed
2354
-     * @return \EE_Base_Class[]
2355
-     * @throws \EE_Error
2356
-     */
2357
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2358
-    {
2359
-        $relation_obj = $this->related_settings_for($relationName);
2360
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2361
-    }
2362
-
2363
-
2364
-
2365
-    /**
2366
-     * Gets all the related items of the specified $model_name, using $query_params.
2367
-     * Note: by default, we remove the "default query params"
2368
-     * because we want to get even deleted items etc.
2369
-     *
2370
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2371
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2372
-     * @param array  $query_params like EEM_Base::get_all
2373
-     * @return EE_Base_Class[]
2374
-     * @throws \EE_Error
2375
-     */
2376
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2377
-    {
2378
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2379
-        $relation_settings = $this->related_settings_for($model_name);
2380
-        return $relation_settings->get_all_related($model_obj, $query_params);
2381
-    }
2382
-
2383
-
2384
-
2385
-    /**
2386
-     * Deletes all the model objects across the relation indicated by $model_name
2387
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2388
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2389
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2390
-     *
2391
-     * @param EE_Base_Class|int|string $id_or_obj
2392
-     * @param string                   $model_name
2393
-     * @param array                    $query_params
2394
-     * @return int how many deleted
2395
-     * @throws \EE_Error
2396
-     */
2397
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2398
-    {
2399
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2400
-        $relation_settings = $this->related_settings_for($model_name);
2401
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2402
-    }
2403
-
2404
-
2405
-
2406
-    /**
2407
-     * Hard deletes all the model objects across the relation indicated by $model_name
2408
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2409
-     * the model objects can't be hard deleted because of blocking related model objects,
2410
-     * just does a soft-delete on them instead.
2411
-     *
2412
-     * @param EE_Base_Class|int|string $id_or_obj
2413
-     * @param string                   $model_name
2414
-     * @param array                    $query_params
2415
-     * @return int how many deleted
2416
-     * @throws \EE_Error
2417
-     */
2418
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2419
-    {
2420
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2421
-        $relation_settings = $this->related_settings_for($model_name);
2422
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2423
-    }
2424
-
2425
-
2426
-
2427
-    /**
2428
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2429
-     * unless otherwise specified in the $query_params
2430
-     *
2431
-     * @param        int             /EE_Base_Class $id_or_obj
2432
-     * @param string $model_name     like 'Event', or 'Registration'
2433
-     * @param array  $query_params   like EEM_Base::get_all's
2434
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2435
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2436
-     *                               that by the setting $distinct to TRUE;
2437
-     * @return int
2438
-     * @throws \EE_Error
2439
-     */
2440
-    public function count_related(
2441
-        $id_or_obj,
2442
-        $model_name,
2443
-        $query_params = array(),
2444
-        $field_to_count = null,
2445
-        $distinct = false
2446
-    ) {
2447
-        $related_model = $this->get_related_model_obj($model_name);
2448
-        //we're just going to use the query params on the related model's normal get_all query,
2449
-        //except add a condition to say to match the current mod
2450
-        if ( ! isset($query_params['default_where_conditions'])) {
2451
-            $query_params['default_where_conditions'] = 'none';
2452
-        }
2453
-        $this_model_name = $this->get_this_model_name();
2454
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2455
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2456
-        return $related_model->count($query_params, $field_to_count, $distinct);
2457
-    }
2458
-
2459
-
2460
-
2461
-    /**
2462
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2463
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2464
-     *
2465
-     * @param        int           /EE_Base_Class $id_or_obj
2466
-     * @param string $model_name   like 'Event', or 'Registration'
2467
-     * @param array  $query_params like EEM_Base::get_all's
2468
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2469
-     * @return float
2470
-     * @throws \EE_Error
2471
-     */
2472
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2473
-    {
2474
-        $related_model = $this->get_related_model_obj($model_name);
2475
-        if ( ! is_array($query_params)) {
2476
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2477
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2478
-                    gettype($query_params)), '4.6.0');
2479
-            $query_params = array();
2480
-        }
2481
-        //we're just going to use the query params on the related model's normal get_all query,
2482
-        //except add a condition to say to match the current mod
2483
-        if ( ! isset($query_params['default_where_conditions'])) {
2484
-            $query_params['default_where_conditions'] = 'none';
2485
-        }
2486
-        $this_model_name = $this->get_this_model_name();
2487
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2488
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2489
-        return $related_model->sum($query_params, $field_to_sum);
2490
-    }
2491
-
2492
-
2493
-
2494
-    /**
2495
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2496
-     * $modelObject
2497
-     *
2498
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2499
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2500
-     * @param array               $query_params     like EEM_Base::get_all's
2501
-     * @return EE_Base_Class
2502
-     * @throws \EE_Error
2503
-     */
2504
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2505
-    {
2506
-        $query_params['limit'] = 1;
2507
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2508
-        if ($results) {
2509
-            return array_shift($results);
2510
-        } else {
2511
-            return null;
2512
-        }
2513
-    }
2514
-
2515
-
2516
-
2517
-    /**
2518
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2519
-     *
2520
-     * @return string
2521
-     */
2522
-    public function get_this_model_name()
2523
-    {
2524
-        return str_replace("EEM_", "", get_class($this));
2525
-    }
2526
-
2527
-
2528
-
2529
-    /**
2530
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2531
-     *
2532
-     * @return EE_Any_Foreign_Model_Name_Field
2533
-     * @throws EE_Error
2534
-     */
2535
-    public function get_field_containing_related_model_name()
2536
-    {
2537
-        foreach ($this->field_settings(true) as $field) {
2538
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2539
-                $field_with_model_name = $field;
2540
-            }
2541
-        }
2542
-        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2543
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2544
-                $this->get_this_model_name()));
2545
-        }
2546
-        return $field_with_model_name;
2547
-    }
2548
-
2549
-
2550
-
2551
-    /**
2552
-     * Inserts a new entry into the database, for each table.
2553
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2554
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2555
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2556
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2557
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2558
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2559
-     *
2560
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2561
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2562
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2563
-     *                              of EEM_Base)
2564
-     * @return int new primary key on main table that got inserted
2565
-     * @throws EE_Error
2566
-     */
2567
-    public function insert($field_n_values)
2568
-    {
2569
-        /**
2570
-         * Filters the fields and their values before inserting an item using the models
2571
-         *
2572
-         * @param array    $fields_n_values keys are the fields and values are their new values
2573
-         * @param EEM_Base $model           the model used
2574
-         */
2575
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2576
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2577
-            $main_table = $this->_get_main_table();
2578
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2579
-            if ($new_id !== false) {
2580
-                foreach ($this->_get_other_tables() as $other_table) {
2581
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2582
-                }
2583
-            }
2584
-            /**
2585
-             * Done just after attempting to insert a new model object
2586
-             *
2587
-             * @param EEM_Base   $model           used
2588
-             * @param array      $fields_n_values fields and their values
2589
-             * @param int|string the              ID of the newly-inserted model object
2590
-             */
2591
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2592
-            return $new_id;
2593
-        } else {
2594
-            return false;
2595
-        }
2596
-    }
2597
-
2598
-
2599
-
2600
-    /**
2601
-     * Checks that the result would satisfy the unique indexes on this model
2602
-     *
2603
-     * @param array  $field_n_values
2604
-     * @param string $action
2605
-     * @return boolean
2606
-     * @throws \EE_Error
2607
-     */
2608
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2609
-    {
2610
-        foreach ($this->unique_indexes() as $index_name => $index) {
2611
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2612
-            if ($this->exists(array($uniqueness_where_params))) {
2613
-                EE_Error::add_error(
2614
-                    sprintf(
2615
-                        __(
2616
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2617
-                            "event_espresso"
2618
-                        ),
2619
-                        $action,
2620
-                        $this->_get_class_name(),
2621
-                        $index_name,
2622
-                        implode(",", $index->field_names()),
2623
-                        http_build_query($uniqueness_where_params)
2624
-                    ),
2625
-                    __FILE__,
2626
-                    __FUNCTION__,
2627
-                    __LINE__
2628
-                );
2629
-                return false;
2630
-            }
2631
-        }
2632
-        return true;
2633
-    }
2634
-
2635
-
2636
-
2637
-    /**
2638
-     * Checks the database for an item that conflicts (ie, if this item were
2639
-     * saved to the DB would break some uniqueness requirement, like a primary key
2640
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2641
-     * can be either an EE_Base_Class or an array of fields n values
2642
-     *
2643
-     * @param EE_Base_Class|array $obj_or_fields_array
2644
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2645
-     *                                                 when looking for conflicts
2646
-     *                                                 (ie, if false, we ignore the model object's primary key
2647
-     *                                                 when finding "conflicts". If true, it's also considered).
2648
-     *                                                 Only works for INT primary key,
2649
-     *                                                 STRING primary keys cannot be ignored
2650
-     * @throws EE_Error
2651
-     * @return EE_Base_Class|array
2652
-     */
2653
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2654
-    {
2655
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2656
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2657
-        } elseif (is_array($obj_or_fields_array)) {
2658
-            $fields_n_values = $obj_or_fields_array;
2659
-        } else {
2660
-            throw new EE_Error(
2661
-                sprintf(
2662
-                    __(
2663
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2664
-                        "event_espresso"
2665
-                    ),
2666
-                    get_class($this),
2667
-                    $obj_or_fields_array
2668
-                )
2669
-            );
2670
-        }
2671
-        $query_params = array();
2672
-        if ($this->has_primary_key_field()
2673
-            && ($include_primary_key
2674
-                || $this->get_primary_key_field()
2675
-                   instanceof
2676
-                   EE_Primary_Key_String_Field)
2677
-            && isset($fields_n_values[$this->primary_key_name()])
2678
-        ) {
2679
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2680
-        }
2681
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2682
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2683
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2684
-        }
2685
-        //if there is nothing to base this search on, then we shouldn't find anything
2686
-        if (empty($query_params)) {
2687
-            return array();
2688
-        } else {
2689
-            return $this->get_one($query_params);
2690
-        }
2691
-    }
2692
-
2693
-
2694
-
2695
-    /**
2696
-     * Like count, but is optimized and returns a boolean instead of an int
2697
-     *
2698
-     * @param array $query_params
2699
-     * @return boolean
2700
-     * @throws \EE_Error
2701
-     */
2702
-    public function exists($query_params)
2703
-    {
2704
-        $query_params['limit'] = 1;
2705
-        return $this->count($query_params) > 0;
2706
-    }
2707
-
2708
-
2709
-
2710
-    /**
2711
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2712
-     *
2713
-     * @param int|string $id
2714
-     * @return boolean
2715
-     * @throws \EE_Error
2716
-     */
2717
-    public function exists_by_ID($id)
2718
-    {
2719
-        return $this->exists(array('default_where_conditions' => 'none', array($this->primary_key_name() => $id)));
2720
-    }
2721
-
2722
-
2723
-
2724
-    /**
2725
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2726
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2727
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2728
-     * on the main table)
2729
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2730
-     * cases where we want to call it directly rather than via insert().
2731
-     *
2732
-     * @access   protected
2733
-     * @param EE_Table_Base $table
2734
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2735
-     *                                       float
2736
-     * @param int           $new_id          for now we assume only int keys
2737
-     * @throws EE_Error
2738
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2739
-     * @return int ID of new row inserted, or FALSE on failure
2740
-     */
2741
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2742
-    {
2743
-        global $wpdb;
2744
-        $insertion_col_n_values = array();
2745
-        $format_for_insertion = array();
2746
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2747
-        foreach ($fields_on_table as $field_name => $field_obj) {
2748
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2749
-            if ($field_obj->is_auto_increment()) {
2750
-                continue;
2751
-            }
2752
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2753
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2754
-            if ($prepared_value !== null) {
2755
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2756
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2757
-            }
2758
-        }
2759
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2760
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2761
-            //so add the fk to the main table as a column
2762
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2763
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2764
-        }
2765
-        //insert the new entry
2766
-        $result = $this->_do_wpdb_query('insert',
2767
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2768
-        if ($result === false) {
2769
-            return false;
2770
-        }
2771
-        //ok, now what do we return for the ID of the newly-inserted thing?
2772
-        if ($this->has_primary_key_field()) {
2773
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2774
-                return $wpdb->insert_id;
2775
-            } else {
2776
-                //it's not an auto-increment primary key, so
2777
-                //it must have been supplied
2778
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2779
-            }
2780
-        } else {
2781
-            //we can't return a  primary key because there is none. instead return
2782
-            //a unique string indicating this model
2783
-            return $this->get_index_primary_key_string($fields_n_values);
2784
-        }
2785
-    }
2786
-
2787
-
2788
-
2789
-    /**
2790
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2791
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2792
-     * and there is no default, we pass it along. WPDB will take care of it)
2793
-     *
2794
-     * @param EE_Model_Field_Base $field_obj
2795
-     * @param array               $fields_n_values
2796
-     * @return mixed string|int|float depending on what the table column will be expecting
2797
-     * @throws \EE_Error
2798
-     */
2799
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2800
-    {
2801
-        //if this field doesn't allow nullable, don't allow it
2802
-        if ( ! $field_obj->is_nullable()
2803
-             && (
2804
-                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2805
-        ) {
2806
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2807
-        }
2808
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2809
-            : null;
2810
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2811
-    }
2812
-
2813
-
2814
-
2815
-    /**
2816
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2817
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2818
-     * the field's prepare_for_set() method.
2819
-     *
2820
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2821
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2822
-     *                                   top of file)
2823
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2824
-     *                                   $value is a custom selection
2825
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2826
-     */
2827
-    private function _prepare_value_for_use_in_db($value, $field)
2828
-    {
2829
-        if ($field && $field instanceof EE_Model_Field_Base) {
2830
-            switch ($this->_values_already_prepared_by_model_object) {
2831
-                /** @noinspection PhpMissingBreakStatementInspection */
2832
-                case self::not_prepared_by_model_object:
2833
-                    $value = $field->prepare_for_set($value);
2834
-                //purposefully left out "return"
2835
-                case self::prepared_by_model_object:
2836
-                    $value = $field->prepare_for_use_in_db($value);
2837
-                case self::prepared_for_use_in_db:
2838
-                    //leave the value alone
2839
-            }
2840
-            return $value;
2841
-        } else {
2842
-            return $value;
2843
-        }
2844
-    }
2845
-
2846
-
2847
-
2848
-    /**
2849
-     * Returns the main table on this model
2850
-     *
2851
-     * @return EE_Primary_Table
2852
-     * @throws EE_Error
2853
-     */
2854
-    protected function _get_main_table()
2855
-    {
2856
-        foreach ($this->_tables as $table) {
2857
-            if ($table instanceof EE_Primary_Table) {
2858
-                return $table;
2859
-            }
2860
-        }
2861
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2862
-            'event_espresso'), get_class($this)));
2863
-    }
2864
-
2865
-
2866
-
2867
-    /**
2868
-     * table
2869
-     * returns EE_Primary_Table table name
2870
-     *
2871
-     * @return string
2872
-     * @throws \EE_Error
2873
-     */
2874
-    public function table()
2875
-    {
2876
-        return $this->_get_main_table()->get_table_name();
2877
-    }
2878
-
2879
-
2880
-
2881
-    /**
2882
-     * table
2883
-     * returns first EE_Secondary_Table table name
2884
-     *
2885
-     * @return string
2886
-     */
2887
-    public function second_table()
2888
-    {
2889
-        // grab second table from tables array
2890
-        $second_table = end($this->_tables);
2891
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2892
-    }
2893
-
2894
-
2895
-
2896
-    /**
2897
-     * get_table_obj_by_alias
2898
-     * returns table name given it's alias
2899
-     *
2900
-     * @param string $table_alias
2901
-     * @return EE_Primary_Table | EE_Secondary_Table
2902
-     */
2903
-    public function get_table_obj_by_alias($table_alias = '')
2904
-    {
2905
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2906
-    }
2907
-
2908
-
2909
-
2910
-    /**
2911
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2912
-     *
2913
-     * @return EE_Secondary_Table[]
2914
-     */
2915
-    protected function _get_other_tables()
2916
-    {
2917
-        $other_tables = array();
2918
-        foreach ($this->_tables as $table_alias => $table) {
2919
-            if ($table instanceof EE_Secondary_Table) {
2920
-                $other_tables[$table_alias] = $table;
2921
-            }
2922
-        }
2923
-        return $other_tables;
2924
-    }
2925
-
2926
-
2927
-
2928
-    /**
2929
-     * Finds all the fields that correspond to the given table
2930
-     *
2931
-     * @param string $table_alias , array key in EEM_Base::_tables
2932
-     * @return EE_Model_Field_Base[]
2933
-     */
2934
-    public function _get_fields_for_table($table_alias)
2935
-    {
2936
-        return $this->_fields[$table_alias];
2937
-    }
2938
-
2939
-
2940
-
2941
-    /**
2942
-     * Recurses through all the where parameters, and finds all the related models we'll need
2943
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2944
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2945
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2946
-     * related Registration, Transaction, and Payment models.
2947
-     *
2948
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2949
-     * @return EE_Model_Query_Info_Carrier
2950
-     * @throws \EE_Error
2951
-     */
2952
-    public function _extract_related_models_from_query($query_params)
2953
-    {
2954
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
2955
-        if (array_key_exists(0, $query_params)) {
2956
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
2957
-        }
2958
-        if (array_key_exists('group_by', $query_params)) {
2959
-            if (is_array($query_params['group_by'])) {
2960
-                $this->_extract_related_models_from_sub_params_array_values(
2961
-                    $query_params['group_by'],
2962
-                    $query_info_carrier,
2963
-                    'group_by'
2964
-                );
2965
-            } elseif ( ! empty ($query_params['group_by'])) {
2966
-                $this->_extract_related_model_info_from_query_param(
2967
-                    $query_params['group_by'],
2968
-                    $query_info_carrier,
2969
-                    'group_by'
2970
-                );
2971
-            }
2972
-        }
2973
-        if (array_key_exists('having', $query_params)) {
2974
-            $this->_extract_related_models_from_sub_params_array_keys(
2975
-                $query_params[0],
2976
-                $query_info_carrier,
2977
-                'having'
2978
-            );
2979
-        }
2980
-        if (array_key_exists('order_by', $query_params)) {
2981
-            if (is_array($query_params['order_by'])) {
2982
-                $this->_extract_related_models_from_sub_params_array_keys(
2983
-                    $query_params['order_by'],
2984
-                    $query_info_carrier,
2985
-                    'order_by'
2986
-                );
2987
-            } elseif ( ! empty($query_params['order_by'])) {
2988
-                $this->_extract_related_model_info_from_query_param(
2989
-                    $query_params['order_by'],
2990
-                    $query_info_carrier,
2991
-                    'order_by'
2992
-                );
2993
-            }
2994
-        }
2995
-        if (array_key_exists('force_join', $query_params)) {
2996
-            $this->_extract_related_models_from_sub_params_array_values(
2997
-                $query_params['force_join'],
2998
-                $query_info_carrier,
2999
-                'force_join'
3000
-            );
3001
-        }
3002
-        return $query_info_carrier;
3003
-    }
3004
-
3005
-
3006
-
3007
-    /**
3008
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3009
-     *
3010
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3011
-     *                                                      $query_params['having']
3012
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3013
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3014
-     * @throws EE_Error
3015
-     * @return \EE_Model_Query_Info_Carrier
3016
-     */
3017
-    private function _extract_related_models_from_sub_params_array_keys(
3018
-        $sub_query_params,
3019
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3020
-        $query_param_type
3021
-    ) {
3022
-        if ( ! empty($sub_query_params)) {
3023
-            $sub_query_params = (array)$sub_query_params;
3024
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3025
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3026
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3027
-                    $query_param_type);
3028
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3029
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3030
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3031
-                //of array('Registration.TXN_ID'=>23)
3032
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3033
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3034
-                    if ( ! is_array($possibly_array_of_params)) {
3035
-                        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'))",
3036
-                            "event_espresso"),
3037
-                            $param, $possibly_array_of_params));
3038
-                    } else {
3039
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3040
-                            $model_query_info_carrier, $query_param_type);
3041
-                    }
3042
-                } elseif ($query_param_type === 0 //ie WHERE
3043
-                          && is_array($possibly_array_of_params)
3044
-                          && isset($possibly_array_of_params[2])
3045
-                          && $possibly_array_of_params[2] == true
3046
-                ) {
3047
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3048
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3049
-                    //from which we should extract query parameters!
3050
-                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3051
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3052
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3053
-                    }
3054
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3055
-                        $model_query_info_carrier, $query_param_type);
3056
-                }
3057
-            }
3058
-        }
3059
-        return $model_query_info_carrier;
3060
-    }
3061
-
3062
-
3063
-
3064
-    /**
3065
-     * For extracting related models from forced_joins, where the array values contain the info about what
3066
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3067
-     *
3068
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3069
-     *                                                      $query_params['having']
3070
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3071
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3072
-     * @throws EE_Error
3073
-     * @return \EE_Model_Query_Info_Carrier
3074
-     */
3075
-    private function _extract_related_models_from_sub_params_array_values(
3076
-        $sub_query_params,
3077
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3078
-        $query_param_type
3079
-    ) {
3080
-        if ( ! empty($sub_query_params)) {
3081
-            if ( ! is_array($sub_query_params)) {
3082
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3083
-                    $sub_query_params));
3084
-            }
3085
-            foreach ($sub_query_params as $param) {
3086
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3087
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3088
-                    $query_param_type);
3089
-            }
3090
-        }
3091
-        return $model_query_info_carrier;
3092
-    }
3093
-
3094
-
3095
-
3096
-    /**
3097
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3098
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3099
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3100
-     * but use them in a different order. Eg, we need to know what models we are querying
3101
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3102
-     * other models before we can finalize the where clause SQL.
3103
-     *
3104
-     * @param array $query_params
3105
-     * @throws EE_Error
3106
-     * @return EE_Model_Query_Info_Carrier
3107
-     */
3108
-    public function _create_model_query_info_carrier($query_params)
3109
-    {
3110
-        if ( ! is_array($query_params)) {
3111
-            EE_Error::doing_it_wrong(
3112
-                'EEM_Base::_create_model_query_info_carrier',
3113
-                sprintf(
3114
-                    __(
3115
-                        '$query_params should be an array, you passed a variable of type %s',
3116
-                        'event_espresso'
3117
-                    ),
3118
-                    gettype($query_params)
3119
-                ),
3120
-                '4.6.0'
3121
-            );
3122
-            $query_params = array();
3123
-        }
3124
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3125
-        //first check if we should alter the query to account for caps or not
3126
-        //because the caps might require us to do extra joins
3127
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3128
-            $query_params[0] = $where_query_params = array_replace_recursive(
3129
-                $where_query_params,
3130
-                $this->caps_where_conditions(
3131
-                    $query_params['caps']
3132
-                )
3133
-            );
3134
-        }
3135
-        $query_object = $this->_extract_related_models_from_query($query_params);
3136
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3137
-        foreach ($where_query_params as $key => $value) {
3138
-            if (is_int($key)) {
3139
-                throw new EE_Error(
3140
-                    sprintf(
3141
-                        __(
3142
-                            "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.",
3143
-                            "event_espresso"
3144
-                        ),
3145
-                        $key,
3146
-                        var_export($value, true),
3147
-                        var_export($query_params, true),
3148
-                        get_class($this)
3149
-                    )
3150
-                );
3151
-            }
3152
-        }
3153
-        if (
3154
-            array_key_exists('default_where_conditions', $query_params)
3155
-            && ! empty($query_params['default_where_conditions'])
3156
-        ) {
3157
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3158
-        } else {
3159
-            $use_default_where_conditions = 'all';
3160
-        }
3161
-        $where_query_params = array_merge(
3162
-            $this->_get_default_where_conditions_for_models_in_query(
3163
-                $query_object,
3164
-                $use_default_where_conditions,
3165
-                $where_query_params
3166
-            ),
3167
-            $where_query_params
3168
-        );
3169
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3170
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3171
-        // So we need to setup a subquery and use that for the main join.
3172
-        // Note for now this only works on the primary table for the model.
3173
-        // So for instance, you could set the limit array like this:
3174
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3175
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3176
-            $query_object->set_main_model_join_sql(
3177
-                $this->_construct_limit_join_select(
3178
-                    $query_params['on_join_limit'][0],
3179
-                    $query_params['on_join_limit'][1]
3180
-                )
3181
-            );
3182
-        }
3183
-        //set limit
3184
-        if (array_key_exists('limit', $query_params)) {
3185
-            if (is_array($query_params['limit'])) {
3186
-                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3187
-                    $e = sprintf(
3188
-                        __(
3189
-                            "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)",
3190
-                            "event_espresso"
3191
-                        ),
3192
-                        http_build_query($query_params['limit'])
3193
-                    );
3194
-                    throw new EE_Error($e . "|" . $e);
3195
-                }
3196
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3197
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3198
-            } elseif ( ! empty ($query_params['limit'])) {
3199
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3200
-            }
3201
-        }
3202
-        //set order by
3203
-        if (array_key_exists('order_by', $query_params)) {
3204
-            if (is_array($query_params['order_by'])) {
3205
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3206
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3207
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3208
-                if (array_key_exists('order', $query_params)) {
3209
-                    throw new EE_Error(
3210
-                        sprintf(
3211
-                            __(
3212
-                                "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 ",
3213
-                                "event_espresso"
3214
-                            ),
3215
-                            get_class($this),
3216
-                            implode(", ", array_keys($query_params['order_by'])),
3217
-                            implode(", ", $query_params['order_by']),
3218
-                            $query_params['order']
3219
-                        )
3220
-                    );
3221
-                }
3222
-                $this->_extract_related_models_from_sub_params_array_keys(
3223
-                    $query_params['order_by'],
3224
-                    $query_object,
3225
-                    'order_by'
3226
-                );
3227
-                //assume it's an array of fields to order by
3228
-                $order_array = array();
3229
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3230
-                    $order = $this->_extract_order($order);
3231
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3232
-                }
3233
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3234
-            } elseif ( ! empty ($query_params['order_by'])) {
3235
-                $this->_extract_related_model_info_from_query_param(
3236
-                    $query_params['order_by'],
3237
-                    $query_object,
3238
-                    'order',
3239
-                    $query_params['order_by']
3240
-                );
3241
-                $order = isset($query_params['order'])
3242
-                    ? $this->_extract_order($query_params['order'])
3243
-                    : 'DESC';
3244
-                $query_object->set_order_by_sql(
3245
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3246
-                );
3247
-            }
3248
-        }
3249
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3250
-        if ( ! array_key_exists('order_by', $query_params)
3251
-             && array_key_exists('order', $query_params)
3252
-             && ! empty($query_params['order'])
3253
-        ) {
3254
-            $pk_field = $this->get_primary_key_field();
3255
-            $order = $this->_extract_order($query_params['order']);
3256
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3257
-        }
3258
-        //set group by
3259
-        if (array_key_exists('group_by', $query_params)) {
3260
-            if (is_array($query_params['group_by'])) {
3261
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3262
-                $group_by_array = array();
3263
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3264
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3265
-                }
3266
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3267
-            } elseif ( ! empty ($query_params['group_by'])) {
3268
-                $query_object->set_group_by_sql(
3269
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3270
-                );
3271
-            }
3272
-        }
3273
-        //set having
3274
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3275
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3276
-        }
3277
-        //now, just verify they didn't pass anything wack
3278
-        foreach ($query_params as $query_key => $query_value) {
3279
-            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3280
-                throw new EE_Error(
3281
-                    sprintf(
3282
-                        __(
3283
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3284
-                            'event_espresso'
3285
-                        ),
3286
-                        $query_key,
3287
-                        get_class($this),
3288
-                        //						print_r( $this->_allowed_query_params, TRUE )
3289
-                        implode(',', $this->_allowed_query_params)
3290
-                    )
3291
-                );
3292
-            }
3293
-        }
3294
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3295
-        if (empty($main_model_join_sql)) {
3296
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3297
-        }
3298
-        return $query_object;
3299
-    }
3300
-
3301
-
3302
-
3303
-    /**
3304
-     * Gets the where conditions that should be imposed on the query based on the
3305
-     * context (eg reading frontend, backend, edit or delete).
3306
-     *
3307
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3308
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3309
-     * @throws \EE_Error
3310
-     */
3311
-    public function caps_where_conditions($context = self::caps_read)
3312
-    {
3313
-        EEM_Base::verify_is_valid_cap_context($context);
3314
-        $cap_where_conditions = array();
3315
-        $cap_restrictions = $this->caps_missing($context);
3316
-        /**
3317
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3318
-         */
3319
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3320
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3321
-                $restriction_if_no_cap->get_default_where_conditions());
3322
-        }
3323
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3324
-            $cap_restrictions);
3325
-    }
3326
-
3327
-
3328
-
3329
-    /**
3330
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3331
-     * otherwise throws an exception
3332
-     *
3333
-     * @param string $should_be_order_string
3334
-     * @return string either ASC, asc, DESC or desc
3335
-     * @throws EE_Error
3336
-     */
3337
-    private function _extract_order($should_be_order_string)
3338
-    {
3339
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3340
-            return $should_be_order_string;
3341
-        } else {
3342
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3343
-                "event_espresso"), get_class($this), $should_be_order_string));
3344
-        }
3345
-    }
3346
-
3347
-
3348
-
3349
-    /**
3350
-     * Looks at all the models which are included in this query, and asks each
3351
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3352
-     * so they can be merged
3353
-     *
3354
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3355
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3356
-     *                                                                  'none' means NO default where conditions will
3357
-     *                                                                  be used AT ALL during this query.
3358
-     *                                                                  'other_models_only' means default where
3359
-     *                                                                  conditions from other models will be used, but
3360
-     *                                                                  not for this primary model. 'all', the default,
3361
-     *                                                                  means default where conditions will apply as
3362
-     *                                                                  normal
3363
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3364
-     * @throws EE_Error
3365
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3366
-     */
3367
-    private function _get_default_where_conditions_for_models_in_query(
3368
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3369
-        $use_default_where_conditions = 'all',
3370
-        $where_query_params = array()
3371
-    ) {
3372
-        $allowed_used_default_where_conditions_values = array(
3373
-            'all',
3374
-            'this_model_only',
3375
-            'other_models_only',
3376
-            'minimum',
3377
-            'none',
3378
-        );
3379
-        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3380
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3381
-                "event_espresso"), $use_default_where_conditions,
3382
-                implode(", ", $allowed_used_default_where_conditions_values)));
3383
-        }
3384
-        $universal_query_params = array();
3385
-        if ($use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only') {
3386
-            $universal_query_params = $this->_get_default_where_conditions();
3387
-        } else if ($use_default_where_conditions === 'minimum') {
3388
-            $universal_query_params = $this->_get_minimum_where_conditions();
3389
-        }
3390
-        if (in_array($use_default_where_conditions, array('all', 'other_models_only'))) {
3391
-            foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3392
-                $related_model = $this->get_related_model_obj($model_name);
3393
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3394
-                $overrides = $this->_override_defaults_or_make_null_friendly(
3395
-                    $related_model_universal_where_params,
3396
-                    $where_query_params,
3397
-                    $related_model,
3398
-                    $model_relation_path
3399
-                );
3400
-                $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3401
-                    $universal_query_params,
3402
-                    $overrides
3403
-                );
3404
-            }
3405
-        }
3406
-        return $universal_query_params;
3407
-    }
3408
-
3409
-
3410
-
3411
-    /**
3412
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3413
-     * then we also add a special where condition which allows for that model's primary key
3414
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3415
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3416
-     *
3417
-     * @param array    $default_where_conditions
3418
-     * @param array    $provided_where_conditions
3419
-     * @param EEM_Base $model
3420
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3421
-     * @return array like EEM_Base::get_all's $query_params[0]
3422
-     * @throws \EE_Error
3423
-     */
3424
-    private function _override_defaults_or_make_null_friendly(
3425
-        $default_where_conditions,
3426
-        $provided_where_conditions,
3427
-        $model,
3428
-        $model_relation_path
3429
-    ) {
3430
-        $null_friendly_where_conditions = array();
3431
-        $none_overridden = true;
3432
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3433
-        foreach ($default_where_conditions as $key => $val) {
3434
-            if (isset($provided_where_conditions[$key])) {
3435
-                $none_overridden = false;
3436
-            } else {
3437
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3438
-            }
3439
-        }
3440
-        if ($none_overridden && $default_where_conditions) {
3441
-            if ($model->has_primary_key_field()) {
3442
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3443
-                                                                                . "."
3444
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3445
-            }/*else{
32
+	//admin posty
33
+	//basic -> grants access to mine -> if they don't have it, select none
34
+	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
+	//*_published -> grants access to published -> if they dont have it, select non-published
37
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
39
+	//frontend posty
40
+	//by default has access to published
41
+	//basic -> grants access to mine that arent published, and all published
42
+	//*_others ->grants access to others that arent private, all mine
43
+	//*_private -> grants full access
44
+	//frontend non-posty
45
+	//like admin posty
46
+	//category-y
47
+	//assign -> grants access to join-table
48
+	//(delete, edit)
49
+	//payment-method-y
50
+	//for each registered payment method,
51
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
+	/**
53
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
56
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_values_already_prepared_by_model_object = 0;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the data is just like form input that needs to have the model fields'
65
+	 * prepare_for_set and prepare_for_use_in_db called on it
66
+	 */
67
+	const not_prepared_by_model_object = 0;
68
+
69
+	/**
70
+	 * when $_values_already_prepared_by_model_object equals this, we
71
+	 * assume this value is coming from a model object and doesn't need to have
72
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
+	 */
74
+	const prepared_by_model_object = 1;
75
+
76
+	/**
77
+	 * when $_values_already_prepared_by_model_object equals this, we assume
78
+	 * the values are already to be used in the database (ie no processing is done
79
+	 * on them by the model's fields)
80
+	 */
81
+	const prepared_for_use_in_db = 2;
82
+
83
+
84
+	protected $singular_item = 'Item';
85
+
86
+	protected $plural_item   = 'Items';
87
+
88
+	/**
89
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
+	 */
91
+	protected $_tables;
92
+
93
+	/**
94
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
+	 *
98
+	 * @var \EE_Model_Field_Base[] $_fields
99
+	 */
100
+	protected $_fields;
101
+
102
+	/**
103
+	 * array of different kinds of relations
104
+	 *
105
+	 * @var \EE_Model_Relation_Base[] $_model_relations
106
+	 */
107
+	protected $_model_relations;
108
+
109
+	/**
110
+	 * @var \EE_Index[] $_indexes
111
+	 */
112
+	protected $_indexes = array();
113
+
114
+	/**
115
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
116
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
+	 * by setting the same columns as used in these queries in the query yourself.
118
+	 *
119
+	 * @var EE_Default_Where_Conditions
120
+	 */
121
+	protected $_default_where_conditions_strategy;
122
+
123
+	/**
124
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
+	 * This is particularly useful when you want something between 'none' and 'default'
126
+	 *
127
+	 * @var EE_Default_Where_Conditions
128
+	 */
129
+	protected $_minimum_where_conditions_strategy;
130
+
131
+	/**
132
+	 * String describing how to find the "owner" of this model's objects.
133
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
+	 * But when there isn't, this indicates which related model, or transiently-related model,
135
+	 * has the foreign key to the wp_users table.
136
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
+	 * related to events, and events have a foreign key to wp_users.
138
+	 * On EEM_Transaction, this would be 'Transaction.Event'
139
+	 *
140
+	 * @var string
141
+	 */
142
+	protected $_model_chain_to_wp_user = '';
143
+
144
+	/**
145
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
+	 * don't need it (particularly CPT models)
147
+	 *
148
+	 * @var bool
149
+	 */
150
+	protected $_ignore_where_strategy = false;
151
+
152
+	/**
153
+	 * String used in caps relating to this model. Eg, if the caps relating to this
154
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
+	 *
156
+	 * @var string. If null it hasn't been initialized yet. If false then we
157
+	 * have indicated capabilities don't apply to this
158
+	 */
159
+	protected $_caps_slug = null;
160
+
161
+	/**
162
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
+	 * and next-level keys are capability names, and each's value is a
164
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
166
+	 * and then each capability in the corresponding sub-array that they're missing
167
+	 * adds the where conditions onto the query.
168
+	 *
169
+	 * @var array
170
+	 */
171
+	protected $_cap_restrictions = array(
172
+		self::caps_read       => array(),
173
+		self::caps_read_admin => array(),
174
+		self::caps_edit       => array(),
175
+		self::caps_delete     => array(),
176
+	);
177
+
178
+	/**
179
+	 * Array defining which cap restriction generators to use to create default
180
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
181
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
+	 * automatically set this to false (not just null).
184
+	 *
185
+	 * @var EE_Restriction_Generator_Base[]
186
+	 */
187
+	protected $_cap_restriction_generators = array();
188
+
189
+	/**
190
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
+	 */
192
+	const caps_read       = 'read';
193
+
194
+	const caps_read_admin = 'read_admin';
195
+
196
+	const caps_edit       = 'edit';
197
+
198
+	const caps_delete     = 'delete';
199
+
200
+	/**
201
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
+	 * maps to 'read' because when looking for relevant permissions we're going to use
204
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_cap_contexts_to_cap_action_map = array(
209
+		self::caps_read       => 'read',
210
+		self::caps_read_admin => 'read',
211
+		self::caps_edit       => 'edit',
212
+		self::caps_delete     => 'delete',
213
+	);
214
+
215
+	/**
216
+	 * Timezone
217
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
+	 * EE_Datetime_Field data type will have access to it.
221
+	 *
222
+	 * @var string
223
+	 */
224
+	protected $_timezone;
225
+
226
+
227
+	/**
228
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
+	 * multisite.
230
+	 *
231
+	 * @var int
232
+	 */
233
+	protected static $_model_query_blog_id;
234
+
235
+	/**
236
+	 * A copy of _fields, except the array keys are the model names pointed to by
237
+	 * the field
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cache_foreign_key_to_fields = array();
242
+
243
+	/**
244
+	 * Cached list of all the fields on the model, indexed by their name
245
+	 *
246
+	 * @var EE_Model_Field_Base[]
247
+	 */
248
+	private $_cached_fields = null;
249
+
250
+	/**
251
+	 * Cached list of all the fields on the model, except those that are
252
+	 * marked as only pertinent to the database
253
+	 *
254
+	 * @var EE_Model_Field_Base[]
255
+	 */
256
+	private $_cached_fields_non_db_only = null;
257
+
258
+	/**
259
+	 * A cached reference to the primary key for quick lookup
260
+	 *
261
+	 * @var EE_Model_Field_Base
262
+	 */
263
+	private $_primary_key_field = null;
264
+
265
+	/**
266
+	 * Flag indicating whether this model has a primary key or not
267
+	 *
268
+	 * @var boolean
269
+	 */
270
+	protected $_has_primary_key_field = null;
271
+
272
+	/**
273
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
274
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
+	 *
276
+	 * @var boolean
277
+	 */
278
+	protected $_wp_core_model = false;
279
+
280
+	/**
281
+	 *    List of valid operators that can be used for querying.
282
+	 * The keys are all operators we'll accept, the values are the real SQL
283
+	 * operators used
284
+	 *
285
+	 * @var array
286
+	 */
287
+	protected $_valid_operators = array(
288
+		'='           => '=',
289
+		'<='          => '<=',
290
+		'<'           => '<',
291
+		'>='          => '>=',
292
+		'>'           => '>',
293
+		'!='          => '!=',
294
+		'LIKE'        => 'LIKE',
295
+		'like'        => 'LIKE',
296
+		'NOT_LIKE'    => 'NOT LIKE',
297
+		'not_like'    => 'NOT LIKE',
298
+		'NOT LIKE'    => 'NOT LIKE',
299
+		'not like'    => 'NOT LIKE',
300
+		'IN'          => 'IN',
301
+		'in'          => 'IN',
302
+		'NOT_IN'      => 'NOT IN',
303
+		'not_in'      => 'NOT IN',
304
+		'NOT IN'      => 'NOT IN',
305
+		'not in'      => 'NOT IN',
306
+		'between'     => 'BETWEEN',
307
+		'BETWEEN'     => 'BETWEEN',
308
+		'IS_NOT_NULL' => 'IS NOT NULL',
309
+		'is_not_null' => 'IS NOT NULL',
310
+		'IS NOT NULL' => 'IS NOT NULL',
311
+		'is not null' => 'IS NOT NULL',
312
+		'IS_NULL'     => 'IS NULL',
313
+		'is_null'     => 'IS NULL',
314
+		'IS NULL'     => 'IS NULL',
315
+		'is null'     => 'IS NULL',
316
+		'REGEXP'      => 'REGEXP',
317
+		'regexp'      => 'REGEXP',
318
+		'NOT_REGEXP'  => 'NOT REGEXP',
319
+		'not_regexp'  => 'NOT REGEXP',
320
+		'NOT REGEXP'  => 'NOT REGEXP',
321
+		'not regexp'  => 'NOT REGEXP',
322
+	);
323
+
324
+	/**
325
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
+	 *
327
+	 * @var array
328
+	 */
329
+	protected $_in_style_operators = array('IN', 'NOT IN');
330
+
331
+	/**
332
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
+	 * '12-31-2012'"
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_between_style_operators = array('BETWEEN');
338
+
339
+	/**
340
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
+	 * on a join table.
342
+	 *
343
+	 * @var array
344
+	 */
345
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
+
347
+	/**
348
+	 * Allowed values for $query_params['order'] for ordering in queries
349
+	 *
350
+	 * @var array
351
+	 */
352
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
+
354
+	/**
355
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
+
362
+	/**
363
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
365
+	 *
366
+	 * @var array
367
+	 */
368
+	private $_allowed_query_params = array(
369
+		0,
370
+		'limit',
371
+		'order_by',
372
+		'group_by',
373
+		'having',
374
+		'force_join',
375
+		'order',
376
+		'on_join_limit',
377
+		'default_where_conditions',
378
+		'caps',
379
+	);
380
+
381
+	/**
382
+	 * All the data types that can be used in $wpdb->prepare statements.
383
+	 *
384
+	 * @var array
385
+	 */
386
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
+
388
+	/**
389
+	 *    EE_Registry Object
390
+	 *
391
+	 * @var    object
392
+	 * @access    protected
393
+	 */
394
+	protected $EE = null;
395
+
396
+
397
+	/**
398
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
+	 *
400
+	 * @var int
401
+	 */
402
+	protected $_show_next_x_db_queries = 0;
403
+
404
+	/**
405
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
+	 *
408
+	 * @var array
409
+	 */
410
+	protected $_custom_selections = array();
411
+
412
+	/**
413
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
+	 * caches every model object we've fetched from the DB on this request
415
+	 *
416
+	 * @var array
417
+	 */
418
+	protected $_entity_map;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has not yet verified the db on this http request
422
+	 */
423
+	const db_verified_none = 0;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
427
+	 * but not the addons' dbs
428
+	 */
429
+	const db_verified_core = 1;
430
+
431
+	/**
432
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
+	 * the EE core db too)
434
+	 */
435
+	const db_verified_addons = 2;
436
+
437
+	/**
438
+	 * indicates whether an EEM_Base child has already re-verified the DB
439
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
440
+	 * looking like EEM_Base::db_verified_*
441
+	 *
442
+	 * @var int - 0 = none, 1 = core, 2 = addons
443
+	 */
444
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
445
+
446
+
447
+
448
+	/**
449
+	 * About all child constructors:
450
+	 * they should define the _tables, _fields and _model_relations arrays.
451
+	 * Should ALWAYS be called after child constructor.
452
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
453
+	 * finalizes constructing all the object's attributes.
454
+	 * Generally, rather than requiring a child to code
455
+	 * $this->_tables = array(
456
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
457
+	 *        ...);
458
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
459
+	 * each EE_Table has a function to set the table's alias after the constructor, using
460
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
461
+	 * do something similar.
462
+	 *
463
+	 * @param null $timezone
464
+	 * @throws \EE_Error
465
+	 */
466
+	protected function __construct($timezone = null)
467
+	{
468
+		// check that the model has not been loaded too soon
469
+		if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
+			throw new EE_Error (
471
+				sprintf(
472
+					__('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.',
473
+						'event_espresso'),
474
+					get_class($this)
475
+				)
476
+			);
477
+		}
478
+		/**
479
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
480
+		 */
481
+		if (empty(EEM_Base::$_model_query_blog_id)) {
482
+			EEM_Base::set_model_query_blog_id();
483
+		}
484
+		/**
485
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
486
+		 * just use EE_Register_Model_Extension
487
+		 *
488
+		 * @var EE_Table_Base[] $_tables
489
+		 */
490
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
491
+		foreach ($this->_tables as $table_alias => $table_obj) {
492
+			/** @var $table_obj EE_Table_Base */
493
+			$table_obj->_construct_finalize_with_alias($table_alias);
494
+			if ($table_obj instanceof EE_Secondary_Table) {
495
+				/** @var $table_obj EE_Secondary_Table */
496
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
497
+			}
498
+		}
499
+		/**
500
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
501
+		 * EE_Register_Model_Extension
502
+		 *
503
+		 * @param EE_Model_Field_Base[] $_fields
504
+		 */
505
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
506
+		$this->_invalidate_field_caches();
507
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
508
+			if ( ! array_key_exists($table_alias, $this->_tables)) {
509
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
511
+			}
512
+			foreach ($fields_for_table as $field_name => $field_obj) {
513
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
514
+				//primary key field base has a slightly different _construct_finalize
515
+				/** @var $field_obj EE_Model_Field_Base */
516
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
517
+			}
518
+		}
519
+		// everything is related to Extra_Meta
520
+		if (get_class($this) !== 'EEM_Extra_Meta') {
521
+			//make extra meta related to everything, but don't block deleting things just
522
+			//because they have related extra meta info. For now just orphan those extra meta
523
+			//in the future we should automatically delete them
524
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
525
+		}
526
+		//and change logs
527
+		if (get_class($this) !== 'EEM_Change_Log') {
528
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
529
+		}
530
+		/**
531
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
532
+		 * EE_Register_Model_Extension
533
+		 *
534
+		 * @param EE_Model_Relation_Base[] $_model_relations
535
+		 */
536
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
537
+			$this->_model_relations);
538
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
539
+			/** @var $relation_obj EE_Model_Relation_Base */
540
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
541
+		}
542
+		foreach ($this->_indexes as $index_name => $index_obj) {
543
+			/** @var $index_obj EE_Index */
544
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
545
+		}
546
+		$this->set_timezone($timezone);
547
+		//finalize default where condition strategy, or set default
548
+		if ( ! $this->_default_where_conditions_strategy) {
549
+			//nothing was set during child constructor, so set default
550
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551
+		}
552
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
553
+		if ( ! $this->_minimum_where_conditions_strategy) {
554
+			//nothing was set during child constructor, so set default
555
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556
+		}
557
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
558
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
559
+		//to indicate to NOT set it, set it to the logical default
560
+		if ($this->_caps_slug === null) {
561
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
562
+		}
563
+		//initialize the standard cap restriction generators if none were specified by the child constructor
564
+		if ($this->_cap_restriction_generators !== false) {
565
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
+				if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
568
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569
+						new EE_Restriction_Generator_Protected(),
570
+						$cap_context,
571
+						$this
572
+					);
573
+				}
574
+			}
575
+		}
576
+		//if there are cap restriction generators, use them to make the default cap restrictions
577
+		if ($this->_cap_restriction_generators !== false) {
578
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
+				if ( ! $generator_object) {
580
+					continue;
581
+				}
582
+				if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583
+					throw new EE_Error(
584
+						sprintf(
585
+							__('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.',
586
+								'event_espresso'),
587
+							$context,
588
+							$this->get_this_model_name()
589
+						)
590
+					);
591
+				}
592
+				$action = $this->cap_action_for_context($context);
593
+				if ( ! $generator_object->construction_finalized()) {
594
+					$generator_object->_construct_finalize($this, $action);
595
+				}
596
+			}
597
+		}
598
+		do_action('AHEE__' . get_class($this) . '__construct__end');
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * Generates the cap restrictions for the given context, or if they were
605
+	 * already generated just gets what's cached
606
+	 *
607
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
608
+	 * @return EE_Default_Where_Conditions[]
609
+	 */
610
+	protected function _generate_cap_restrictions($context)
611
+	{
612
+		if (isset($this->_cap_restriction_generators[$context])
613
+			&& $this->_cap_restriction_generators[$context]
614
+			   instanceof
615
+			   EE_Restriction_Generator_Base
616
+		) {
617
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
618
+		} else {
619
+			return array();
620
+		}
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * Used to set the $_model_query_blog_id static property.
627
+	 *
628
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
629
+	 *                      value for get_current_blog_id() will be used.
630
+	 */
631
+	public static function set_model_query_blog_id($blog_id = 0)
632
+	{
633
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
634
+	}
635
+
636
+
637
+
638
+	/**
639
+	 * Returns whatever is set as the internal $model_query_blog_id.
640
+	 *
641
+	 * @return int
642
+	 */
643
+	public static function get_model_query_blog_id()
644
+	{
645
+		return EEM_Base::$_model_query_blog_id;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 *        This function is a singleton method used to instantiate the Espresso_model object
652
+	 *
653
+	 * @access public
654
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
655
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
656
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
657
+	 *                         timezone in the 'timezone_string' wp option)
658
+	 * @return static (as in the concrete child class)
659
+	 */
660
+	public static function instance($timezone = null)
661
+	{
662
+		// check if instance of Espresso_model already exists
663
+		if ( ! static::$_instance instanceof static) {
664
+			// instantiate Espresso_model
665
+			static::$_instance = new static($timezone);
666
+		}
667
+		//we might have a timezone set, let set_timezone decide what to do with it
668
+		static::$_instance->set_timezone($timezone);
669
+		// Espresso_model object
670
+		return static::$_instance;
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * resets the model and returns it
677
+	 *
678
+	 * @param null | string $timezone
679
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
680
+	 * all its properties reset; if it wasn't instantiated, returns null)
681
+	 */
682
+	public static function reset($timezone = null)
683
+	{
684
+		if (static::$_instance instanceof EEM_Base) {
685
+			//let's try to NOT swap out the current instance for a new one
686
+			//because if someone has a reference to it, we can't remove their reference
687
+			//so it's best to keep using the same reference, but change the original object
688
+			//reset all its properties to their original values as defined in the class
689
+			$r = new ReflectionClass(get_class(static::$_instance));
690
+			$static_properties = $r->getStaticProperties();
691
+			foreach ($r->getDefaultProperties() as $property => $value) {
692
+				//don't set instance to null like it was originally,
693
+				//but it's static anyways, and we're ignoring static properties (for now at least)
694
+				if ( ! isset($static_properties[$property])) {
695
+					static::$_instance->{$property} = $value;
696
+				}
697
+			}
698
+			//and then directly call its constructor again, like we would if we
699
+			//were creating a new one
700
+			static::$_instance->__construct($timezone);
701
+			return self::instance();
702
+		}
703
+		return null;
704
+	}
705
+
706
+
707
+
708
+	/**
709
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
710
+	 *
711
+	 * @param  boolean $translated return localized strings or JUST the array.
712
+	 * @return array
713
+	 * @throws \EE_Error
714
+	 */
715
+	public function status_array($translated = false)
716
+	{
717
+		if ( ! array_key_exists('Status', $this->_model_relations)) {
718
+			return array();
719
+		}
720
+		$model_name = $this->get_this_model_name();
721
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
722
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
723
+		$status_array = array();
724
+		foreach ($stati as $status) {
725
+			$status_array[$status->ID()] = $status->get('STS_code');
726
+		}
727
+		return $translated
728
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
729
+			: $status_array;
730
+	}
731
+
732
+
733
+
734
+	/**
735
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
736
+	 *
737
+	 * @param array $query_params             {
738
+	 * @var array $0 (where) array {
739
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
740
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
741
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
742
+	 *                                        conditions based on related models (and even
743
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
744
+	 *                                        name. Eg,
745
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
746
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
747
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
748
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
749
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically
750
+	 *                                        took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having
751
+	 *                                        "Venue.VNU_ID", you could have
752
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
753
+	 *                                        events are related to Registrations, which are related to Attendees). You
754
+	 *                                        can take it even further with
755
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
756
+	 *                                        (from the default of '='), change the value to an numerically-indexed
757
+	 *                                        array, where the first item in the list is the operator. eg: array(
758
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
759
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
760
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
761
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
762
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can
763
+	 *                                        also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
764
+	 *                                        eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field
765
+	 *                                        name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default
766
+	 *                                        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__>' =>
767
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' =>
768
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
769
+	 *                                        but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND.
770
+	 *                                        eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
771
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes
772
+	 *                                        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
773
+	 *                                        place two or more where conditions applying to the same field. eg:
774
+	 *                                        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
775
+	 *                                        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 '*'
776
+	 *                                        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
777
+	 *                                        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 >>
778
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg:
779
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
780
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
781
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
782
+	 *                                        and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
783
+	 *                                        the OFFSET, the 2nd is the LIMIT
784
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
785
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
786
+	 *                                        => array( 'table_alias', array(1,2) ) ).
787
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
788
+	 *                                        values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
789
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
790
+	 *                                        'where' conditions, these fields can be on related models. Eg
791
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
792
+	 *                                        to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
793
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
794
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
795
+	 *                                        Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
796
+	 *                                        want to order by the primary key. Eg,
797
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
798
+	 *                                        with the Datetime model's table(s) and order by its field DTT_EVT_start) or
799
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
800
+	 *                                        wp_esp_registration ORDER BY REG_ID ASC"
801
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
802
+	 *                                        'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
803
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
804
+	 *                                        primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
805
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
806
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
807
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped results)
808
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
809
+	 *                                        array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
810
+	 *                                        join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
811
+	 *                                        to do this in hopes of increasing efficiency, as related models which belongs to the current model
812
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
813
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
814
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
815
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
816
+	 *                                        filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
817
+	 *                                        model's default where conditions set it to 'other_models_only'. If you only want this model's default where
818
+	 *                                        conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
819
+	 *                                        (default), set to 'all'.
820
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
821
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
822
+	 *                                        the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
823
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
824
+	 *                                        }
825
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
826
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
827
+	 *                                        are object IDs (if there is a primary key on the model. if not, numerically indexed)
828
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
829
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
830
+	 *                                        'OR'=>array(
831
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
832
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
833
+	 *                                        )
834
+	 *                                        ),
835
+	 *                                        'limit'=>10,
836
+	 *                                        'group_by'=>'TXN_ID'
837
+	 *                                        ));
838
+	 *                                        get all the answers to the question titled "shirt size" for event with id
839
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
840
+	 *                                        'Question.QST_display_text'=>'shirt size',
841
+	 *                                        'Registration.Event.EVT_ID'=>12
842
+	 *                                        ),
843
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
844
+	 *                                        ));
845
+	 * @throws \EE_Error
846
+	 */
847
+	public function get_all($query_params = array())
848
+	{
849
+		if (isset($query_params['limit'])
850
+			&& ! isset($query_params['group_by'])
851
+		) {
852
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
853
+		}
854
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
855
+	}
856
+
857
+
858
+
859
+	/**
860
+	 * Modifies the query parameters so we only get back model objects
861
+	 * that "belong" to the current user
862
+	 *
863
+	 * @param array $query_params @see EEM_Base::get_all()
864
+	 * @return array like EEM_Base::get_all
865
+	 */
866
+	public function alter_query_params_to_only_include_mine($query_params = array())
867
+	{
868
+		$wp_user_field_name = $this->wp_user_field_name();
869
+		if ($wp_user_field_name) {
870
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
871
+		}
872
+		return $query_params;
873
+	}
874
+
875
+
876
+
877
+	/**
878
+	 * Returns the name of the field's name that points to the WP_User table
879
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
880
+	 * foreign key to the WP_User table)
881
+	 *
882
+	 * @return string|boolean string on success, boolean false when there is no
883
+	 * foreign key to the WP_User table
884
+	 */
885
+	public function wp_user_field_name()
886
+	{
887
+		try {
888
+			if ( ! empty($this->_model_chain_to_wp_user)) {
889
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
890
+				$last_model_name = end($models_to_follow_to_wp_users);
891
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
892
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
893
+			} else {
894
+				$model_with_fk_to_wp_users = $this;
895
+				$model_chain_to_wp_user = '';
896
+			}
897
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
898
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
899
+		} catch (EE_Error $e) {
900
+			return false;
901
+		}
902
+	}
903
+
904
+
905
+
906
+	/**
907
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
908
+	 * (or transiently-related model) has a foreign key to the wp_users table;
909
+	 * useful for finding if model objects of this type are 'owned' by the current user.
910
+	 * This is an empty string when the foreign key is on this model and when it isn't,
911
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
912
+	 * (or transiently-related model)
913
+	 *
914
+	 * @return string
915
+	 */
916
+	public function model_chain_to_wp_user()
917
+	{
918
+		return $this->_model_chain_to_wp_user;
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
925
+	 * like how registrations don't have a foreign key to wp_users, but the
926
+	 * events they are for are), or is unrelated to wp users.
927
+	 * generally available
928
+	 *
929
+	 * @return boolean
930
+	 */
931
+	public function is_owned()
932
+	{
933
+		if ($this->model_chain_to_wp_user()) {
934
+			return true;
935
+		} else {
936
+			try {
937
+				$this->get_foreign_key_to('WP_User');
938
+				return true;
939
+			} catch (EE_Error $e) {
940
+				return false;
941
+			}
942
+		}
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
949
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
950
+	 * the model)
951
+	 *
952
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
953
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
954
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
955
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
956
+	 *                                  override this and set the select to "*", or a specific column name, like
957
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
958
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
959
+	 *                                  the aliases used to refer to this selection, and values are to be
960
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
961
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
962
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
963
+	 * @throws \EE_Error
964
+	 */
965
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
966
+	{
967
+		// remember the custom selections, if any, and type cast as array
968
+		// (unless $columns_to_select is an object, then just set as an empty array)
969
+		// Note: (array) 'some string' === array( 'some string' )
970
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
971
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
972
+		$select_expressions = $columns_to_select !== null
973
+			? $this->_construct_select_from_input($columns_to_select)
974
+			: $this->_construct_default_select_sql($model_query_info);
975
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
976
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
977
+	}
978
+
979
+
980
+
981
+	/**
982
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
983
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
984
+	 * take care of joins, field preparation etc.
985
+	 *
986
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
987
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
988
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
989
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
990
+	 *                                  override this and set the select to "*", or a specific column name, like
991
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
992
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
993
+	 *                                  the aliases used to refer to this selection, and values are to be
994
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
995
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
996
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
997
+	 * @throws \EE_Error
998
+	 */
999
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1000
+	{
1001
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1002
+	}
1003
+
1004
+
1005
+
1006
+	/**
1007
+	 * For creating a custom select statement
1008
+	 *
1009
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1010
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1011
+	 *                                 SQL, and 1=>is the datatype
1012
+	 * @throws EE_Error
1013
+	 * @return string
1014
+	 */
1015
+	private function _construct_select_from_input($columns_to_select)
1016
+	{
1017
+		if (is_array($columns_to_select)) {
1018
+			$select_sql_array = array();
1019
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1020
+				if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1021
+					throw new EE_Error(
1022
+						sprintf(
1023
+							__(
1024
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1025
+								"event_espresso"
1026
+							),
1027
+							$selection_and_datatype,
1028
+							$alias
1029
+						)
1030
+					);
1031
+				}
1032
+				if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1033
+					throw new EE_Error(
1034
+						sprintf(
1035
+							__(
1036
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1037
+								"event_espresso"
1038
+							),
1039
+							$selection_and_datatype[1],
1040
+							$selection_and_datatype[0],
1041
+							$alias,
1042
+							implode(",", $this->_valid_wpdb_data_types)
1043
+						)
1044
+					);
1045
+				}
1046
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1047
+			}
1048
+			$columns_to_select_string = implode(", ", $select_sql_array);
1049
+		} else {
1050
+			$columns_to_select_string = $columns_to_select;
1051
+		}
1052
+		return $columns_to_select_string;
1053
+	}
1054
+
1055
+
1056
+
1057
+	/**
1058
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1059
+	 *
1060
+	 * @return string
1061
+	 * @throws \EE_Error
1062
+	 */
1063
+	public function primary_key_name()
1064
+	{
1065
+		return $this->get_primary_key_field()->get_name();
1066
+	}
1067
+
1068
+
1069
+
1070
+	/**
1071
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1072
+	 * If there is no primary key on this model, $id is treated as primary key string
1073
+	 *
1074
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1075
+	 * @return EE_Base_Class
1076
+	 */
1077
+	public function get_one_by_ID($id)
1078
+	{
1079
+		if ($this->get_from_entity_map($id)) {
1080
+			return $this->get_from_entity_map($id);
1081
+		}
1082
+		return $this->get_one(
1083
+			$this->alter_query_params_to_restrict_by_ID(
1084
+				$id,
1085
+				array('default_where_conditions' => 'minimum')
1086
+			)
1087
+		);
1088
+	}
1089
+
1090
+
1091
+
1092
+	/**
1093
+	 * Alters query parameters to only get items with this ID are returned.
1094
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1095
+	 * or could just be a simple primary key ID
1096
+	 *
1097
+	 * @param int   $id
1098
+	 * @param array $query_params
1099
+	 * @return array of normal query params, @see EEM_Base::get_all
1100
+	 * @throws \EE_Error
1101
+	 */
1102
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1103
+	{
1104
+		if ( ! isset($query_params[0])) {
1105
+			$query_params[0] = array();
1106
+		}
1107
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1108
+		if ($conditions_from_id === null) {
1109
+			$query_params[0][$this->primary_key_name()] = $id;
1110
+		} else {
1111
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1112
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1113
+		}
1114
+		return $query_params;
1115
+	}
1116
+
1117
+
1118
+
1119
+	/**
1120
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1121
+	 * array. If no item is found, null is returned.
1122
+	 *
1123
+	 * @param array $query_params like EEM_Base's $query_params variable.
1124
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1125
+	 * @throws \EE_Error
1126
+	 */
1127
+	public function get_one($query_params = array())
1128
+	{
1129
+		if ( ! is_array($query_params)) {
1130
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1131
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1132
+					gettype($query_params)), '4.6.0');
1133
+			$query_params = array();
1134
+		}
1135
+		$query_params['limit'] = 1;
1136
+		$items = $this->get_all($query_params);
1137
+		if (empty($items)) {
1138
+			return null;
1139
+		} else {
1140
+			return array_shift($items);
1141
+		}
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * Returns the next x number of items in sequence from the given value as
1148
+	 * found in the database matching the given query conditions.
1149
+	 *
1150
+	 * @param mixed $current_field_value    Value used for the reference point.
1151
+	 * @param null  $field_to_order_by      What field is used for the
1152
+	 *                                      reference point.
1153
+	 * @param int   $limit                  How many to return.
1154
+	 * @param array $query_params           Extra conditions on the query.
1155
+	 * @param null  $columns_to_select      If left null, then an array of
1156
+	 *                                      EE_Base_Class objects is returned,
1157
+	 *                                      otherwise you can indicate just the
1158
+	 *                                      columns you want returned.
1159
+	 * @return EE_Base_Class[]|array
1160
+	 * @throws \EE_Error
1161
+	 */
1162
+	public function next_x(
1163
+		$current_field_value,
1164
+		$field_to_order_by = null,
1165
+		$limit = 1,
1166
+		$query_params = array(),
1167
+		$columns_to_select = null
1168
+	) {
1169
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1170
+			$columns_to_select);
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Returns the previous x number of items in sequence from the given value
1177
+	 * as found in the database matching the given query conditions.
1178
+	 *
1179
+	 * @param mixed $current_field_value    Value used for the reference point.
1180
+	 * @param null  $field_to_order_by      What field is used for the
1181
+	 *                                      reference point.
1182
+	 * @param int   $limit                  How many to return.
1183
+	 * @param array $query_params           Extra conditions on the query.
1184
+	 * @param null  $columns_to_select      If left null, then an array of
1185
+	 *                                      EE_Base_Class objects is returned,
1186
+	 *                                      otherwise you can indicate just the
1187
+	 *                                      columns you want returned.
1188
+	 * @return EE_Base_Class[]|array
1189
+	 * @throws \EE_Error
1190
+	 */
1191
+	public function previous_x(
1192
+		$current_field_value,
1193
+		$field_to_order_by = null,
1194
+		$limit = 1,
1195
+		$query_params = array(),
1196
+		$columns_to_select = null
1197
+	) {
1198
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1199
+			$columns_to_select);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Returns the next item in sequence from the given value as found in the
1206
+	 * database matching the given query conditions.
1207
+	 *
1208
+	 * @param mixed $current_field_value    Value used for the reference point.
1209
+	 * @param null  $field_to_order_by      What field is used for the
1210
+	 *                                      reference point.
1211
+	 * @param array $query_params           Extra conditions on the query.
1212
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1213
+	 *                                      object is returned, otherwise you
1214
+	 *                                      can indicate just the columns you
1215
+	 *                                      want and a single array indexed by
1216
+	 *                                      the columns will be returned.
1217
+	 * @return EE_Base_Class|null|array()
1218
+	 * @throws \EE_Error
1219
+	 */
1220
+	public function next(
1221
+		$current_field_value,
1222
+		$field_to_order_by = null,
1223
+		$query_params = array(),
1224
+		$columns_to_select = null
1225
+	) {
1226
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1227
+			$columns_to_select);
1228
+		return empty($results) ? null : reset($results);
1229
+	}
1230
+
1231
+
1232
+
1233
+	/**
1234
+	 * Returns the previous item in sequence from the given value as found in
1235
+	 * the database matching the given query conditions.
1236
+	 *
1237
+	 * @param mixed $current_field_value    Value used for the reference point.
1238
+	 * @param null  $field_to_order_by      What field is used for the
1239
+	 *                                      reference point.
1240
+	 * @param array $query_params           Extra conditions on the query.
1241
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1242
+	 *                                      object is returned, otherwise you
1243
+	 *                                      can indicate just the columns you
1244
+	 *                                      want and a single array indexed by
1245
+	 *                                      the columns will be returned.
1246
+	 * @return EE_Base_Class|null|array()
1247
+	 * @throws EE_Error
1248
+	 */
1249
+	public function previous(
1250
+		$current_field_value,
1251
+		$field_to_order_by = null,
1252
+		$query_params = array(),
1253
+		$columns_to_select = null
1254
+	) {
1255
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1256
+			$columns_to_select);
1257
+		return empty($results) ? null : reset($results);
1258
+	}
1259
+
1260
+
1261
+
1262
+	/**
1263
+	 * Returns the a consecutive number of items in sequence from the given
1264
+	 * value as found in the database matching the given query conditions.
1265
+	 *
1266
+	 * @param mixed  $current_field_value   Value used for the reference point.
1267
+	 * @param string $operand               What operand is used for the sequence.
1268
+	 * @param string $field_to_order_by     What field is used for the reference point.
1269
+	 * @param int    $limit                 How many to return.
1270
+	 * @param array  $query_params          Extra conditions on the query.
1271
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1272
+	 *                                      otherwise you can indicate just the columns you want returned.
1273
+	 * @return EE_Base_Class[]|array
1274
+	 * @throws EE_Error
1275
+	 */
1276
+	protected function _get_consecutive(
1277
+		$current_field_value,
1278
+		$operand = '>',
1279
+		$field_to_order_by = null,
1280
+		$limit = 1,
1281
+		$query_params = array(),
1282
+		$columns_to_select = null
1283
+	) {
1284
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1285
+		if (empty($field_to_order_by)) {
1286
+			if ($this->has_primary_key_field()) {
1287
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1288
+			} else {
1289
+				if (WP_DEBUG) {
1290
+					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).',
1291
+						'event_espresso'));
1292
+				}
1293
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1294
+				return array();
1295
+			}
1296
+		}
1297
+		if ( ! is_array($query_params)) {
1298
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1299
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1300
+					gettype($query_params)), '4.6.0');
1301
+			$query_params = array();
1302
+		}
1303
+		//let's add the where query param for consecutive look up.
1304
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1305
+		$query_params['limit'] = $limit;
1306
+		//set direction
1307
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1308
+		$query_params['order_by'] = $operand === '>'
1309
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1310
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1311
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1312
+		if (empty($columns_to_select)) {
1313
+			return $this->get_all($query_params);
1314
+		} else {
1315
+			//getting just the fields
1316
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1317
+		}
1318
+	}
1319
+
1320
+
1321
+
1322
+	/**
1323
+	 * This sets the _timezone property after model object has been instantiated.
1324
+	 *
1325
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1326
+	 */
1327
+	public function set_timezone($timezone)
1328
+	{
1329
+		if ($timezone !== null) {
1330
+			$this->_timezone = $timezone;
1331
+		}
1332
+		//note we need to loop through relations and set the timezone on those objects as well.
1333
+		foreach ($this->_model_relations as $relation) {
1334
+			$relation->set_timezone($timezone);
1335
+		}
1336
+		//and finally we do the same for any datetime fields
1337
+		foreach ($this->_fields as $field) {
1338
+			if ($field instanceof EE_Datetime_Field) {
1339
+				$field->set_timezone($timezone);
1340
+			}
1341
+		}
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * This just returns whatever is set for the current timezone.
1348
+	 *
1349
+	 * @access public
1350
+	 * @return string
1351
+	 */
1352
+	public function get_timezone()
1353
+	{
1354
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1355
+		if (empty($this->_timezone)) {
1356
+			foreach ($this->_fields as $field) {
1357
+				if ($field instanceof EE_Datetime_Field) {
1358
+					$this->set_timezone($field->get_timezone());
1359
+					break;
1360
+				}
1361
+			}
1362
+		}
1363
+		//if timezone STILL empty then return the default timezone for the site.
1364
+		if (empty($this->_timezone)) {
1365
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1366
+		}
1367
+		return $this->_timezone;
1368
+	}
1369
+
1370
+
1371
+
1372
+	/**
1373
+	 * This returns the date formats set for the given field name and also ensures that
1374
+	 * $this->_timezone property is set correctly.
1375
+	 *
1376
+	 * @since 4.6.x
1377
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1378
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1379
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1380
+	 * @return array formats in an array with the date format first, and the time format last.
1381
+	 */
1382
+	public function get_formats_for($field_name, $pretty = false)
1383
+	{
1384
+		$field_settings = $this->field_settings_for($field_name);
1385
+		//if not a valid EE_Datetime_Field then throw error
1386
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1387
+			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.',
1388
+				'event_espresso'), $field_name));
1389
+		}
1390
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1391
+		//the field.
1392
+		$this->_timezone = $field_settings->get_timezone();
1393
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1394
+	}
1395
+
1396
+
1397
+
1398
+	/**
1399
+	 * This returns the current time in a format setup for a query on this model.
1400
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1401
+	 * it will return:
1402
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1403
+	 *  NOW
1404
+	 *  - or a unix timestamp (equivalent to time())
1405
+	 *
1406
+	 * @since 4.6.x
1407
+	 * @param string $field_name       The field the current time is needed for.
1408
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1409
+	 *                                 formatted string matching the set format for the field in the set timezone will
1410
+	 *                                 be returned.
1411
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1412
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1413
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1414
+	 *                                 exception is triggered.
1415
+	 */
1416
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1417
+	{
1418
+		$formats = $this->get_formats_for($field_name);
1419
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1420
+		if ($timestamp) {
1421
+			return $DateTime->format('U');
1422
+		}
1423
+		//not returning timestamp, so return formatted string in timezone.
1424
+		switch ($what) {
1425
+			case 'time' :
1426
+				return $DateTime->format($formats[1]);
1427
+				break;
1428
+			case 'date' :
1429
+				return $DateTime->format($formats[0]);
1430
+				break;
1431
+			default :
1432
+				return $DateTime->format(implode(' ', $formats));
1433
+				break;
1434
+		}
1435
+	}
1436
+
1437
+
1438
+
1439
+	/**
1440
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1441
+	 * for the model are.  Returns a DateTime object.
1442
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1443
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1444
+	 * ignored.
1445
+	 *
1446
+	 * @param string $field_name      The field being setup.
1447
+	 * @param string $timestring      The date time string being used.
1448
+	 * @param string $incoming_format The format for the time string.
1449
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1450
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1451
+	 *                                format is
1452
+	 *                                'U', this is ignored.
1453
+	 * @return DateTime
1454
+	 * @throws \EE_Error
1455
+	 */
1456
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1457
+	{
1458
+		//just using this to ensure the timezone is set correctly internally
1459
+		$this->get_formats_for($field_name);
1460
+		//load EEH_DTT_Helper
1461
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1462
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1463
+		return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1464
+	}
1465
+
1466
+
1467
+
1468
+	/**
1469
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1470
+	 *
1471
+	 * @return EE_Table_Base[]
1472
+	 */
1473
+	public function get_tables()
1474
+	{
1475
+		return $this->_tables;
1476
+	}
1477
+
1478
+
1479
+
1480
+	/**
1481
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1482
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1483
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1484
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1485
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1486
+	 * model object with EVT_ID = 1
1487
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1488
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1489
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1490
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1491
+	 * are not specified)
1492
+	 *
1493
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1494
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1495
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1496
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1497
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1498
+	 *                                         ID=34, we'd use this method as follows:
1499
+	 *                                         EEM_Transaction::instance()->update(
1500
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1501
+	 *                                         array(array('TXN_ID'=>34)));
1502
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1503
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1504
+	 *                                         consider updating Question's QST_admin_label field is of type
1505
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1506
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1507
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1508
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1509
+	 *                                         TRUE, it is assumed that you've already called
1510
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1511
+	 *                                         malicious javascript. However, if
1512
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1513
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set
1514
+	 *                                         function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1515
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1516
+	 *                                         in this model's entity map according to $fields_n_values that match
1517
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1518
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1519
+	 *                                         could get out-of-sync with the database
1520
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1521
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was bad)
1522
+	 * @throws \EE_Error
1523
+	 */
1524
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1525
+	{
1526
+		if ( ! is_array($query_params)) {
1527
+			EE_Error::doing_it_wrong('EEM_Base::update',
1528
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1529
+					gettype($query_params)), '4.6.0');
1530
+			$query_params = array();
1531
+		}
1532
+		/**
1533
+		 * Action called before a model update call has been made.
1534
+		 *
1535
+		 * @param EEM_Base $model
1536
+		 * @param array    $fields_n_values the updated fields and their new values
1537
+		 * @param array    $query_params    @see EEM_Base::get_all()
1538
+		 */
1539
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1540
+		/**
1541
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1542
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1543
+		 *
1544
+		 * @param array    $fields_n_values fields and their new values
1545
+		 * @param EEM_Base $model           the model being queried
1546
+		 * @param array    $query_params    see EEM_Base::get_all()
1547
+		 */
1548
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1549
+			$query_params);
1550
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1551
+		//to do that, for each table, verify that it's PK isn't null.
1552
+		$tables = $this->get_tables();
1553
+		//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
1554
+		//NOTE: we should make this code more efficient by NOT querying twice
1555
+		//before the real update, but that needs to first go through ALPHA testing
1556
+		//as it's dangerous. says Mike August 8 2014
1557
+		//we want to make sure the default_where strategy is ignored
1558
+		$this->_ignore_where_strategy = true;
1559
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1560
+		foreach ($wpdb_select_results as $wpdb_result) {
1561
+			// type cast stdClass as array
1562
+			$wpdb_result = (array)$wpdb_result;
1563
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1564
+			if ($this->has_primary_key_field()) {
1565
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1566
+			} else {
1567
+				//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)
1568
+				$main_table_pk_value = null;
1569
+			}
1570
+			//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
1571
+			//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
1572
+			if (count($tables) > 1) {
1573
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1574
+				//in that table, and so we'll want to insert one
1575
+				foreach ($tables as $table_obj) {
1576
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1577
+					//if there is no private key for this table on the results, it means there's no entry
1578
+					//in this table, right? so insert a row in the current table, using any fields available
1579
+					if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1580
+							&& $wpdb_result[$this_table_pk_column])
1581
+					) {
1582
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1583
+							$main_table_pk_value);
1584
+						//if we died here, report the error
1585
+						if ( ! $success) {
1586
+							return false;
1587
+						}
1588
+					}
1589
+				}
1590
+			}
1591
+			//				//and now check that if we have cached any models by that ID on the model, that
1592
+			//				//they also get updated properly
1593
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1594
+			//				if( $model_object ){
1595
+			//					foreach( $fields_n_values as $field => $value ){
1596
+			//						$model_object->set($field, $value);
1597
+			//let's make sure default_where strategy is followed now
1598
+			$this->_ignore_where_strategy = false;
1599
+		}
1600
+		//if we want to keep model objects in sync, AND
1601
+		//if this wasn't called from a model object (to update itself)
1602
+		//then we want to make sure we keep all the existing
1603
+		//model objects in sync with the db
1604
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1605
+			if ($this->has_primary_key_field()) {
1606
+				$model_objs_affected_ids = $this->get_col($query_params);
1607
+			} else {
1608
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1609
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1610
+				$model_objs_affected_ids = array();
1611
+				foreach ($models_affected_key_columns as $row) {
1612
+					$combined_index_key = $this->get_index_primary_key_string($row);
1613
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1614
+				}
1615
+			}
1616
+			if ( ! $model_objs_affected_ids) {
1617
+				//wait wait wait- if nothing was affected let's stop here
1618
+				return 0;
1619
+			}
1620
+			foreach ($model_objs_affected_ids as $id) {
1621
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1622
+				if ($model_obj_in_entity_map) {
1623
+					foreach ($fields_n_values as $field => $new_value) {
1624
+						$model_obj_in_entity_map->set($field, $new_value);
1625
+					}
1626
+				}
1627
+			}
1628
+			//if there is a primary key on this model, we can now do a slight optimization
1629
+			if ($this->has_primary_key_field()) {
1630
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1631
+				$query_params = array(
1632
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1633
+					'limit'                    => count($model_objs_affected_ids),
1634
+					'default_where_conditions' => 'none',
1635
+				);
1636
+			}
1637
+		}
1638
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1639
+		$SQL = "UPDATE "
1640
+			   . $model_query_info->get_full_join_sql()
1641
+			   . " SET "
1642
+			   . $this->_construct_update_sql($fields_n_values)
1643
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1644
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1645
+		/**
1646
+		 * Action called after a model update call has been made.
1647
+		 *
1648
+		 * @param EEM_Base $model
1649
+		 * @param array    $fields_n_values the updated fields and their new values
1650
+		 * @param array    $query_params    @see EEM_Base::get_all()
1651
+		 * @param int      $rows_affected
1652
+		 */
1653
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1654
+		return $rows_affected;//how many supposedly got updated
1655
+	}
1656
+
1657
+
1658
+
1659
+	/**
1660
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1661
+	 * are teh values of the field specified (or by default the primary key field)
1662
+	 * that matched the query params. Note that you should pass the name of the
1663
+	 * model FIELD, not the database table's column name.
1664
+	 *
1665
+	 * @param array  $query_params @see EEM_Base::get_all()
1666
+	 * @param string $field_to_select
1667
+	 * @return array just like $wpdb->get_col()
1668
+	 * @throws \EE_Error
1669
+	 */
1670
+	public function get_col($query_params = array(), $field_to_select = null)
1671
+	{
1672
+		if ($field_to_select) {
1673
+			$field = $this->field_settings_for($field_to_select);
1674
+		} elseif ($this->has_primary_key_field()) {
1675
+			$field = $this->get_primary_key_field();
1676
+		} else {
1677
+			//no primary key, just grab the first column
1678
+			$field = reset($this->field_settings());
1679
+		}
1680
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1681
+		$select_expressions = $field->get_qualified_column();
1682
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1683
+		return $this->_do_wpdb_query('get_col', array($SQL));
1684
+	}
1685
+
1686
+
1687
+
1688
+	/**
1689
+	 * Returns a single column value for a single row from the database
1690
+	 *
1691
+	 * @param array  $query_params    @see EEM_Base::get_all()
1692
+	 * @param string $field_to_select @see EEM_Base::get_col()
1693
+	 * @return string
1694
+	 * @throws \EE_Error
1695
+	 */
1696
+	public function get_var($query_params = array(), $field_to_select = null)
1697
+	{
1698
+		$query_params['limit'] = 1;
1699
+		$col = $this->get_col($query_params, $field_to_select);
1700
+		if ( ! empty($col)) {
1701
+			return reset($col);
1702
+		} else {
1703
+			return null;
1704
+		}
1705
+	}
1706
+
1707
+
1708
+
1709
+	/**
1710
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1711
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1712
+	 * injection, but currently no further filtering is done
1713
+	 *
1714
+	 * @global      $wpdb
1715
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1716
+	 *                               be updated to in the DB
1717
+	 * @return string of SQL
1718
+	 * @throws \EE_Error
1719
+	 */
1720
+	public function _construct_update_sql($fields_n_values)
1721
+	{
1722
+		/** @type WPDB $wpdb */
1723
+		global $wpdb;
1724
+		$cols_n_values = array();
1725
+		foreach ($fields_n_values as $field_name => $value) {
1726
+			$field_obj = $this->field_settings_for($field_name);
1727
+			//if the value is NULL, we want to assign the value to that.
1728
+			//wpdb->prepare doesn't really handle that properly
1729
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1730
+			$value_sql = $prepared_value === null ? 'NULL'
1731
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1732
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1733
+		}
1734
+		return implode(",", $cols_n_values);
1735
+	}
1736
+
1737
+
1738
+
1739
+	/**
1740
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1741
+	 * Performs a HARD delete, meaning the database row should always be removed,
1742
+	 * not just have a flag field on it switched
1743
+	 * Wrapper for EEM_Base::delete_permanently()
1744
+	 *
1745
+	 * @param mixed $id
1746
+	 * @return boolean whether the row got deleted or not
1747
+	 * @throws \EE_Error
1748
+	 */
1749
+	public function delete_permanently_by_ID($id)
1750
+	{
1751
+		return $this->delete_permanently(
1752
+			array(
1753
+				array($this->get_primary_key_field()->get_name() => $id),
1754
+				'limit' => 1,
1755
+			)
1756
+		);
1757
+	}
1758
+
1759
+
1760
+
1761
+	/**
1762
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1763
+	 * Wrapper for EEM_Base::delete()
1764
+	 *
1765
+	 * @param mixed $id
1766
+	 * @return boolean whether the row got deleted or not
1767
+	 * @throws \EE_Error
1768
+	 */
1769
+	public function delete_by_ID($id)
1770
+	{
1771
+		return $this->delete(
1772
+			array(
1773
+				array($this->get_primary_key_field()->get_name() => $id),
1774
+				'limit' => 1,
1775
+			)
1776
+		);
1777
+	}
1778
+
1779
+
1780
+
1781
+	/**
1782
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1783
+	 * meaning if the model has a field that indicates its been "trashed" or
1784
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1785
+	 *
1786
+	 * @see EEM_Base::delete_permanently
1787
+	 * @param array   $query_params
1788
+	 * @param boolean $allow_blocking
1789
+	 * @return int how many rows got deleted
1790
+	 * @throws \EE_Error
1791
+	 */
1792
+	public function delete($query_params, $allow_blocking = true)
1793
+	{
1794
+		return $this->delete_permanently($query_params, $allow_blocking);
1795
+	}
1796
+
1797
+
1798
+
1799
+	/**
1800
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1801
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1802
+	 * as archived, not actually deleted
1803
+	 *
1804
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1805
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1806
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1807
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1808
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1809
+	 *                                DB
1810
+	 * @return int how many rows got deleted
1811
+	 * @throws \EE_Error
1812
+	 */
1813
+	public function delete_permanently($query_params, $allow_blocking = true)
1814
+	{
1815
+		/**
1816
+		 * Action called just before performing a real deletion query. You can use the
1817
+		 * model and its $query_params to find exactly which items will be deleted
1818
+		 *
1819
+		 * @param EEM_Base $model
1820
+		 * @param array    $query_params   @see EEM_Base::get_all()
1821
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1822
+		 *                                 to block (prevent) this deletion
1823
+		 */
1824
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1825
+		//some MySQL databases may be running safe mode, which may restrict
1826
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1827
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1828
+		//to delete them
1829
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1830
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1831
+		if ($deletion_where) {
1832
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1833
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1834
+			$table_aliases = array_keys($this->_tables);
1835
+			$SQL = "DELETE "
1836
+				   . implode(", ", $table_aliases)
1837
+				   . " FROM "
1838
+				   . $model_query_info->get_full_join_sql()
1839
+				   . " WHERE "
1840
+				   . $deletion_where;
1841
+			//		/echo "delete sql:$SQL";
1842
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1843
+		} else {
1844
+			$rows_deleted = 0;
1845
+		}
1846
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1847
+		if ($this->has_primary_key_field()) {
1848
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1849
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1850
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1851
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1852
+				}
1853
+			}
1854
+		}
1855
+		/**
1856
+		 * Action called just after performing a real deletion query. Although at this point the
1857
+		 * items should have been deleted
1858
+		 *
1859
+		 * @param EEM_Base $model
1860
+		 * @param array    $query_params @see EEM_Base::get_all()
1861
+		 * @param int      $rows_deleted
1862
+		 */
1863
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1864
+		return $rows_deleted;//how many supposedly got deleted
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Checks all the relations that throw error messages when there are blocking related objects
1871
+	 * for related model objects. If there are any related model objects on those relations,
1872
+	 * adds an EE_Error, and return true
1873
+	 *
1874
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1875
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1876
+	 *                                                 should be ignored when determining whether there are related
1877
+	 *                                                 model objects which block this model object's deletion. Useful
1878
+	 *                                                 if you know A is related to B and are considering deleting A,
1879
+	 *                                                 but want to see if A has any other objects blocking its deletion
1880
+	 *                                                 before removing the relation between A and B
1881
+	 * @return boolean
1882
+	 * @throws \EE_Error
1883
+	 */
1884
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1885
+	{
1886
+		//first, if $ignore_this_model_obj was supplied, get its model
1887
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1888
+			$ignored_model = $ignore_this_model_obj->get_model();
1889
+		} else {
1890
+			$ignored_model = null;
1891
+		}
1892
+		//now check all the relations of $this_model_obj_or_id and see if there
1893
+		//are any related model objects blocking it?
1894
+		$is_blocked = false;
1895
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1896
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1897
+				//if $ignore_this_model_obj was supplied, then for the query
1898
+				//on that model needs to be told to ignore $ignore_this_model_obj
1899
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1900
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1901
+						array(
1902
+							$ignored_model->get_primary_key_field()->get_name() => array(
1903
+								'!=',
1904
+								$ignore_this_model_obj->ID(),
1905
+							),
1906
+						),
1907
+					));
1908
+				} else {
1909
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1910
+				}
1911
+				if ($related_model_objects) {
1912
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1913
+					$is_blocked = true;
1914
+				}
1915
+			}
1916
+		}
1917
+		return $is_blocked;
1918
+	}
1919
+
1920
+
1921
+
1922
+	/**
1923
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1924
+	 * well.
1925
+	 *
1926
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1927
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1928
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
1929
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
1930
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
1931
+	 *                                      easily corrupt your DB
1932
+	 * @throws EE_Error
1933
+	 * @return string    everything that comes after the WHERE statement.
1934
+	 */
1935
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1936
+	{
1937
+		if ($this->has_primary_key_field()) {
1938
+			$primary_table = $this->_get_main_table();
1939
+			$other_tables = $this->_get_other_tables();
1940
+			$deletes = $query = array();
1941
+			foreach ($objects_for_deletion as $delete_object) {
1942
+				//before we mark this object for deletion,
1943
+				//make sure there's no related objects blocking its deletion (if we're checking)
1944
+				if (
1945
+					$allow_blocking
1946
+					&& $this->delete_is_blocked_by_related_models(
1947
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
1948
+					)
1949
+				) {
1950
+					continue;
1951
+				}
1952
+				//primary table deletes
1953
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1954
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1955
+				}
1956
+				//other tables
1957
+				if ( ! empty($other_tables)) {
1958
+					foreach ($other_tables as $ot) {
1959
+						//first check if we've got the foreign key column here.
1960
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
1961
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1962
+						}
1963
+						// wait! it's entirely possible that we'll have a the primary key
1964
+						// for this table in here, if it's a foreign key for one of the other secondary tables
1965
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
1966
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1967
+						}
1968
+						// finally, it is possible that the fk for this table is found
1969
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
1970
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
1971
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1972
+						}
1973
+					}
1974
+				}
1975
+			}
1976
+			//we should have deletes now, so let's just go through and setup the where statement
1977
+			foreach ($deletes as $column => $values) {
1978
+				//make sure we have unique $values;
1979
+				$values = array_unique($values);
1980
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
1981
+			}
1982
+			return ! empty($query) ? implode(' AND ', $query) : '';
1983
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
1984
+			$ways_to_identify_a_row = array();
1985
+			$fields = $this->get_combined_primary_key_fields();
1986
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1987
+			foreach ($objects_for_deletion as $delete_object) {
1988
+				$values_for_each_cpk_for_a_row = array();
1989
+				foreach ($fields as $cpk_field) {
1990
+					if ($cpk_field instanceof EE_Model_Field_Base) {
1991
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1992
+														   . "="
1993
+														   . $delete_object[$cpk_field->get_qualified_column()];
1994
+					}
1995
+				}
1996
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1997
+			}
1998
+			return implode(" OR ", $ways_to_identify_a_row);
1999
+		} else {
2000
+			//so there's no primary key and no combined key...
2001
+			//sorry, can't help you
2002
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2003
+				"event_espresso"), get_class($this)));
2004
+		}
2005
+	}
2006
+
2007
+
2008
+
2009
+	/**
2010
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2011
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2012
+	 * column
2013
+	 *
2014
+	 * @param array  $query_params   like EEM_Base::get_all's
2015
+	 * @param string $field_to_count field on model to count by (not column name)
2016
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2017
+	 *                               that by the setting $distinct to TRUE;
2018
+	 * @return int
2019
+	 * @throws \EE_Error
2020
+	 */
2021
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2022
+	{
2023
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2024
+		if ($field_to_count) {
2025
+			$field_obj = $this->field_settings_for($field_to_count);
2026
+			$column_to_count = $field_obj->get_qualified_column();
2027
+		} elseif ($this->has_primary_key_field()) {
2028
+			$pk_field_obj = $this->get_primary_key_field();
2029
+			$column_to_count = $pk_field_obj->get_qualified_column();
2030
+		} else {
2031
+			//there's no primary key
2032
+			//if we're counting distinct items, and there's no primary key,
2033
+			//we need to list out the columns for distinction;
2034
+			//otherwise we can just use star
2035
+			if ($distinct) {
2036
+				$columns_to_use = array();
2037
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2038
+					$columns_to_use[] = $field_obj->get_qualified_column();
2039
+				}
2040
+				$column_to_count = implode(',', $columns_to_use);
2041
+			} else {
2042
+				$column_to_count = '*';
2043
+			}
2044
+		}
2045
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2046
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2047
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2048
+	}
2049
+
2050
+
2051
+
2052
+	/**
2053
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2054
+	 *
2055
+	 * @param array  $query_params like EEM_Base::get_all
2056
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2057
+	 * @return float
2058
+	 * @throws \EE_Error
2059
+	 */
2060
+	public function sum($query_params, $field_to_sum = null)
2061
+	{
2062
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2063
+		if ($field_to_sum) {
2064
+			$field_obj = $this->field_settings_for($field_to_sum);
2065
+		} else {
2066
+			$field_obj = $this->get_primary_key_field();
2067
+		}
2068
+		$column_to_count = $field_obj->get_qualified_column();
2069
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2070
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2071
+		$data_type = $field_obj->get_wpdb_data_type();
2072
+		if ($data_type === '%d' || $data_type === '%s') {
2073
+			return (float)$return_value;
2074
+		} else {//must be %f
2075
+			return (float)$return_value;
2076
+		}
2077
+	}
2078
+
2079
+
2080
+
2081
+	/**
2082
+	 * Just calls the specified method on $wpdb with the given arguments
2083
+	 * Consolidates a little extra error handling code
2084
+	 *
2085
+	 * @param string $wpdb_method
2086
+	 * @param array  $arguments_to_provide
2087
+	 * @throws EE_Error
2088
+	 * @global wpdb  $wpdb
2089
+	 * @return mixed
2090
+	 */
2091
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2092
+	{
2093
+		//if we're in maintenance mode level 2, DON'T run any queries
2094
+		//because level 2 indicates the database needs updating and
2095
+		//is probably out of sync with the code
2096
+		if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2097
+			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.",
2098
+				"event_espresso")));
2099
+		}
2100
+		/** @type WPDB $wpdb */
2101
+		global $wpdb;
2102
+		if ( ! method_exists($wpdb, $wpdb_method)) {
2103
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2104
+				'event_espresso'), $wpdb_method));
2105
+		}
2106
+		if (WP_DEBUG) {
2107
+			$old_show_errors_value = $wpdb->show_errors;
2108
+			$wpdb->show_errors(false);
2109
+		}
2110
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2111
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2112
+		if (WP_DEBUG) {
2113
+			$wpdb->show_errors($old_show_errors_value);
2114
+			if ( ! empty($wpdb->last_error)) {
2115
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2116
+			} elseif ($result === false) {
2117
+				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"',
2118
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2119
+			}
2120
+		} elseif ($result === false) {
2121
+			EE_Error::add_error(
2122
+				sprintf(
2123
+					__('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"',
2124
+						'event_espresso'),
2125
+					$wpdb_method,
2126
+					var_export($arguments_to_provide, true),
2127
+					$wpdb->last_error
2128
+				),
2129
+				__FILE__,
2130
+				__FUNCTION__,
2131
+				__LINE__
2132
+			);
2133
+		}
2134
+		return $result;
2135
+	}
2136
+
2137
+
2138
+
2139
+	/**
2140
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2141
+	 * and if there's an error tries to verify the DB is correct. Uses
2142
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2143
+	 * we should try to fix the EE core db, the addons, or just give up
2144
+	 *
2145
+	 * @param string $wpdb_method
2146
+	 * @param array  $arguments_to_provide
2147
+	 * @return mixed
2148
+	 */
2149
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2150
+	{
2151
+		/** @type WPDB $wpdb */
2152
+		global $wpdb;
2153
+		$wpdb->last_error = null;
2154
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2155
+		// was there an error running the query? but we don't care on new activations
2156
+		// (we're going to setup the DB anyway on new activations)
2157
+		if (($result === false || ! empty($wpdb->last_error))
2158
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2159
+		) {
2160
+			switch (EEM_Base::$_db_verification_level) {
2161
+				case EEM_Base::db_verified_none :
2162
+					// let's double-check core's DB
2163
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2164
+					break;
2165
+				case EEM_Base::db_verified_core :
2166
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2167
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2168
+					break;
2169
+				case EEM_Base::db_verified_addons :
2170
+					// ummmm... you in trouble
2171
+					return $result;
2172
+					break;
2173
+			}
2174
+			if ( ! empty($error_message)) {
2175
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2176
+				trigger_error($error_message);
2177
+			}
2178
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2179
+		}
2180
+		return $result;
2181
+	}
2182
+
2183
+
2184
+
2185
+	/**
2186
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2187
+	 * EEM_Base::$_db_verification_level
2188
+	 *
2189
+	 * @param string $wpdb_method
2190
+	 * @param array  $arguments_to_provide
2191
+	 * @return string
2192
+	 */
2193
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2194
+	{
2195
+		/** @type WPDB $wpdb */
2196
+		global $wpdb;
2197
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2198
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2199
+		$error_message = sprintf(
2200
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2201
+				'event_espresso'),
2202
+			$wpdb->last_error,
2203
+			$wpdb_method,
2204
+			json_encode($arguments_to_provide)
2205
+		);
2206
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2207
+		return $error_message;
2208
+	}
2209
+
2210
+
2211
+
2212
+	/**
2213
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2214
+	 * EEM_Base::$_db_verification_level
2215
+	 *
2216
+	 * @param $wpdb_method
2217
+	 * @param $arguments_to_provide
2218
+	 * @return string
2219
+	 */
2220
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2221
+	{
2222
+		/** @type WPDB $wpdb */
2223
+		global $wpdb;
2224
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2225
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2226
+		$error_message = sprintf(
2227
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2228
+				'event_espresso'),
2229
+			$wpdb->last_error,
2230
+			$wpdb_method,
2231
+			json_encode($arguments_to_provide)
2232
+		);
2233
+		EE_System::instance()->initialize_addons();
2234
+		return $error_message;
2235
+	}
2236
+
2237
+
2238
+
2239
+	/**
2240
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2241
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2242
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2243
+	 * ..."
2244
+	 *
2245
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2246
+	 * @return string
2247
+	 */
2248
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2249
+	{
2250
+		return " FROM " . $model_query_info->get_full_join_sql() .
2251
+			   $model_query_info->get_where_sql() .
2252
+			   $model_query_info->get_group_by_sql() .
2253
+			   $model_query_info->get_having_sql() .
2254
+			   $model_query_info->get_order_by_sql() .
2255
+			   $model_query_info->get_limit_sql();
2256
+	}
2257
+
2258
+
2259
+
2260
+	/**
2261
+	 * Set to easily debug the next X queries ran from this model.
2262
+	 *
2263
+	 * @param int $count
2264
+	 */
2265
+	public function show_next_x_db_queries($count = 1)
2266
+	{
2267
+		$this->_show_next_x_db_queries = $count;
2268
+	}
2269
+
2270
+
2271
+
2272
+	/**
2273
+	 * @param $sql_query
2274
+	 */
2275
+	public function show_db_query_if_previously_requested($sql_query)
2276
+	{
2277
+		if ($this->_show_next_x_db_queries > 0) {
2278
+			echo $sql_query;
2279
+			$this->_show_next_x_db_queries--;
2280
+		}
2281
+	}
2282
+
2283
+
2284
+
2285
+	/**
2286
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2287
+	 * There are the 3 cases:
2288
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2289
+	 * $otherModelObject has no ID, it is first saved.
2290
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2291
+	 * has no ID, it is first saved.
2292
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2293
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2294
+	 * join table
2295
+	 *
2296
+	 * @param        EE_Base_Class                     /int $thisModelObject
2297
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2298
+	 * @param string $relationName                     , key in EEM_Base::_relations
2299
+	 *                                                 an attendee to a group, you also want to specify which role they
2300
+	 *                                                 will have in that group. So you would use this parameter to
2301
+	 *                                                 specify array('role-column-name'=>'role-id')
2302
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2303
+	 *                                                 to for relation to methods that allow you to further specify
2304
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2305
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2306
+	 *                                                 because these will be inserted in any new rows created as well.
2307
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2308
+	 * @throws \EE_Error
2309
+	 */
2310
+	public function add_relationship_to(
2311
+		$id_or_obj,
2312
+		$other_model_id_or_obj,
2313
+		$relationName,
2314
+		$extra_join_model_fields_n_values = array()
2315
+	) {
2316
+		$relation_obj = $this->related_settings_for($relationName);
2317
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2318
+	}
2319
+
2320
+
2321
+
2322
+	/**
2323
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2324
+	 * There are the 3 cases:
2325
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2326
+	 * error
2327
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2328
+	 * an error
2329
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2330
+	 *
2331
+	 * @param        EE_Base_Class /int $id_or_obj
2332
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2333
+	 * @param string $relationName key in EEM_Base::_relations
2334
+	 * @return boolean of success
2335
+	 * @throws \EE_Error
2336
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2337
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2338
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2339
+	 *                             because these will be inserted in any new rows created as well.
2340
+	 */
2341
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2342
+	{
2343
+		$relation_obj = $this->related_settings_for($relationName);
2344
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2345
+	}
2346
+
2347
+
2348
+
2349
+	/**
2350
+	 * @param mixed           $id_or_obj
2351
+	 * @param string          $relationName
2352
+	 * @param array           $where_query_params
2353
+	 * @param EE_Base_Class[] objects to which relations were removed
2354
+	 * @return \EE_Base_Class[]
2355
+	 * @throws \EE_Error
2356
+	 */
2357
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2358
+	{
2359
+		$relation_obj = $this->related_settings_for($relationName);
2360
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2361
+	}
2362
+
2363
+
2364
+
2365
+	/**
2366
+	 * Gets all the related items of the specified $model_name, using $query_params.
2367
+	 * Note: by default, we remove the "default query params"
2368
+	 * because we want to get even deleted items etc.
2369
+	 *
2370
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2371
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2372
+	 * @param array  $query_params like EEM_Base::get_all
2373
+	 * @return EE_Base_Class[]
2374
+	 * @throws \EE_Error
2375
+	 */
2376
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2377
+	{
2378
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2379
+		$relation_settings = $this->related_settings_for($model_name);
2380
+		return $relation_settings->get_all_related($model_obj, $query_params);
2381
+	}
2382
+
2383
+
2384
+
2385
+	/**
2386
+	 * Deletes all the model objects across the relation indicated by $model_name
2387
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2388
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2389
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2390
+	 *
2391
+	 * @param EE_Base_Class|int|string $id_or_obj
2392
+	 * @param string                   $model_name
2393
+	 * @param array                    $query_params
2394
+	 * @return int how many deleted
2395
+	 * @throws \EE_Error
2396
+	 */
2397
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2398
+	{
2399
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2400
+		$relation_settings = $this->related_settings_for($model_name);
2401
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2402
+	}
2403
+
2404
+
2405
+
2406
+	/**
2407
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2408
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2409
+	 * the model objects can't be hard deleted because of blocking related model objects,
2410
+	 * just does a soft-delete on them instead.
2411
+	 *
2412
+	 * @param EE_Base_Class|int|string $id_or_obj
2413
+	 * @param string                   $model_name
2414
+	 * @param array                    $query_params
2415
+	 * @return int how many deleted
2416
+	 * @throws \EE_Error
2417
+	 */
2418
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2419
+	{
2420
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2421
+		$relation_settings = $this->related_settings_for($model_name);
2422
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2423
+	}
2424
+
2425
+
2426
+
2427
+	/**
2428
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2429
+	 * unless otherwise specified in the $query_params
2430
+	 *
2431
+	 * @param        int             /EE_Base_Class $id_or_obj
2432
+	 * @param string $model_name     like 'Event', or 'Registration'
2433
+	 * @param array  $query_params   like EEM_Base::get_all's
2434
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2435
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2436
+	 *                               that by the setting $distinct to TRUE;
2437
+	 * @return int
2438
+	 * @throws \EE_Error
2439
+	 */
2440
+	public function count_related(
2441
+		$id_or_obj,
2442
+		$model_name,
2443
+		$query_params = array(),
2444
+		$field_to_count = null,
2445
+		$distinct = false
2446
+	) {
2447
+		$related_model = $this->get_related_model_obj($model_name);
2448
+		//we're just going to use the query params on the related model's normal get_all query,
2449
+		//except add a condition to say to match the current mod
2450
+		if ( ! isset($query_params['default_where_conditions'])) {
2451
+			$query_params['default_where_conditions'] = 'none';
2452
+		}
2453
+		$this_model_name = $this->get_this_model_name();
2454
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2455
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2456
+		return $related_model->count($query_params, $field_to_count, $distinct);
2457
+	}
2458
+
2459
+
2460
+
2461
+	/**
2462
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2463
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2464
+	 *
2465
+	 * @param        int           /EE_Base_Class $id_or_obj
2466
+	 * @param string $model_name   like 'Event', or 'Registration'
2467
+	 * @param array  $query_params like EEM_Base::get_all's
2468
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2469
+	 * @return float
2470
+	 * @throws \EE_Error
2471
+	 */
2472
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2473
+	{
2474
+		$related_model = $this->get_related_model_obj($model_name);
2475
+		if ( ! is_array($query_params)) {
2476
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2477
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2478
+					gettype($query_params)), '4.6.0');
2479
+			$query_params = array();
2480
+		}
2481
+		//we're just going to use the query params on the related model's normal get_all query,
2482
+		//except add a condition to say to match the current mod
2483
+		if ( ! isset($query_params['default_where_conditions'])) {
2484
+			$query_params['default_where_conditions'] = 'none';
2485
+		}
2486
+		$this_model_name = $this->get_this_model_name();
2487
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2488
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2489
+		return $related_model->sum($query_params, $field_to_sum);
2490
+	}
2491
+
2492
+
2493
+
2494
+	/**
2495
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2496
+	 * $modelObject
2497
+	 *
2498
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2499
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2500
+	 * @param array               $query_params     like EEM_Base::get_all's
2501
+	 * @return EE_Base_Class
2502
+	 * @throws \EE_Error
2503
+	 */
2504
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2505
+	{
2506
+		$query_params['limit'] = 1;
2507
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2508
+		if ($results) {
2509
+			return array_shift($results);
2510
+		} else {
2511
+			return null;
2512
+		}
2513
+	}
2514
+
2515
+
2516
+
2517
+	/**
2518
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2519
+	 *
2520
+	 * @return string
2521
+	 */
2522
+	public function get_this_model_name()
2523
+	{
2524
+		return str_replace("EEM_", "", get_class($this));
2525
+	}
2526
+
2527
+
2528
+
2529
+	/**
2530
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2531
+	 *
2532
+	 * @return EE_Any_Foreign_Model_Name_Field
2533
+	 * @throws EE_Error
2534
+	 */
2535
+	public function get_field_containing_related_model_name()
2536
+	{
2537
+		foreach ($this->field_settings(true) as $field) {
2538
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2539
+				$field_with_model_name = $field;
2540
+			}
2541
+		}
2542
+		if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2543
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2544
+				$this->get_this_model_name()));
2545
+		}
2546
+		return $field_with_model_name;
2547
+	}
2548
+
2549
+
2550
+
2551
+	/**
2552
+	 * Inserts a new entry into the database, for each table.
2553
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2554
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2555
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2556
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2557
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2558
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2559
+	 *
2560
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2561
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2562
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2563
+	 *                              of EEM_Base)
2564
+	 * @return int new primary key on main table that got inserted
2565
+	 * @throws EE_Error
2566
+	 */
2567
+	public function insert($field_n_values)
2568
+	{
2569
+		/**
2570
+		 * Filters the fields and their values before inserting an item using the models
2571
+		 *
2572
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2573
+		 * @param EEM_Base $model           the model used
2574
+		 */
2575
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2576
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2577
+			$main_table = $this->_get_main_table();
2578
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2579
+			if ($new_id !== false) {
2580
+				foreach ($this->_get_other_tables() as $other_table) {
2581
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2582
+				}
2583
+			}
2584
+			/**
2585
+			 * Done just after attempting to insert a new model object
2586
+			 *
2587
+			 * @param EEM_Base   $model           used
2588
+			 * @param array      $fields_n_values fields and their values
2589
+			 * @param int|string the              ID of the newly-inserted model object
2590
+			 */
2591
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2592
+			return $new_id;
2593
+		} else {
2594
+			return false;
2595
+		}
2596
+	}
2597
+
2598
+
2599
+
2600
+	/**
2601
+	 * Checks that the result would satisfy the unique indexes on this model
2602
+	 *
2603
+	 * @param array  $field_n_values
2604
+	 * @param string $action
2605
+	 * @return boolean
2606
+	 * @throws \EE_Error
2607
+	 */
2608
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2609
+	{
2610
+		foreach ($this->unique_indexes() as $index_name => $index) {
2611
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2612
+			if ($this->exists(array($uniqueness_where_params))) {
2613
+				EE_Error::add_error(
2614
+					sprintf(
2615
+						__(
2616
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2617
+							"event_espresso"
2618
+						),
2619
+						$action,
2620
+						$this->_get_class_name(),
2621
+						$index_name,
2622
+						implode(",", $index->field_names()),
2623
+						http_build_query($uniqueness_where_params)
2624
+					),
2625
+					__FILE__,
2626
+					__FUNCTION__,
2627
+					__LINE__
2628
+				);
2629
+				return false;
2630
+			}
2631
+		}
2632
+		return true;
2633
+	}
2634
+
2635
+
2636
+
2637
+	/**
2638
+	 * Checks the database for an item that conflicts (ie, if this item were
2639
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2640
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2641
+	 * can be either an EE_Base_Class or an array of fields n values
2642
+	 *
2643
+	 * @param EE_Base_Class|array $obj_or_fields_array
2644
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2645
+	 *                                                 when looking for conflicts
2646
+	 *                                                 (ie, if false, we ignore the model object's primary key
2647
+	 *                                                 when finding "conflicts". If true, it's also considered).
2648
+	 *                                                 Only works for INT primary key,
2649
+	 *                                                 STRING primary keys cannot be ignored
2650
+	 * @throws EE_Error
2651
+	 * @return EE_Base_Class|array
2652
+	 */
2653
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2654
+	{
2655
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2656
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2657
+		} elseif (is_array($obj_or_fields_array)) {
2658
+			$fields_n_values = $obj_or_fields_array;
2659
+		} else {
2660
+			throw new EE_Error(
2661
+				sprintf(
2662
+					__(
2663
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2664
+						"event_espresso"
2665
+					),
2666
+					get_class($this),
2667
+					$obj_or_fields_array
2668
+				)
2669
+			);
2670
+		}
2671
+		$query_params = array();
2672
+		if ($this->has_primary_key_field()
2673
+			&& ($include_primary_key
2674
+				|| $this->get_primary_key_field()
2675
+				   instanceof
2676
+				   EE_Primary_Key_String_Field)
2677
+			&& isset($fields_n_values[$this->primary_key_name()])
2678
+		) {
2679
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2680
+		}
2681
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2682
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2683
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2684
+		}
2685
+		//if there is nothing to base this search on, then we shouldn't find anything
2686
+		if (empty($query_params)) {
2687
+			return array();
2688
+		} else {
2689
+			return $this->get_one($query_params);
2690
+		}
2691
+	}
2692
+
2693
+
2694
+
2695
+	/**
2696
+	 * Like count, but is optimized and returns a boolean instead of an int
2697
+	 *
2698
+	 * @param array $query_params
2699
+	 * @return boolean
2700
+	 * @throws \EE_Error
2701
+	 */
2702
+	public function exists($query_params)
2703
+	{
2704
+		$query_params['limit'] = 1;
2705
+		return $this->count($query_params) > 0;
2706
+	}
2707
+
2708
+
2709
+
2710
+	/**
2711
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2712
+	 *
2713
+	 * @param int|string $id
2714
+	 * @return boolean
2715
+	 * @throws \EE_Error
2716
+	 */
2717
+	public function exists_by_ID($id)
2718
+	{
2719
+		return $this->exists(array('default_where_conditions' => 'none', array($this->primary_key_name() => $id)));
2720
+	}
2721
+
2722
+
2723
+
2724
+	/**
2725
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2726
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2727
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2728
+	 * on the main table)
2729
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2730
+	 * cases where we want to call it directly rather than via insert().
2731
+	 *
2732
+	 * @access   protected
2733
+	 * @param EE_Table_Base $table
2734
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2735
+	 *                                       float
2736
+	 * @param int           $new_id          for now we assume only int keys
2737
+	 * @throws EE_Error
2738
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2739
+	 * @return int ID of new row inserted, or FALSE on failure
2740
+	 */
2741
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2742
+	{
2743
+		global $wpdb;
2744
+		$insertion_col_n_values = array();
2745
+		$format_for_insertion = array();
2746
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2747
+		foreach ($fields_on_table as $field_name => $field_obj) {
2748
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2749
+			if ($field_obj->is_auto_increment()) {
2750
+				continue;
2751
+			}
2752
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2753
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2754
+			if ($prepared_value !== null) {
2755
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2756
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2757
+			}
2758
+		}
2759
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2760
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2761
+			//so add the fk to the main table as a column
2762
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2763
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2764
+		}
2765
+		//insert the new entry
2766
+		$result = $this->_do_wpdb_query('insert',
2767
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2768
+		if ($result === false) {
2769
+			return false;
2770
+		}
2771
+		//ok, now what do we return for the ID of the newly-inserted thing?
2772
+		if ($this->has_primary_key_field()) {
2773
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2774
+				return $wpdb->insert_id;
2775
+			} else {
2776
+				//it's not an auto-increment primary key, so
2777
+				//it must have been supplied
2778
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2779
+			}
2780
+		} else {
2781
+			//we can't return a  primary key because there is none. instead return
2782
+			//a unique string indicating this model
2783
+			return $this->get_index_primary_key_string($fields_n_values);
2784
+		}
2785
+	}
2786
+
2787
+
2788
+
2789
+	/**
2790
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2791
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2792
+	 * and there is no default, we pass it along. WPDB will take care of it)
2793
+	 *
2794
+	 * @param EE_Model_Field_Base $field_obj
2795
+	 * @param array               $fields_n_values
2796
+	 * @return mixed string|int|float depending on what the table column will be expecting
2797
+	 * @throws \EE_Error
2798
+	 */
2799
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2800
+	{
2801
+		//if this field doesn't allow nullable, don't allow it
2802
+		if ( ! $field_obj->is_nullable()
2803
+			 && (
2804
+				 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2805
+		) {
2806
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2807
+		}
2808
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2809
+			: null;
2810
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2811
+	}
2812
+
2813
+
2814
+
2815
+	/**
2816
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2817
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2818
+	 * the field's prepare_for_set() method.
2819
+	 *
2820
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2821
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2822
+	 *                                   top of file)
2823
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2824
+	 *                                   $value is a custom selection
2825
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2826
+	 */
2827
+	private function _prepare_value_for_use_in_db($value, $field)
2828
+	{
2829
+		if ($field && $field instanceof EE_Model_Field_Base) {
2830
+			switch ($this->_values_already_prepared_by_model_object) {
2831
+				/** @noinspection PhpMissingBreakStatementInspection */
2832
+				case self::not_prepared_by_model_object:
2833
+					$value = $field->prepare_for_set($value);
2834
+				//purposefully left out "return"
2835
+				case self::prepared_by_model_object:
2836
+					$value = $field->prepare_for_use_in_db($value);
2837
+				case self::prepared_for_use_in_db:
2838
+					//leave the value alone
2839
+			}
2840
+			return $value;
2841
+		} else {
2842
+			return $value;
2843
+		}
2844
+	}
2845
+
2846
+
2847
+
2848
+	/**
2849
+	 * Returns the main table on this model
2850
+	 *
2851
+	 * @return EE_Primary_Table
2852
+	 * @throws EE_Error
2853
+	 */
2854
+	protected function _get_main_table()
2855
+	{
2856
+		foreach ($this->_tables as $table) {
2857
+			if ($table instanceof EE_Primary_Table) {
2858
+				return $table;
2859
+			}
2860
+		}
2861
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2862
+			'event_espresso'), get_class($this)));
2863
+	}
2864
+
2865
+
2866
+
2867
+	/**
2868
+	 * table
2869
+	 * returns EE_Primary_Table table name
2870
+	 *
2871
+	 * @return string
2872
+	 * @throws \EE_Error
2873
+	 */
2874
+	public function table()
2875
+	{
2876
+		return $this->_get_main_table()->get_table_name();
2877
+	}
2878
+
2879
+
2880
+
2881
+	/**
2882
+	 * table
2883
+	 * returns first EE_Secondary_Table table name
2884
+	 *
2885
+	 * @return string
2886
+	 */
2887
+	public function second_table()
2888
+	{
2889
+		// grab second table from tables array
2890
+		$second_table = end($this->_tables);
2891
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2892
+	}
2893
+
2894
+
2895
+
2896
+	/**
2897
+	 * get_table_obj_by_alias
2898
+	 * returns table name given it's alias
2899
+	 *
2900
+	 * @param string $table_alias
2901
+	 * @return EE_Primary_Table | EE_Secondary_Table
2902
+	 */
2903
+	public function get_table_obj_by_alias($table_alias = '')
2904
+	{
2905
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2906
+	}
2907
+
2908
+
2909
+
2910
+	/**
2911
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2912
+	 *
2913
+	 * @return EE_Secondary_Table[]
2914
+	 */
2915
+	protected function _get_other_tables()
2916
+	{
2917
+		$other_tables = array();
2918
+		foreach ($this->_tables as $table_alias => $table) {
2919
+			if ($table instanceof EE_Secondary_Table) {
2920
+				$other_tables[$table_alias] = $table;
2921
+			}
2922
+		}
2923
+		return $other_tables;
2924
+	}
2925
+
2926
+
2927
+
2928
+	/**
2929
+	 * Finds all the fields that correspond to the given table
2930
+	 *
2931
+	 * @param string $table_alias , array key in EEM_Base::_tables
2932
+	 * @return EE_Model_Field_Base[]
2933
+	 */
2934
+	public function _get_fields_for_table($table_alias)
2935
+	{
2936
+		return $this->_fields[$table_alias];
2937
+	}
2938
+
2939
+
2940
+
2941
+	/**
2942
+	 * Recurses through all the where parameters, and finds all the related models we'll need
2943
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2944
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2945
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2946
+	 * related Registration, Transaction, and Payment models.
2947
+	 *
2948
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2949
+	 * @return EE_Model_Query_Info_Carrier
2950
+	 * @throws \EE_Error
2951
+	 */
2952
+	public function _extract_related_models_from_query($query_params)
2953
+	{
2954
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
2955
+		if (array_key_exists(0, $query_params)) {
2956
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
2957
+		}
2958
+		if (array_key_exists('group_by', $query_params)) {
2959
+			if (is_array($query_params['group_by'])) {
2960
+				$this->_extract_related_models_from_sub_params_array_values(
2961
+					$query_params['group_by'],
2962
+					$query_info_carrier,
2963
+					'group_by'
2964
+				);
2965
+			} elseif ( ! empty ($query_params['group_by'])) {
2966
+				$this->_extract_related_model_info_from_query_param(
2967
+					$query_params['group_by'],
2968
+					$query_info_carrier,
2969
+					'group_by'
2970
+				);
2971
+			}
2972
+		}
2973
+		if (array_key_exists('having', $query_params)) {
2974
+			$this->_extract_related_models_from_sub_params_array_keys(
2975
+				$query_params[0],
2976
+				$query_info_carrier,
2977
+				'having'
2978
+			);
2979
+		}
2980
+		if (array_key_exists('order_by', $query_params)) {
2981
+			if (is_array($query_params['order_by'])) {
2982
+				$this->_extract_related_models_from_sub_params_array_keys(
2983
+					$query_params['order_by'],
2984
+					$query_info_carrier,
2985
+					'order_by'
2986
+				);
2987
+			} elseif ( ! empty($query_params['order_by'])) {
2988
+				$this->_extract_related_model_info_from_query_param(
2989
+					$query_params['order_by'],
2990
+					$query_info_carrier,
2991
+					'order_by'
2992
+				);
2993
+			}
2994
+		}
2995
+		if (array_key_exists('force_join', $query_params)) {
2996
+			$this->_extract_related_models_from_sub_params_array_values(
2997
+				$query_params['force_join'],
2998
+				$query_info_carrier,
2999
+				'force_join'
3000
+			);
3001
+		}
3002
+		return $query_info_carrier;
3003
+	}
3004
+
3005
+
3006
+
3007
+	/**
3008
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3009
+	 *
3010
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3011
+	 *                                                      $query_params['having']
3012
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3013
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3014
+	 * @throws EE_Error
3015
+	 * @return \EE_Model_Query_Info_Carrier
3016
+	 */
3017
+	private function _extract_related_models_from_sub_params_array_keys(
3018
+		$sub_query_params,
3019
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3020
+		$query_param_type
3021
+	) {
3022
+		if ( ! empty($sub_query_params)) {
3023
+			$sub_query_params = (array)$sub_query_params;
3024
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3025
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3026
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3027
+					$query_param_type);
3028
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3029
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3030
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3031
+				//of array('Registration.TXN_ID'=>23)
3032
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3033
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3034
+					if ( ! is_array($possibly_array_of_params)) {
3035
+						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'))",
3036
+							"event_espresso"),
3037
+							$param, $possibly_array_of_params));
3038
+					} else {
3039
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3040
+							$model_query_info_carrier, $query_param_type);
3041
+					}
3042
+				} elseif ($query_param_type === 0 //ie WHERE
3043
+						  && is_array($possibly_array_of_params)
3044
+						  && isset($possibly_array_of_params[2])
3045
+						  && $possibly_array_of_params[2] == true
3046
+				) {
3047
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3048
+					//indicating that $possible_array_of_params[1] is actually a field name,
3049
+					//from which we should extract query parameters!
3050
+					if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3051
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3052
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3053
+					}
3054
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3055
+						$model_query_info_carrier, $query_param_type);
3056
+				}
3057
+			}
3058
+		}
3059
+		return $model_query_info_carrier;
3060
+	}
3061
+
3062
+
3063
+
3064
+	/**
3065
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3066
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3067
+	 *
3068
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3069
+	 *                                                      $query_params['having']
3070
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3071
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3072
+	 * @throws EE_Error
3073
+	 * @return \EE_Model_Query_Info_Carrier
3074
+	 */
3075
+	private function _extract_related_models_from_sub_params_array_values(
3076
+		$sub_query_params,
3077
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3078
+		$query_param_type
3079
+	) {
3080
+		if ( ! empty($sub_query_params)) {
3081
+			if ( ! is_array($sub_query_params)) {
3082
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3083
+					$sub_query_params));
3084
+			}
3085
+			foreach ($sub_query_params as $param) {
3086
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3087
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3088
+					$query_param_type);
3089
+			}
3090
+		}
3091
+		return $model_query_info_carrier;
3092
+	}
3093
+
3094
+
3095
+
3096
+	/**
3097
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3098
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3099
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3100
+	 * but use them in a different order. Eg, we need to know what models we are querying
3101
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3102
+	 * other models before we can finalize the where clause SQL.
3103
+	 *
3104
+	 * @param array $query_params
3105
+	 * @throws EE_Error
3106
+	 * @return EE_Model_Query_Info_Carrier
3107
+	 */
3108
+	public function _create_model_query_info_carrier($query_params)
3109
+	{
3110
+		if ( ! is_array($query_params)) {
3111
+			EE_Error::doing_it_wrong(
3112
+				'EEM_Base::_create_model_query_info_carrier',
3113
+				sprintf(
3114
+					__(
3115
+						'$query_params should be an array, you passed a variable of type %s',
3116
+						'event_espresso'
3117
+					),
3118
+					gettype($query_params)
3119
+				),
3120
+				'4.6.0'
3121
+			);
3122
+			$query_params = array();
3123
+		}
3124
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3125
+		//first check if we should alter the query to account for caps or not
3126
+		//because the caps might require us to do extra joins
3127
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3128
+			$query_params[0] = $where_query_params = array_replace_recursive(
3129
+				$where_query_params,
3130
+				$this->caps_where_conditions(
3131
+					$query_params['caps']
3132
+				)
3133
+			);
3134
+		}
3135
+		$query_object = $this->_extract_related_models_from_query($query_params);
3136
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3137
+		foreach ($where_query_params as $key => $value) {
3138
+			if (is_int($key)) {
3139
+				throw new EE_Error(
3140
+					sprintf(
3141
+						__(
3142
+							"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.",
3143
+							"event_espresso"
3144
+						),
3145
+						$key,
3146
+						var_export($value, true),
3147
+						var_export($query_params, true),
3148
+						get_class($this)
3149
+					)
3150
+				);
3151
+			}
3152
+		}
3153
+		if (
3154
+			array_key_exists('default_where_conditions', $query_params)
3155
+			&& ! empty($query_params['default_where_conditions'])
3156
+		) {
3157
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3158
+		} else {
3159
+			$use_default_where_conditions = 'all';
3160
+		}
3161
+		$where_query_params = array_merge(
3162
+			$this->_get_default_where_conditions_for_models_in_query(
3163
+				$query_object,
3164
+				$use_default_where_conditions,
3165
+				$where_query_params
3166
+			),
3167
+			$where_query_params
3168
+		);
3169
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3170
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3171
+		// So we need to setup a subquery and use that for the main join.
3172
+		// Note for now this only works on the primary table for the model.
3173
+		// So for instance, you could set the limit array like this:
3174
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3175
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3176
+			$query_object->set_main_model_join_sql(
3177
+				$this->_construct_limit_join_select(
3178
+					$query_params['on_join_limit'][0],
3179
+					$query_params['on_join_limit'][1]
3180
+				)
3181
+			);
3182
+		}
3183
+		//set limit
3184
+		if (array_key_exists('limit', $query_params)) {
3185
+			if (is_array($query_params['limit'])) {
3186
+				if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3187
+					$e = sprintf(
3188
+						__(
3189
+							"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)",
3190
+							"event_espresso"
3191
+						),
3192
+						http_build_query($query_params['limit'])
3193
+					);
3194
+					throw new EE_Error($e . "|" . $e);
3195
+				}
3196
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3197
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3198
+			} elseif ( ! empty ($query_params['limit'])) {
3199
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3200
+			}
3201
+		}
3202
+		//set order by
3203
+		if (array_key_exists('order_by', $query_params)) {
3204
+			if (is_array($query_params['order_by'])) {
3205
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3206
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3207
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3208
+				if (array_key_exists('order', $query_params)) {
3209
+					throw new EE_Error(
3210
+						sprintf(
3211
+							__(
3212
+								"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 ",
3213
+								"event_espresso"
3214
+							),
3215
+							get_class($this),
3216
+							implode(", ", array_keys($query_params['order_by'])),
3217
+							implode(", ", $query_params['order_by']),
3218
+							$query_params['order']
3219
+						)
3220
+					);
3221
+				}
3222
+				$this->_extract_related_models_from_sub_params_array_keys(
3223
+					$query_params['order_by'],
3224
+					$query_object,
3225
+					'order_by'
3226
+				);
3227
+				//assume it's an array of fields to order by
3228
+				$order_array = array();
3229
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3230
+					$order = $this->_extract_order($order);
3231
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3232
+				}
3233
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3234
+			} elseif ( ! empty ($query_params['order_by'])) {
3235
+				$this->_extract_related_model_info_from_query_param(
3236
+					$query_params['order_by'],
3237
+					$query_object,
3238
+					'order',
3239
+					$query_params['order_by']
3240
+				);
3241
+				$order = isset($query_params['order'])
3242
+					? $this->_extract_order($query_params['order'])
3243
+					: 'DESC';
3244
+				$query_object->set_order_by_sql(
3245
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3246
+				);
3247
+			}
3248
+		}
3249
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3250
+		if ( ! array_key_exists('order_by', $query_params)
3251
+			 && array_key_exists('order', $query_params)
3252
+			 && ! empty($query_params['order'])
3253
+		) {
3254
+			$pk_field = $this->get_primary_key_field();
3255
+			$order = $this->_extract_order($query_params['order']);
3256
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3257
+		}
3258
+		//set group by
3259
+		if (array_key_exists('group_by', $query_params)) {
3260
+			if (is_array($query_params['group_by'])) {
3261
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3262
+				$group_by_array = array();
3263
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3264
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3265
+				}
3266
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3267
+			} elseif ( ! empty ($query_params['group_by'])) {
3268
+				$query_object->set_group_by_sql(
3269
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3270
+				);
3271
+			}
3272
+		}
3273
+		//set having
3274
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3275
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3276
+		}
3277
+		//now, just verify they didn't pass anything wack
3278
+		foreach ($query_params as $query_key => $query_value) {
3279
+			if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3280
+				throw new EE_Error(
3281
+					sprintf(
3282
+						__(
3283
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3284
+							'event_espresso'
3285
+						),
3286
+						$query_key,
3287
+						get_class($this),
3288
+						//						print_r( $this->_allowed_query_params, TRUE )
3289
+						implode(',', $this->_allowed_query_params)
3290
+					)
3291
+				);
3292
+			}
3293
+		}
3294
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3295
+		if (empty($main_model_join_sql)) {
3296
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3297
+		}
3298
+		return $query_object;
3299
+	}
3300
+
3301
+
3302
+
3303
+	/**
3304
+	 * Gets the where conditions that should be imposed on the query based on the
3305
+	 * context (eg reading frontend, backend, edit or delete).
3306
+	 *
3307
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3308
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3309
+	 * @throws \EE_Error
3310
+	 */
3311
+	public function caps_where_conditions($context = self::caps_read)
3312
+	{
3313
+		EEM_Base::verify_is_valid_cap_context($context);
3314
+		$cap_where_conditions = array();
3315
+		$cap_restrictions = $this->caps_missing($context);
3316
+		/**
3317
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3318
+		 */
3319
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3320
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3321
+				$restriction_if_no_cap->get_default_where_conditions());
3322
+		}
3323
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3324
+			$cap_restrictions);
3325
+	}
3326
+
3327
+
3328
+
3329
+	/**
3330
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3331
+	 * otherwise throws an exception
3332
+	 *
3333
+	 * @param string $should_be_order_string
3334
+	 * @return string either ASC, asc, DESC or desc
3335
+	 * @throws EE_Error
3336
+	 */
3337
+	private function _extract_order($should_be_order_string)
3338
+	{
3339
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3340
+			return $should_be_order_string;
3341
+		} else {
3342
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3343
+				"event_espresso"), get_class($this), $should_be_order_string));
3344
+		}
3345
+	}
3346
+
3347
+
3348
+
3349
+	/**
3350
+	 * Looks at all the models which are included in this query, and asks each
3351
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3352
+	 * so they can be merged
3353
+	 *
3354
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3355
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3356
+	 *                                                                  'none' means NO default where conditions will
3357
+	 *                                                                  be used AT ALL during this query.
3358
+	 *                                                                  'other_models_only' means default where
3359
+	 *                                                                  conditions from other models will be used, but
3360
+	 *                                                                  not for this primary model. 'all', the default,
3361
+	 *                                                                  means default where conditions will apply as
3362
+	 *                                                                  normal
3363
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3364
+	 * @throws EE_Error
3365
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3366
+	 */
3367
+	private function _get_default_where_conditions_for_models_in_query(
3368
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3369
+		$use_default_where_conditions = 'all',
3370
+		$where_query_params = array()
3371
+	) {
3372
+		$allowed_used_default_where_conditions_values = array(
3373
+			'all',
3374
+			'this_model_only',
3375
+			'other_models_only',
3376
+			'minimum',
3377
+			'none',
3378
+		);
3379
+		if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3380
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3381
+				"event_espresso"), $use_default_where_conditions,
3382
+				implode(", ", $allowed_used_default_where_conditions_values)));
3383
+		}
3384
+		$universal_query_params = array();
3385
+		if ($use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only') {
3386
+			$universal_query_params = $this->_get_default_where_conditions();
3387
+		} else if ($use_default_where_conditions === 'minimum') {
3388
+			$universal_query_params = $this->_get_minimum_where_conditions();
3389
+		}
3390
+		if (in_array($use_default_where_conditions, array('all', 'other_models_only'))) {
3391
+			foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3392
+				$related_model = $this->get_related_model_obj($model_name);
3393
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3394
+				$overrides = $this->_override_defaults_or_make_null_friendly(
3395
+					$related_model_universal_where_params,
3396
+					$where_query_params,
3397
+					$related_model,
3398
+					$model_relation_path
3399
+				);
3400
+				$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3401
+					$universal_query_params,
3402
+					$overrides
3403
+				);
3404
+			}
3405
+		}
3406
+		return $universal_query_params;
3407
+	}
3408
+
3409
+
3410
+
3411
+	/**
3412
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3413
+	 * then we also add a special where condition which allows for that model's primary key
3414
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3415
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3416
+	 *
3417
+	 * @param array    $default_where_conditions
3418
+	 * @param array    $provided_where_conditions
3419
+	 * @param EEM_Base $model
3420
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3421
+	 * @return array like EEM_Base::get_all's $query_params[0]
3422
+	 * @throws \EE_Error
3423
+	 */
3424
+	private function _override_defaults_or_make_null_friendly(
3425
+		$default_where_conditions,
3426
+		$provided_where_conditions,
3427
+		$model,
3428
+		$model_relation_path
3429
+	) {
3430
+		$null_friendly_where_conditions = array();
3431
+		$none_overridden = true;
3432
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3433
+		foreach ($default_where_conditions as $key => $val) {
3434
+			if (isset($provided_where_conditions[$key])) {
3435
+				$none_overridden = false;
3436
+			} else {
3437
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3438
+			}
3439
+		}
3440
+		if ($none_overridden && $default_where_conditions) {
3441
+			if ($model->has_primary_key_field()) {
3442
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3443
+																				. "."
3444
+																				. $model->primary_key_name()] = array('IS NULL');
3445
+			}/*else{
3446 3446
 				//@todo NO PK, use other defaults
3447 3447
 			}*/
3448
-        }
3449
-        return $null_friendly_where_conditions;
3450
-    }
3451
-
3452
-
3453
-
3454
-    /**
3455
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3456
-     * default where conditions on all get_all, update, and delete queries done by this model.
3457
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3458
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3459
-     *
3460
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3461
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3462
-     */
3463
-    private function _get_default_where_conditions($model_relation_path = null)
3464
-    {
3465
-        if ($this->_ignore_where_strategy) {
3466
-            return array();
3467
-        }
3468
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3469
-    }
3470
-
3471
-
3472
-
3473
-    /**
3474
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3475
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3476
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3477
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3478
-     * Similar to _get_default_where_conditions
3479
-     *
3480
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3481
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3482
-     */
3483
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3484
-    {
3485
-        if ($this->_ignore_where_strategy) {
3486
-            return array();
3487
-        }
3488
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3489
-    }
3490
-
3491
-
3492
-
3493
-    /**
3494
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3495
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3496
-     *
3497
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3498
-     * @return string
3499
-     * @throws \EE_Error
3500
-     */
3501
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3502
-    {
3503
-        $selects = $this->_get_columns_to_select_for_this_model();
3504
-        foreach (
3505
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3506
-            $name_of_other_model_included
3507
-        ) {
3508
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3509
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3510
-            foreach ($other_model_selects as $key => $value) {
3511
-                $selects[] = $value;
3512
-            }
3513
-        }
3514
-        return implode(", ", $selects);
3515
-    }
3516
-
3517
-
3518
-
3519
-    /**
3520
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3521
-     * So that's going to be the columns for all the fields on the model
3522
-     *
3523
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3524
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3525
-     */
3526
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3527
-    {
3528
-        $fields = $this->field_settings();
3529
-        $selects = array();
3530
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3531
-            $this->get_this_model_name());
3532
-        foreach ($fields as $field_obj) {
3533
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3534
-                         . $field_obj->get_table_alias()
3535
-                         . "."
3536
-                         . $field_obj->get_table_column()
3537
-                         . " AS '"
3538
-                         . $table_alias_with_model_relation_chain_prefix
3539
-                         . $field_obj->get_table_alias()
3540
-                         . "."
3541
-                         . $field_obj->get_table_column()
3542
-                         . "'";
3543
-        }
3544
-        //make sure we are also getting the PKs of each table
3545
-        $tables = $this->get_tables();
3546
-        if (count($tables) > 1) {
3547
-            foreach ($tables as $table_obj) {
3548
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3549
-                                       . $table_obj->get_fully_qualified_pk_column();
3550
-                if ( ! in_array($qualified_pk_column, $selects)) {
3551
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3552
-                }
3553
-            }
3554
-        }
3555
-        return $selects;
3556
-    }
3557
-
3558
-
3559
-
3560
-    /**
3561
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3562
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3563
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3564
-     * SQL for joining, and the data types
3565
-     *
3566
-     * @param null|string                 $original_query_param
3567
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3568
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3569
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3570
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3571
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3572
-     *                                                          or 'Registration's
3573
-     * @param string                      $original_query_param what it originally was (eg
3574
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3575
-     *                                                          matches $query_param
3576
-     * @throws EE_Error
3577
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3578
-     */
3579
-    private function _extract_related_model_info_from_query_param(
3580
-        $query_param,
3581
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3582
-        $query_param_type,
3583
-        $original_query_param = null
3584
-    ) {
3585
-        if ($original_query_param === null) {
3586
-            $original_query_param = $query_param;
3587
-        }
3588
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3589
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3590
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3591
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3592
-        //check to see if we have a field on this model
3593
-        $this_model_fields = $this->field_settings(true);
3594
-        if (array_key_exists($query_param, $this_model_fields)) {
3595
-            if ($allow_fields) {
3596
-                return;
3597
-            } else {
3598
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3599
-                    "event_espresso"),
3600
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3601
-            }
3602
-        } //check if this is a special logic query param
3603
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3604
-            if ($allow_logic_query_params) {
3605
-                return;
3606
-            } else {
3607
-                throw new EE_Error(
3608
-                    sprintf(
3609
-                        __('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',
3610
-                            'event_espresso'),
3611
-                        implode('", "', $this->_logic_query_param_keys),
3612
-                        $query_param,
3613
-                        get_class($this),
3614
-                        '<br />',
3615
-                        "\t"
3616
-                        . ' $passed_in_query_info = <pre>'
3617
-                        . print_r($passed_in_query_info, true)
3618
-                        . '</pre>'
3619
-                        . "\n\t"
3620
-                        . ' $query_param_type = '
3621
-                        . $query_param_type
3622
-                        . "\n\t"
3623
-                        . ' $original_query_param = '
3624
-                        . $original_query_param
3625
-                    )
3626
-                );
3627
-            }
3628
-        } //check if it's a custom selection
3629
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3630
-            return;
3631
-        }
3632
-        //check if has a model name at the beginning
3633
-        //and
3634
-        //check if it's a field on a related model
3635
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3636
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3637
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3638
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3639
-                if ($query_param === '') {
3640
-                    //nothing left to $query_param
3641
-                    //we should actually end in a field name, not a model like this!
3642
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3643
-                        "event_espresso"),
3644
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3645
-                } else {
3646
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3647
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3648
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3649
-                    return;
3650
-                }
3651
-            } elseif ($query_param === $valid_related_model_name) {
3652
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3653
-                return;
3654
-            }
3655
-        }
3656
-        //ok so $query_param didn't start with a model name
3657
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3658
-        //it's wack, that's what it is
3659
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3660
-            "event_espresso"),
3661
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3662
-    }
3663
-
3664
-
3665
-
3666
-    /**
3667
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3668
-     * and store it on $passed_in_query_info
3669
-     *
3670
-     * @param string                      $model_name
3671
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3672
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3673
-     *                                                          model and $model_name. Eg, if we are querying Event,
3674
-     *                                                          and are adding a join to 'Payment' with the original
3675
-     *                                                          query param key
3676
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3677
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3678
-     *                                                          Payment wants to add default query params so that it
3679
-     *                                                          will know what models to prepend onto its default query
3680
-     *                                                          params or in case it wants to rename tables (in case
3681
-     *                                                          there are multiple joins to the same table)
3682
-     * @return void
3683
-     * @throws \EE_Error
3684
-     */
3685
-    private function _add_join_to_model(
3686
-        $model_name,
3687
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3688
-        $original_query_param
3689
-    ) {
3690
-        $relation_obj = $this->related_settings_for($model_name);
3691
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3692
-        //check if the relation is HABTM, because then we're essentially doing two joins
3693
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3694
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3695
-            $join_model_obj = $relation_obj->get_join_model();
3696
-            //replace the model specified with the join model for this relation chain, whi
3697
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3698
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3699
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3700
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3701
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3702
-            $passed_in_query_info->merge($new_query_info);
3703
-        }
3704
-        //now just join to the other table pointed to by the relation object, and add its data types
3705
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3706
-            array($model_relation_chain => $model_name),
3707
-            $relation_obj->get_join_statement($model_relation_chain));
3708
-        $passed_in_query_info->merge($new_query_info);
3709
-    }
3710
-
3711
-
3712
-
3713
-    /**
3714
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3715
-     *
3716
-     * @param array $where_params like EEM_Base::get_all
3717
-     * @return string of SQL
3718
-     * @throws \EE_Error
3719
-     */
3720
-    private function _construct_where_clause($where_params)
3721
-    {
3722
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3723
-        if ($SQL) {
3724
-            return " WHERE " . $SQL;
3725
-        } else {
3726
-            return '';
3727
-        }
3728
-    }
3729
-
3730
-
3731
-
3732
-    /**
3733
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3734
-     * and should be passed HAVING parameters, not WHERE parameters
3735
-     *
3736
-     * @param array $having_params
3737
-     * @return string
3738
-     * @throws \EE_Error
3739
-     */
3740
-    private function _construct_having_clause($having_params)
3741
-    {
3742
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3743
-        if ($SQL) {
3744
-            return " HAVING " . $SQL;
3745
-        } else {
3746
-            return '';
3747
-        }
3748
-    }
3749
-
3750
-
3751
-
3752
-    /**
3753
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3754
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3755
-     * EEM_Attendee.
3756
-     *
3757
-     * @param string $field_name
3758
-     * @param string $model_name
3759
-     * @return EE_Model_Field_Base
3760
-     * @throws EE_Error
3761
-     */
3762
-    protected function _get_field_on_model($field_name, $model_name)
3763
-    {
3764
-        $model_class = 'EEM_' . $model_name;
3765
-        $model_filepath = $model_class . ".model.php";
3766
-        if (is_readable($model_filepath)) {
3767
-            require_once($model_filepath);
3768
-            $model_instance = call_user_func($model_name . "::instance");
3769
-            /* @var $model_instance EEM_Base */
3770
-            return $model_instance->field_settings_for($field_name);
3771
-        } else {
3772
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3773
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3774
-        }
3775
-    }
3776
-
3777
-
3778
-
3779
-    /**
3780
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3781
-     * Event_Meta.meta_value = 'foo'))"
3782
-     *
3783
-     * @param array  $where_params see EEM_Base::get_all for documentation
3784
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3785
-     * @throws EE_Error
3786
-     * @return string of SQL
3787
-     */
3788
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3789
-    {
3790
-        $where_clauses = array();
3791
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3792
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3793
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3794
-                switch ($query_param) {
3795
-                    case 'not':
3796
-                    case 'NOT':
3797
-                        $where_clauses[] = "! ("
3798
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3799
-                                $glue)
3800
-                                           . ")";
3801
-                        break;
3802
-                    case 'and':
3803
-                    case 'AND':
3804
-                        $where_clauses[] = " ("
3805
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3806
-                                ' AND ')
3807
-                                           . ")";
3808
-                        break;
3809
-                    case 'or':
3810
-                    case 'OR':
3811
-                        $where_clauses[] = " ("
3812
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3813
-                                ' OR ')
3814
-                                           . ")";
3815
-                        break;
3816
-                }
3817
-            } else {
3818
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3819
-                //if it's not a normal field, maybe it's a custom selection?
3820
-                if ( ! $field_obj) {
3821
-                    if (isset($this->_custom_selections[$query_param][1])) {
3822
-                        $field_obj = $this->_custom_selections[$query_param][1];
3823
-                    } else {
3824
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3825
-                            "event_espresso"), $query_param));
3826
-                    }
3827
-                }
3828
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3829
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3830
-            }
3831
-        }
3832
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3833
-    }
3834
-
3835
-
3836
-
3837
-    /**
3838
-     * Takes the input parameter and extract the table name (alias) and column name
3839
-     *
3840
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3841
-     * @throws EE_Error
3842
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3843
-     */
3844
-    private function _deduce_column_name_from_query_param($query_param)
3845
-    {
3846
-        $field = $this->_deduce_field_from_query_param($query_param);
3847
-        if ($field) {
3848
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3849
-                $query_param);
3850
-            return $table_alias_prefix . $field->get_qualified_column();
3851
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3852
-            //maybe it's custom selection item?
3853
-            //if so, just use it as the "column name"
3854
-            return $query_param;
3855
-        } else {
3856
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3857
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3858
-        }
3859
-    }
3860
-
3861
-
3862
-
3863
-    /**
3864
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3865
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3866
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3867
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3868
-     *
3869
-     * @param string $condition_query_param_key
3870
-     * @return string
3871
-     */
3872
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3873
-    {
3874
-        $pos_of_star = strpos($condition_query_param_key, '*');
3875
-        if ($pos_of_star === false) {
3876
-            return $condition_query_param_key;
3877
-        } else {
3878
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3879
-            return $condition_query_param_sans_star;
3880
-        }
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3887
-     *
3888
-     * @param                            mixed      array | string    $op_and_value
3889
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3890
-     * @throws EE_Error
3891
-     * @return string
3892
-     */
3893
-    private function _construct_op_and_value($op_and_value, $field_obj)
3894
-    {
3895
-        if (is_array($op_and_value)) {
3896
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3897
-            if ( ! $operator) {
3898
-                $php_array_like_string = array();
3899
-                foreach ($op_and_value as $key => $value) {
3900
-                    $php_array_like_string[] = "$key=>$value";
3901
-                }
3902
-                throw new EE_Error(
3903
-                    sprintf(
3904
-                        __(
3905
-                            "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))",
3906
-                            "event_espresso"
3907
-                        ),
3908
-                        implode(",", $php_array_like_string)
3909
-                    )
3910
-                );
3911
-            }
3912
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3913
-        } else {
3914
-            $operator = '=';
3915
-            $value = $op_and_value;
3916
-        }
3917
-        //check to see if the value is actually another field
3918
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3919
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3920
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3921
-            //in this case, the value should be an array, or at least a comma-separated list
3922
-            //it will need to handle a little differently
3923
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
3924
-            //note: $cleaned_value has already been run through $wpdb->prepare()
3925
-            return $operator . SP . $cleaned_value;
3926
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3927
-            //the value should be an array with count of two.
3928
-            if (count($value) !== 2) {
3929
-                throw new EE_Error(
3930
-                    sprintf(
3931
-                        __(
3932
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3933
-                            'event_espresso'
3934
-                        ),
3935
-                        "BETWEEN"
3936
-                    )
3937
-                );
3938
-            }
3939
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
3940
-            return $operator . SP . $cleaned_value;
3941
-        } elseif (in_array($operator, $this->_null_style_operators)) {
3942
-            if ($value !== null) {
3943
-                throw new EE_Error(
3944
-                    sprintf(
3945
-                        __(
3946
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3947
-                            "event_espresso"
3948
-                        ),
3949
-                        $value,
3950
-                        $operator
3951
-                    )
3952
-                );
3953
-            }
3954
-            return $operator;
3955
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
3956
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
3957
-            //remove other junk. So just treat it as a string.
3958
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3959
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3960
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3961
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3962
-            throw new EE_Error(
3963
-                sprintf(
3964
-                    __(
3965
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3966
-                        'event_espresso'
3967
-                    ),
3968
-                    $operator,
3969
-                    $operator
3970
-                )
3971
-            );
3972
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
3973
-            throw new EE_Error(
3974
-                sprintf(
3975
-                    __(
3976
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3977
-                        'event_espresso'
3978
-                    ),
3979
-                    $operator,
3980
-                    $operator
3981
-                )
3982
-            );
3983
-        } else {
3984
-            throw new EE_Error(
3985
-                sprintf(
3986
-                    __(
3987
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3988
-                        "event_espresso"
3989
-                    ),
3990
-                    http_build_query($op_and_value)
3991
-                )
3992
-            );
3993
-        }
3994
-    }
3995
-
3996
-
3997
-
3998
-    /**
3999
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4000
-     *
4001
-     * @param array                      $values
4002
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4003
-     *                                              '%s'
4004
-     * @return string
4005
-     * @throws \EE_Error
4006
-     */
4007
-    public function _construct_between_value($values, $field_obj)
4008
-    {
4009
-        $cleaned_values = array();
4010
-        foreach ($values as $value) {
4011
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4012
-        }
4013
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4014
-    }
4015
-
4016
-
4017
-
4018
-    /**
4019
-     * Takes an array or a comma-separated list of $values and cleans them
4020
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4021
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4022
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4023
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4024
-     *
4025
-     * @param mixed                      $values    array or comma-separated string
4026
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4027
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4028
-     * @throws \EE_Error
4029
-     */
4030
-    public function _construct_in_value($values, $field_obj)
4031
-    {
4032
-        //check if the value is a CSV list
4033
-        if (is_string($values)) {
4034
-            //in which case, turn it into an array
4035
-            $values = explode(",", $values);
4036
-        }
4037
-        $cleaned_values = array();
4038
-        foreach ($values as $value) {
4039
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4040
-        }
4041
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4042
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4043
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4044
-        if (empty($cleaned_values)) {
4045
-            $all_fields = $this->field_settings();
4046
-            $a_field = array_shift($all_fields);
4047
-            $main_table = $this->_get_main_table();
4048
-            $cleaned_values[] = "SELECT "
4049
-                                . $a_field->get_table_column()
4050
-                                . " FROM "
4051
-                                . $main_table->get_table_name()
4052
-                                . " WHERE FALSE";
4053
-        }
4054
-        return "(" . implode(",", $cleaned_values) . ")";
4055
-    }
4056
-
4057
-
4058
-
4059
-    /**
4060
-     * @param mixed                      $value
4061
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4062
-     * @throws EE_Error
4063
-     * @return false|null|string
4064
-     */
4065
-    private function _wpdb_prepare_using_field($value, $field_obj)
4066
-    {
4067
-        /** @type WPDB $wpdb */
4068
-        global $wpdb;
4069
-        if ($field_obj instanceof EE_Model_Field_Base) {
4070
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4071
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4072
-        } else {//$field_obj should really just be a data type
4073
-            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4074
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4075
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4076
-            }
4077
-            return $wpdb->prepare($field_obj, $value);
4078
-        }
4079
-    }
4080
-
4081
-
4082
-
4083
-    /**
4084
-     * Takes the input parameter and finds the model field that it indicates.
4085
-     *
4086
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4087
-     * @throws EE_Error
4088
-     * @return EE_Model_Field_Base
4089
-     */
4090
-    protected function _deduce_field_from_query_param($query_param_name)
4091
-    {
4092
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4093
-        //which will help us find the database table and column
4094
-        $query_param_parts = explode(".", $query_param_name);
4095
-        if (empty($query_param_parts)) {
4096
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4097
-                'event_espresso'), $query_param_name));
4098
-        }
4099
-        $number_of_parts = count($query_param_parts);
4100
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4101
-        if ($number_of_parts === 1) {
4102
-            $field_name = $last_query_param_part;
4103
-            $model_obj = $this;
4104
-        } else {// $number_of_parts >= 2
4105
-            //the last part is the column name, and there are only 2parts. therefore...
4106
-            $field_name = $last_query_param_part;
4107
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4108
-        }
4109
-        try {
4110
-            return $model_obj->field_settings_for($field_name);
4111
-        } catch (EE_Error $e) {
4112
-            return null;
4113
-        }
4114
-    }
4115
-
4116
-
4117
-
4118
-    /**
4119
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4120
-     * alias and column which corresponds to it
4121
-     *
4122
-     * @param string $field_name
4123
-     * @throws EE_Error
4124
-     * @return string
4125
-     */
4126
-    public function _get_qualified_column_for_field($field_name)
4127
-    {
4128
-        $all_fields = $this->field_settings();
4129
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4130
-        if ($field) {
4131
-            return $field->get_qualified_column();
4132
-        } else {
4133
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4134
-                'event_espresso'), $field_name, get_class($this)));
4135
-        }
4136
-    }
4137
-
4138
-
4139
-
4140
-    /**
4141
-     * constructs the select use on special limit joins
4142
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4143
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4144
-     * (as that is typically where the limits would be set).
4145
-     *
4146
-     * @param  string       $table_alias The table the select is being built for
4147
-     * @param  mixed|string $limit       The limit for this select
4148
-     * @return string                The final select join element for the query.
4149
-     */
4150
-    public function _construct_limit_join_select($table_alias, $limit)
4151
-    {
4152
-        $SQL = '';
4153
-        foreach ($this->_tables as $table_obj) {
4154
-            if ($table_obj instanceof EE_Primary_Table) {
4155
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4156
-                    ? $table_obj->get_select_join_limit($limit)
4157
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4158
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4159
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4160
-                    ? $table_obj->get_select_join_limit_join($limit)
4161
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4162
-            }
4163
-        }
4164
-        return $SQL;
4165
-    }
4166
-
4167
-
4168
-
4169
-    /**
4170
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4171
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4172
-     *
4173
-     * @return string SQL
4174
-     * @throws \EE_Error
4175
-     */
4176
-    public function _construct_internal_join()
4177
-    {
4178
-        $SQL = $this->_get_main_table()->get_table_sql();
4179
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4180
-        return $SQL;
4181
-    }
4182
-
4183
-
4184
-
4185
-    /**
4186
-     * Constructs the SQL for joining all the tables on this model.
4187
-     * Normally $alias should be the primary table's alias, but in cases where
4188
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4189
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4190
-     * alias, this will construct SQL like:
4191
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4192
-     * With $alias being a secondary table's alias, this will construct SQL like:
4193
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4194
-     *
4195
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4196
-     * @return string
4197
-     */
4198
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4199
-    {
4200
-        $SQL = '';
4201
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4202
-        foreach ($this->_tables as $table_obj) {
4203
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4204
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4205
-                    //so we're joining to this table, meaning the table is already in
4206
-                    //the FROM statement, BUT the primary table isn't. So we want
4207
-                    //to add the inverse join sql
4208
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4209
-                } else {
4210
-                    //just add a regular JOIN to this table from the primary table
4211
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4212
-                }
4213
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4214
-        }
4215
-        return $SQL;
4216
-    }
4217
-
4218
-
4219
-
4220
-    /**
4221
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4222
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4223
-     * their data type (eg, '%s', '%d', etc)
4224
-     *
4225
-     * @return array
4226
-     */
4227
-    public function _get_data_types()
4228
-    {
4229
-        $data_types = array();
4230
-        foreach ($this->field_settings() as $field_obj) {
4231
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4232
-            /** @var $field_obj EE_Model_Field_Base */
4233
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4234
-        }
4235
-        return $data_types;
4236
-    }
4237
-
4238
-
4239
-
4240
-    /**
4241
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4242
-     *
4243
-     * @param string $model_name
4244
-     * @throws EE_Error
4245
-     * @return EEM_Base
4246
-     */
4247
-    public function get_related_model_obj($model_name)
4248
-    {
4249
-        $model_classname = "EEM_" . $model_name;
4250
-        if ( ! class_exists($model_classname)) {
4251
-            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",
4252
-                'event_espresso'), $model_name, $model_classname));
4253
-        }
4254
-        return call_user_func($model_classname . "::instance");
4255
-    }
4256
-
4257
-
4258
-
4259
-    /**
4260
-     * Returns the array of EE_ModelRelations for this model.
4261
-     *
4262
-     * @return EE_Model_Relation_Base[]
4263
-     */
4264
-    public function relation_settings()
4265
-    {
4266
-        return $this->_model_relations;
4267
-    }
4268
-
4269
-
4270
-
4271
-    /**
4272
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4273
-     * because without THOSE models, this model probably doesn't have much purpose.
4274
-     * (Eg, without an event, datetimes have little purpose.)
4275
-     *
4276
-     * @return EE_Belongs_To_Relation[]
4277
-     */
4278
-    public function belongs_to_relations()
4279
-    {
4280
-        $belongs_to_relations = array();
4281
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4282
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4283
-                $belongs_to_relations[$model_name] = $relation_obj;
4284
-            }
4285
-        }
4286
-        return $belongs_to_relations;
4287
-    }
4288
-
4289
-
4290
-
4291
-    /**
4292
-     * Returns the specified EE_Model_Relation, or throws an exception
4293
-     *
4294
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4295
-     * @throws EE_Error
4296
-     * @return EE_Model_Relation_Base
4297
-     */
4298
-    public function related_settings_for($relation_name)
4299
-    {
4300
-        $relatedModels = $this->relation_settings();
4301
-        if ( ! array_key_exists($relation_name, $relatedModels)) {
4302
-            throw new EE_Error(
4303
-                sprintf(
4304
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4305
-                        'event_espresso'),
4306
-                    $relation_name,
4307
-                    $this->_get_class_name(),
4308
-                    implode(', ', array_keys($relatedModels))
4309
-                )
4310
-            );
4311
-        }
4312
-        return $relatedModels[$relation_name];
4313
-    }
4314
-
4315
-
4316
-
4317
-    /**
4318
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4319
-     * fields
4320
-     *
4321
-     * @param string $fieldName
4322
-     * @throws EE_Error
4323
-     * @return EE_Model_Field_Base
4324
-     */
4325
-    public function field_settings_for($fieldName)
4326
-    {
4327
-        $fieldSettings = $this->field_settings(true);
4328
-        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4329
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4330
-                get_class($this)));
4331
-        }
4332
-        return $fieldSettings[$fieldName];
4333
-    }
4334
-
4335
-
4336
-
4337
-    /**
4338
-     * Checks if this field exists on this model
4339
-     *
4340
-     * @param string $fieldName a key in the model's _field_settings array
4341
-     * @return boolean
4342
-     */
4343
-    public function has_field($fieldName)
4344
-    {
4345
-        $fieldSettings = $this->field_settings(true);
4346
-        if (isset($fieldSettings[$fieldName])) {
4347
-            return true;
4348
-        } else {
4349
-            return false;
4350
-        }
4351
-    }
4352
-
4353
-
4354
-
4355
-    /**
4356
-     * Returns whether or not this model has a relation to the specified model
4357
-     *
4358
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4359
-     * @return boolean
4360
-     */
4361
-    public function has_relation($relation_name)
4362
-    {
4363
-        $relations = $this->relation_settings();
4364
-        if (isset($relations[$relation_name])) {
4365
-            return true;
4366
-        } else {
4367
-            return false;
4368
-        }
4369
-    }
4370
-
4371
-
4372
-
4373
-    /**
4374
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4375
-     * Eg, on EE_Answer that would be ANS_ID field object
4376
-     *
4377
-     * @param $field_obj
4378
-     * @return boolean
4379
-     */
4380
-    public function is_primary_key_field($field_obj)
4381
-    {
4382
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4383
-    }
4384
-
4385
-
4386
-
4387
-    /**
4388
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4389
-     * Eg, on EE_Answer that would be ANS_ID field object
4390
-     *
4391
-     * @return EE_Model_Field_Base
4392
-     * @throws EE_Error
4393
-     */
4394
-    public function get_primary_key_field()
4395
-    {
4396
-        if ($this->_primary_key_field === null) {
4397
-            foreach ($this->field_settings(true) as $field_obj) {
4398
-                if ($this->is_primary_key_field($field_obj)) {
4399
-                    $this->_primary_key_field = $field_obj;
4400
-                    break;
4401
-                }
4402
-            }
4403
-            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4404
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4405
-                    get_class($this)));
4406
-            }
4407
-        }
4408
-        return $this->_primary_key_field;
4409
-    }
4410
-
4411
-
4412
-
4413
-    /**
4414
-     * Returns whether or not not there is a primary key on this model.
4415
-     * Internally does some caching.
4416
-     *
4417
-     * @return boolean
4418
-     */
4419
-    public function has_primary_key_field()
4420
-    {
4421
-        if ($this->_has_primary_key_field === null) {
4422
-            try {
4423
-                $this->get_primary_key_field();
4424
-                $this->_has_primary_key_field = true;
4425
-            } catch (EE_Error $e) {
4426
-                $this->_has_primary_key_field = false;
4427
-            }
4428
-        }
4429
-        return $this->_has_primary_key_field;
4430
-    }
4431
-
4432
-
4433
-
4434
-    /**
4435
-     * Finds the first field of type $field_class_name.
4436
-     *
4437
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4438
-     *                                 EE_Foreign_Key_Field, etc
4439
-     * @return EE_Model_Field_Base or null if none is found
4440
-     */
4441
-    public function get_a_field_of_type($field_class_name)
4442
-    {
4443
-        foreach ($this->field_settings() as $field) {
4444
-            if ($field instanceof $field_class_name) {
4445
-                return $field;
4446
-            }
4447
-        }
4448
-        return null;
4449
-    }
4450
-
4451
-
4452
-
4453
-    /**
4454
-     * Gets a foreign key field pointing to model.
4455
-     *
4456
-     * @param string $model_name eg Event, Registration, not EEM_Event
4457
-     * @return EE_Foreign_Key_Field_Base
4458
-     * @throws EE_Error
4459
-     */
4460
-    public function get_foreign_key_to($model_name)
4461
-    {
4462
-        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4463
-            foreach ($this->field_settings() as $field) {
4464
-                if (
4465
-                    $field instanceof EE_Foreign_Key_Field_Base
4466
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4467
-                ) {
4468
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4469
-                    break;
4470
-                }
4471
-            }
4472
-            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4473
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4474
-                    'event_espresso'), $model_name, get_class($this)));
4475
-            }
4476
-        }
4477
-        return $this->_cache_foreign_key_to_fields[$model_name];
4478
-    }
4479
-
4480
-
4481
-
4482
-    /**
4483
-     * Gets the actual table for the table alias
4484
-     *
4485
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4486
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4487
-     *                            Either one works
4488
-     * @return EE_Table_Base
4489
-     */
4490
-    public function get_table_for_alias($table_alias)
4491
-    {
4492
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4493
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4494
-    }
4495
-
4496
-
4497
-
4498
-    /**
4499
-     * Returns a flat array of all field son this model, instead of organizing them
4500
-     * by table_alias as they are in the constructor.
4501
-     *
4502
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4503
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4504
-     */
4505
-    public function field_settings($include_db_only_fields = false)
4506
-    {
4507
-        if ($include_db_only_fields) {
4508
-            if ($this->_cached_fields === null) {
4509
-                $this->_cached_fields = array();
4510
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4511
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4512
-                        $this->_cached_fields[$field_name] = $field_obj;
4513
-                    }
4514
-                }
4515
-            }
4516
-            return $this->_cached_fields;
4517
-        } else {
4518
-            if ($this->_cached_fields_non_db_only === null) {
4519
-                $this->_cached_fields_non_db_only = array();
4520
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4521
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4522
-                        /** @var $field_obj EE_Model_Field_Base */
4523
-                        if ( ! $field_obj->is_db_only_field()) {
4524
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4525
-                        }
4526
-                    }
4527
-                }
4528
-            }
4529
-            return $this->_cached_fields_non_db_only;
4530
-        }
4531
-    }
4532
-
4533
-
4534
-
4535
-    /**
4536
-     *        cycle though array of attendees and create objects out of each item
4537
-     *
4538
-     * @access        private
4539
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4540
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4541
-     *                           numerically indexed)
4542
-     * @throws \EE_Error
4543
-     */
4544
-    protected function _create_objects($rows = array())
4545
-    {
4546
-        $array_of_objects = array();
4547
-        if (empty($rows)) {
4548
-            return array();
4549
-        }
4550
-        $count_if_model_has_no_primary_key = 0;
4551
-        $has_primary_key = $this->has_primary_key_field();
4552
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4553
-        foreach ((array)$rows as $row) {
4554
-            if (empty($row)) {
4555
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4556
-                return array();
4557
-            }
4558
-            //check if we've already set this object in the results array,
4559
-            //in which case there's no need to process it further (again)
4560
-            if ($has_primary_key) {
4561
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4562
-                    $row,
4563
-                    $primary_key_field->get_qualified_column(),
4564
-                    $primary_key_field->get_table_column()
4565
-                );
4566
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4567
-                    continue;
4568
-                }
4569
-            }
4570
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4571
-            if ( ! $classInstance) {
4572
-                throw new EE_Error(
4573
-                    sprintf(
4574
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4575
-                        $this->get_this_model_name(),
4576
-                        http_build_query($row)
4577
-                    )
4578
-                );
4579
-            }
4580
-            //set the timezone on the instantiated objects
4581
-            $classInstance->set_timezone($this->_timezone);
4582
-            //make sure if there is any timezone setting present that we set the timezone for the object
4583
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4584
-            $array_of_objects[$key] = $classInstance;
4585
-            //also, for all the relations of type BelongsTo, see if we can cache
4586
-            //those related models
4587
-            //(we could do this for other relations too, but if there are conditions
4588
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4589
-            //so it requires a little more thought than just caching them immediately...)
4590
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4591
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4592
-                    //check if this model's INFO is present. If so, cache it on the model
4593
-                    $other_model = $relation_obj->get_other_model();
4594
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4595
-                    //if we managed to make a model object from the results, cache it on the main model object
4596
-                    if ($other_model_obj_maybe) {
4597
-                        //set timezone on these other model objects if they are present
4598
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4599
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4600
-                    }
4601
-                }
4602
-            }
4603
-        }
4604
-        return $array_of_objects;
4605
-    }
4606
-
4607
-
4608
-
4609
-    /**
4610
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4611
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4612
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4613
-     * object (as set in the model_field!).
4614
-     *
4615
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4616
-     */
4617
-    public function create_default_object()
4618
-    {
4619
-        $this_model_fields_and_values = array();
4620
-        //setup the row using default values;
4621
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4622
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4623
-        }
4624
-        $className = $this->_get_class_name();
4625
-        $classInstance = EE_Registry::instance()
4626
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4627
-        return $classInstance;
4628
-    }
4629
-
4630
-
4631
-
4632
-    /**
4633
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4634
-     *                             or an stdClass where each property is the name of a column,
4635
-     * @return EE_Base_Class
4636
-     * @throws \EE_Error
4637
-     */
4638
-    public function instantiate_class_from_array_or_object($cols_n_values)
4639
-    {
4640
-        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4641
-            $cols_n_values = get_object_vars($cols_n_values);
4642
-        }
4643
-        $primary_key = null;
4644
-        //make sure the array only has keys that are fields/columns on this model
4645
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4646
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4647
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4648
-        }
4649
-        $className = $this->_get_class_name();
4650
-        //check we actually found results that we can use to build our model object
4651
-        //if not, return null
4652
-        if ($this->has_primary_key_field()) {
4653
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4654
-                return null;
4655
-            }
4656
-        } else if ($this->unique_indexes()) {
4657
-            $first_column = reset($this_model_fields_n_values);
4658
-            if (empty($first_column)) {
4659
-                return null;
4660
-            }
4661
-        }
4662
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4663
-        if ($primary_key) {
4664
-            $classInstance = $this->get_from_entity_map($primary_key);
4665
-            if ( ! $classInstance) {
4666
-                $classInstance = EE_Registry::instance()
4667
-                                            ->load_class($className,
4668
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4669
-                // add this new object to the entity map
4670
-                $classInstance = $this->add_to_entity_map($classInstance);
4671
-            }
4672
-        } else {
4673
-            $classInstance = EE_Registry::instance()
4674
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4675
-                                            true, false);
4676
-        }
4677
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4678
-        $this->set_timezone($classInstance->get_timezone());
4679
-        return $classInstance;
4680
-    }
4681
-
4682
-
4683
-
4684
-    /**
4685
-     * Gets the model object from the  entity map if it exists
4686
-     *
4687
-     * @param int|string $id the ID of the model object
4688
-     * @return EE_Base_Class
4689
-     */
4690
-    public function get_from_entity_map($id)
4691
-    {
4692
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4693
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4694
-    }
4695
-
4696
-
4697
-
4698
-    /**
4699
-     * add_to_entity_map
4700
-     * Adds the object to the model's entity mappings
4701
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4702
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4703
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4704
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4705
-     *        then this method should be called immediately after the update query
4706
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4707
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4708
-     *
4709
-     * @param    EE_Base_Class $object
4710
-     * @throws EE_Error
4711
-     * @return \EE_Base_Class
4712
-     */
4713
-    public function add_to_entity_map(EE_Base_Class $object)
4714
-    {
4715
-        $className = $this->_get_class_name();
4716
-        if ( ! $object instanceof $className) {
4717
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4718
-                is_object($object) ? get_class($object) : $object, $className));
4719
-        }
4720
-        /** @var $object EE_Base_Class */
4721
-        if ( ! $object->ID()) {
4722
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4723
-                "event_espresso"), get_class($this)));
4724
-        }
4725
-        // double check it's not already there
4726
-        $classInstance = $this->get_from_entity_map($object->ID());
4727
-        if ($classInstance) {
4728
-            return $classInstance;
4729
-        } else {
4730
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4731
-            return $object;
4732
-        }
4733
-    }
4734
-
4735
-
4736
-
4737
-    /**
4738
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4739
-     * if no identifier is provided, then the entire entity map is emptied
4740
-     *
4741
-     * @param int|string $id the ID of the model object
4742
-     * @return boolean
4743
-     */
4744
-    public function clear_entity_map($id = null)
4745
-    {
4746
-        if (empty($id)) {
4747
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4748
-            return true;
4749
-        }
4750
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4751
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4752
-            return true;
4753
-        }
4754
-        return false;
4755
-    }
4756
-
4757
-
4758
-
4759
-    /**
4760
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4761
-     * Given an array where keys are column (or column alias) names and values,
4762
-     * returns an array of their corresponding field names and database values
4763
-     *
4764
-     * @param array $cols_n_values
4765
-     * @return array
4766
-     */
4767
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4768
-    {
4769
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4770
-    }
4771
-
4772
-
4773
-
4774
-    /**
4775
-     * _deduce_fields_n_values_from_cols_n_values
4776
-     * Given an array where keys are column (or column alias) names and values,
4777
-     * returns an array of their corresponding field names and database values
4778
-     *
4779
-     * @param string $cols_n_values
4780
-     * @return array
4781
-     */
4782
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4783
-    {
4784
-        $this_model_fields_n_values = array();
4785
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
4786
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4787
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4788
-            //there is a primary key on this table and its not set. Use defaults for all its columns
4789
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
4790
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4791
-                    if ( ! $field_obj->is_db_only_field()) {
4792
-                        //prepare field as if its coming from db
4793
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4794
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4795
-                    }
4796
-                }
4797
-            } else {
4798
-                //the table's rows existed. Use their values
4799
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4800
-                    if ( ! $field_obj->is_db_only_field()) {
4801
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4802
-                            $cols_n_values, $field_obj->get_qualified_column(),
4803
-                            $field_obj->get_table_column()
4804
-                        );
4805
-                    }
4806
-                }
4807
-            }
4808
-        }
4809
-        return $this_model_fields_n_values;
4810
-    }
4811
-
4812
-
4813
-
4814
-    /**
4815
-     * @param $cols_n_values
4816
-     * @param $qualified_column
4817
-     * @param $regular_column
4818
-     * @return null
4819
-     */
4820
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4821
-    {
4822
-        $value = null;
4823
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4824
-        //does the field on the model relate to this column retrieved from the db?
4825
-        //or is it a db-only field? (not relating to the model)
4826
-        if (isset($cols_n_values[$qualified_column])) {
4827
-            $value = $cols_n_values[$qualified_column];
4828
-        } elseif (isset($cols_n_values[$regular_column])) {
4829
-            $value = $cols_n_values[$regular_column];
4830
-        }
4831
-        return $value;
4832
-    }
4833
-
4834
-
4835
-
4836
-    /**
4837
-     * refresh_entity_map_from_db
4838
-     * Makes sure the model object in the entity map at $id assumes the values
4839
-     * of the database (opposite of EE_base_Class::save())
4840
-     *
4841
-     * @param int|string $id
4842
-     * @return EE_Base_Class
4843
-     * @throws \EE_Error
4844
-     */
4845
-    public function refresh_entity_map_from_db($id)
4846
-    {
4847
-        $obj_in_map = $this->get_from_entity_map($id);
4848
-        if ($obj_in_map) {
4849
-            $wpdb_results = $this->_get_all_wpdb_results(
4850
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4851
-            );
4852
-            if ($wpdb_results && is_array($wpdb_results)) {
4853
-                $one_row = reset($wpdb_results);
4854
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4855
-                    $obj_in_map->set_from_db($field_name, $db_value);
4856
-                }
4857
-                //clear the cache of related model objects
4858
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4859
-                    $obj_in_map->clear_cache($relation_name, null, true);
4860
-                }
4861
-            }
4862
-            return $obj_in_map;
4863
-        } else {
4864
-            return $this->get_one_by_ID($id);
4865
-        }
4866
-    }
4867
-
4868
-
4869
-
4870
-    /**
4871
-     * refresh_entity_map_with
4872
-     * Leaves the entry in the entity map alone, but updates it to match the provided
4873
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4874
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4875
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4876
-     *
4877
-     * @param int|string    $id
4878
-     * @param EE_Base_Class $replacing_model_obj
4879
-     * @return \EE_Base_Class
4880
-     * @throws \EE_Error
4881
-     */
4882
-    public function refresh_entity_map_with($id, $replacing_model_obj)
4883
-    {
4884
-        $obj_in_map = $this->get_from_entity_map($id);
4885
-        if ($obj_in_map) {
4886
-            if ($replacing_model_obj instanceof EE_Base_Class) {
4887
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4888
-                    $obj_in_map->set($field_name, $value);
4889
-                }
4890
-                //make the model object in the entity map's cache match the $replacing_model_obj
4891
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4892
-                    $obj_in_map->clear_cache($relation_name, null, true);
4893
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4894
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4895
-                    }
4896
-                }
4897
-            }
4898
-            return $obj_in_map;
4899
-        } else {
4900
-            $this->add_to_entity_map($replacing_model_obj);
4901
-            return $replacing_model_obj;
4902
-        }
4903
-    }
4904
-
4905
-
4906
-
4907
-    /**
4908
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4909
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4910
-     * require_once($this->_getClassName().".class.php");
4911
-     *
4912
-     * @return string
4913
-     */
4914
-    private function _get_class_name()
4915
-    {
4916
-        return "EE_" . $this->get_this_model_name();
4917
-    }
4918
-
4919
-
4920
-
4921
-    /**
4922
-     * Get the name of the items this model represents, for the quantity specified. Eg,
4923
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4924
-     * it would be 'Events'.
4925
-     *
4926
-     * @param int $quantity
4927
-     * @return string
4928
-     */
4929
-    public function item_name($quantity = 1)
4930
-    {
4931
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4932
-    }
4933
-
4934
-
4935
-
4936
-    /**
4937
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4938
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
4939
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
4940
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
4941
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
4942
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
4943
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
4944
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
4945
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
4946
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4947
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4948
-     *        return $previousReturnValue.$returnString;
4949
-     * }
4950
-     * require('EEM_Answer.model.php');
4951
-     * $answer=EEM_Answer::instance();
4952
-     * echo $answer->my_callback('monkeys',100);
4953
-     * //will output "you called my_callback! and passed args:monkeys,100"
4954
-     *
4955
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4956
-     * @param array  $args       array of original arguments passed to the function
4957
-     * @throws EE_Error
4958
-     * @return mixed whatever the plugin which calls add_filter decides
4959
-     */
4960
-    public function __call($methodName, $args)
4961
-    {
4962
-        $className = get_class($this);
4963
-        $tagName = "FHEE__{$className}__{$methodName}";
4964
-        if ( ! has_filter($tagName)) {
4965
-            throw new EE_Error(
4966
-                sprintf(
4967
-                    __('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 );',
4968
-                        'event_espresso'),
4969
-                    $methodName,
4970
-                    $className,
4971
-                    $tagName,
4972
-                    '<br />'
4973
-                )
4974
-            );
4975
-        }
4976
-        return apply_filters($tagName, null, $this, $args);
4977
-    }
4978
-
4979
-
4980
-
4981
-    /**
4982
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4983
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4984
-     *
4985
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
4986
-     *                                                       the EE_Base_Class object that corresponds to this Model,
4987
-     *                                                       the object's class name
4988
-     *                                                       or object's ID
4989
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
4990
-     *                                                       exists in the database. If it does not, we add it
4991
-     * @throws EE_Error
4992
-     * @return EE_Base_Class
4993
-     */
4994
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
4995
-    {
4996
-        $className = $this->_get_class_name();
4997
-        if ($base_class_obj_or_id instanceof $className) {
4998
-            $model_object = $base_class_obj_or_id;
4999
-        } else {
5000
-            $primary_key_field = $this->get_primary_key_field();
5001
-            if (
5002
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5003
-                && (
5004
-                    is_int($base_class_obj_or_id)
5005
-                    || is_string($base_class_obj_or_id)
5006
-                )
5007
-            ) {
5008
-                // assume it's an ID.
5009
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5010
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5011
-            } else if (
5012
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5013
-                && is_string($base_class_obj_or_id)
5014
-            ) {
5015
-                // assume its a string representation of the object
5016
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5017
-            } else {
5018
-                throw new EE_Error(
5019
-                    sprintf(
5020
-                        __(
5021
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5022
-                            'event_espresso'
5023
-                        ),
5024
-                        $base_class_obj_or_id,
5025
-                        $this->_get_class_name(),
5026
-                        print_r($base_class_obj_or_id, true)
5027
-                    )
5028
-                );
5029
-            }
5030
-        }
5031
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5032
-            $model_object->save();
5033
-        }
5034
-        return $model_object;
5035
-    }
5036
-
5037
-
5038
-
5039
-    /**
5040
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5041
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5042
-     * returns it ID.
5043
-     *
5044
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5045
-     * @return int|string depending on the type of this model object's ID
5046
-     * @throws EE_Error
5047
-     */
5048
-    public function ensure_is_ID($base_class_obj_or_id)
5049
-    {
5050
-        $className = $this->_get_class_name();
5051
-        if ($base_class_obj_or_id instanceof $className) {
5052
-            /** @var $base_class_obj_or_id EE_Base_Class */
5053
-            $id = $base_class_obj_or_id->ID();
5054
-        } elseif (is_int($base_class_obj_or_id)) {
5055
-            //assume it's an ID
5056
-            $id = $base_class_obj_or_id;
5057
-        } elseif (is_string($base_class_obj_or_id)) {
5058
-            //assume its a string representation of the object
5059
-            $id = $base_class_obj_or_id;
5060
-        } else {
5061
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5062
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5063
-                print_r($base_class_obj_or_id, true)));
5064
-        }
5065
-        return $id;
5066
-    }
5067
-
5068
-
5069
-
5070
-    /**
5071
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5072
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5073
-     * been sanitized and converted into the appropriate domain.
5074
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5075
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5076
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5077
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5078
-     * $EVT = EEM_Event::instance(); $old_setting =
5079
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5080
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5081
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5082
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5083
-     *
5084
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5085
-     * @return void
5086
-     */
5087
-    public function assume_values_already_prepared_by_model_object(
5088
-        $values_already_prepared = self::not_prepared_by_model_object
5089
-    ) {
5090
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5091
-    }
5092
-
5093
-
5094
-
5095
-    /**
5096
-     * Read comments for assume_values_already_prepared_by_model_object()
5097
-     *
5098
-     * @return int
5099
-     */
5100
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5101
-    {
5102
-        return $this->_values_already_prepared_by_model_object;
5103
-    }
5104
-
5105
-
5106
-
5107
-    /**
5108
-     * Gets all the indexes on this model
5109
-     *
5110
-     * @return EE_Index[]
5111
-     */
5112
-    public function indexes()
5113
-    {
5114
-        return $this->_indexes;
5115
-    }
5116
-
5117
-
5118
-
5119
-    /**
5120
-     * Gets all the Unique Indexes on this model
5121
-     *
5122
-     * @return EE_Unique_Index[]
5123
-     */
5124
-    public function unique_indexes()
5125
-    {
5126
-        $unique_indexes = array();
5127
-        foreach ($this->_indexes as $name => $index) {
5128
-            if ($index instanceof EE_Unique_Index) {
5129
-                $unique_indexes [$name] = $index;
5130
-            }
5131
-        }
5132
-        return $unique_indexes;
5133
-    }
5134
-
5135
-
5136
-
5137
-    /**
5138
-     * Gets all the fields which, when combined, make the primary key.
5139
-     * This is usually just an array with 1 element (the primary key), but in cases
5140
-     * where there is no primary key, it's a combination of fields as defined
5141
-     * on a primary index
5142
-     *
5143
-     * @return EE_Model_Field_Base[] indexed by the field's name
5144
-     * @throws \EE_Error
5145
-     */
5146
-    public function get_combined_primary_key_fields()
5147
-    {
5148
-        foreach ($this->indexes() as $index) {
5149
-            if ($index instanceof EE_Primary_Key_Index) {
5150
-                return $index->fields();
5151
-            }
5152
-        }
5153
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5154
-    }
5155
-
5156
-
5157
-
5158
-    /**
5159
-     * Used to build a primary key string (when the model has no primary key),
5160
-     * which can be used a unique string to identify this model object.
5161
-     *
5162
-     * @param array $cols_n_values keys are field names, values are their values
5163
-     * @return string
5164
-     * @throws \EE_Error
5165
-     */
5166
-    public function get_index_primary_key_string($cols_n_values)
5167
-    {
5168
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5169
-            $this->get_combined_primary_key_fields());
5170
-        return http_build_query($cols_n_values_for_primary_key_index);
5171
-    }
5172
-
5173
-
5174
-
5175
-    /**
5176
-     * Gets the field values from the primary key string
5177
-     *
5178
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5179
-     * @param string $index_primary_key_string
5180
-     * @return null|array
5181
-     * @throws \EE_Error
5182
-     */
5183
-    public function parse_index_primary_key_string($index_primary_key_string)
5184
-    {
5185
-        $key_fields = $this->get_combined_primary_key_fields();
5186
-        //check all of them are in the $id
5187
-        $key_vals_in_combined_pk = array();
5188
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5189
-        foreach ($key_fields as $key_field_name => $field_obj) {
5190
-            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5191
-                return null;
5192
-            }
5193
-        }
5194
-        return $key_vals_in_combined_pk;
5195
-    }
5196
-
5197
-
5198
-
5199
-    /**
5200
-     * verifies that an array of key-value pairs for model fields has a key
5201
-     * for each field comprising the primary key index
5202
-     *
5203
-     * @param array $key_vals
5204
-     * @return boolean
5205
-     * @throws \EE_Error
5206
-     */
5207
-    public function has_all_combined_primary_key_fields($key_vals)
5208
-    {
5209
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5210
-        foreach ($keys_it_should_have as $key) {
5211
-            if ( ! isset($key_vals[$key])) {
5212
-                return false;
5213
-            }
5214
-        }
5215
-        return true;
5216
-    }
5217
-
5218
-
5219
-
5220
-    /**
5221
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5222
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5223
-     *
5224
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5225
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5226
-     * @throws EE_Error
5227
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5228
-     *                                                              indexed)
5229
-     */
5230
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5231
-    {
5232
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5233
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5234
-        } elseif (is_array($model_object_or_attributes_array)) {
5235
-            $attributes_array = $model_object_or_attributes_array;
5236
-        } else {
5237
-            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",
5238
-                "event_espresso"), $model_object_or_attributes_array));
5239
-        }
5240
-        //even copies obviously won't have the same ID, so remove the primary key
5241
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5242
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5243
-            unset($attributes_array[$this->primary_key_name()]);
5244
-        }
5245
-        if (isset($query_params[0])) {
5246
-            $query_params[0] = array_merge($attributes_array, $query_params);
5247
-        } else {
5248
-            $query_params[0] = $attributes_array;
5249
-        }
5250
-        return $this->get_all($query_params);
5251
-    }
5252
-
5253
-
5254
-
5255
-    /**
5256
-     * Gets the first copy we find. See get_all_copies for more details
5257
-     *
5258
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5259
-     * @param array $query_params
5260
-     * @return EE_Base_Class
5261
-     * @throws \EE_Error
5262
-     */
5263
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5264
-    {
5265
-        if ( ! is_array($query_params)) {
5266
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5267
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5268
-                    gettype($query_params)), '4.6.0');
5269
-            $query_params = array();
5270
-        }
5271
-        $query_params['limit'] = 1;
5272
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5273
-        if (is_array($copies)) {
5274
-            return array_shift($copies);
5275
-        } else {
5276
-            return null;
5277
-        }
5278
-    }
5279
-
5280
-
5281
-
5282
-    /**
5283
-     * Updates the item with the specified id. Ignores default query parameters because
5284
-     * we have specified the ID, and its assumed we KNOW what we're doing
5285
-     *
5286
-     * @param array      $fields_n_values keys are field names, values are their new values
5287
-     * @param int|string $id              the value of the primary key to update
5288
-     * @return int number of rows updated
5289
-     * @throws \EE_Error
5290
-     */
5291
-    public function update_by_ID($fields_n_values, $id)
5292
-    {
5293
-        $query_params = array(
5294
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5295
-            'default_where_conditions' => 'other_models_only',
5296
-        );
5297
-        return $this->update($fields_n_values, $query_params);
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * Changes an operator which was supplied to the models into one usable in SQL
5304
-     *
5305
-     * @param string $operator_supplied
5306
-     * @return string an operator which can be used in SQL
5307
-     * @throws EE_Error
5308
-     */
5309
-    private function _prepare_operator_for_sql($operator_supplied)
5310
-    {
5311
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5312
-            : null;
5313
-        if ($sql_operator) {
5314
-            return $sql_operator;
5315
-        } else {
5316
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5317
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5318
-        }
5319
-    }
5320
-
5321
-
5322
-
5323
-    /**
5324
-     * Gets an array where keys are the primary keys and values are their 'names'
5325
-     * (as determined by the model object's name() function, which is often overridden)
5326
-     *
5327
-     * @param array $query_params like get_all's
5328
-     * @return string[]
5329
-     * @throws \EE_Error
5330
-     */
5331
-    public function get_all_names($query_params = array())
5332
-    {
5333
-        $objs = $this->get_all($query_params);
5334
-        $names = array();
5335
-        foreach ($objs as $obj) {
5336
-            $names[$obj->ID()] = $obj->name();
5337
-        }
5338
-        return $names;
5339
-    }
5340
-
5341
-
5342
-
5343
-    /**
5344
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5345
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5346
-     * this is duplicated effort and reduces efficiency) you would be better to use
5347
-     * array_keys() on $model_objects.
5348
-     *
5349
-     * @param \EE_Base_Class[] $model_objects
5350
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5351
-     *                                               in the returned array
5352
-     * @return array
5353
-     * @throws \EE_Error
5354
-     */
5355
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5356
-    {
5357
-        if ( ! $this->has_primary_key_field()) {
5358
-            if (WP_DEBUG) {
5359
-                EE_Error::add_error(
5360
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5361
-                    __FILE__,
5362
-                    __FUNCTION__,
5363
-                    __LINE__
5364
-                );
5365
-            }
5366
-        }
5367
-        $IDs = array();
5368
-        foreach ($model_objects as $model_object) {
5369
-            $id = $model_object->ID();
5370
-            if ( ! $id) {
5371
-                if ($filter_out_empty_ids) {
5372
-                    continue;
5373
-                }
5374
-                if (WP_DEBUG) {
5375
-                    EE_Error::add_error(
5376
-                        __(
5377
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5378
-                            'event_espresso'
5379
-                        ),
5380
-                        __FILE__,
5381
-                        __FUNCTION__,
5382
-                        __LINE__
5383
-                    );
5384
-                }
5385
-            }
5386
-            $IDs[] = $id;
5387
-        }
5388
-        return $IDs;
5389
-    }
5390
-
5391
-
5392
-
5393
-    /**
5394
-     * Returns the string used in capabilities relating to this model. If there
5395
-     * are no capabilities that relate to this model returns false
5396
-     *
5397
-     * @return string|false
5398
-     */
5399
-    public function cap_slug()
5400
-    {
5401
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5402
-    }
5403
-
5404
-
5405
-
5406
-    /**
5407
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5408
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5409
-     * only returns the cap restrictions array in that context (ie, the array
5410
-     * at that key)
5411
-     *
5412
-     * @param string $context
5413
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5414
-     * @throws \EE_Error
5415
-     */
5416
-    public function cap_restrictions($context = EEM_Base::caps_read)
5417
-    {
5418
-        EEM_Base::verify_is_valid_cap_context($context);
5419
-        //check if we ought to run the restriction generator first
5420
-        if (
5421
-            isset($this->_cap_restriction_generators[$context])
5422
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5423
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5424
-        ) {
5425
-            $this->_cap_restrictions[$context] = array_merge(
5426
-                $this->_cap_restrictions[$context],
5427
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5428
-            );
5429
-        }
5430
-        //and make sure we've finalized the construction of each restriction
5431
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5432
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5433
-                $where_conditions_obj->_finalize_construct($this);
5434
-            }
5435
-        }
5436
-        return $this->_cap_restrictions[$context];
5437
-    }
5438
-
5439
-
5440
-
5441
-    /**
5442
-     * Indicating whether or not this model thinks its a wp core model
5443
-     *
5444
-     * @return boolean
5445
-     */
5446
-    public function is_wp_core_model()
5447
-    {
5448
-        return $this->_wp_core_model;
5449
-    }
5450
-
5451
-
5452
-
5453
-    /**
5454
-     * Gets all the caps that are missing which impose a restriction on
5455
-     * queries made in this context
5456
-     *
5457
-     * @param string $context one of EEM_Base::caps_ constants
5458
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5459
-     * @throws \EE_Error
5460
-     */
5461
-    public function caps_missing($context = EEM_Base::caps_read)
5462
-    {
5463
-        $missing_caps = array();
5464
-        $cap_restrictions = $this->cap_restrictions($context);
5465
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5466
-            if ( ! EE_Capabilities::instance()
5467
-                                  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5468
-            ) {
5469
-                $missing_caps[$cap] = $restriction_if_no_cap;
5470
-            }
5471
-        }
5472
-        return $missing_caps;
5473
-    }
5474
-
5475
-
5476
-
5477
-    /**
5478
-     * Gets the mapping from capability contexts to action strings used in capability names
5479
-     *
5480
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5481
-     * one of 'read', 'edit', or 'delete'
5482
-     */
5483
-    public function cap_contexts_to_cap_action_map()
5484
-    {
5485
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5486
-            $this);
5487
-    }
5488
-
5489
-
5490
-
5491
-    /**
5492
-     * Gets the action string for the specified capability context
5493
-     *
5494
-     * @param string $context
5495
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5496
-     * @throws \EE_Error
5497
-     */
5498
-    public function cap_action_for_context($context)
5499
-    {
5500
-        $mapping = $this->cap_contexts_to_cap_action_map();
5501
-        if (isset($mapping[$context])) {
5502
-            return $mapping[$context];
5503
-        }
5504
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5505
-            return $action;
5506
-        }
5507
-        throw new EE_Error(
5508
-            sprintf(
5509
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5510
-                $context,
5511
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5512
-            )
5513
-        );
5514
-    }
5515
-
5516
-
5517
-
5518
-    /**
5519
-     * Returns all the capability contexts which are valid when querying models
5520
-     *
5521
-     * @return array
5522
-     */
5523
-    static public function valid_cap_contexts()
5524
-    {
5525
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5526
-            self::caps_read,
5527
-            self::caps_read_admin,
5528
-            self::caps_edit,
5529
-            self::caps_delete,
5530
-        ));
5531
-    }
5532
-
5533
-
5534
-
5535
-    /**
5536
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5537
-     *
5538
-     * @param string $context
5539
-     * @return bool
5540
-     * @throws \EE_Error
5541
-     */
5542
-    static public function verify_is_valid_cap_context($context)
5543
-    {
5544
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5545
-        if (in_array($context, $valid_cap_contexts)) {
5546
-            return true;
5547
-        } else {
5548
-            throw new EE_Error(
5549
-                sprintf(
5550
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5551
-                        'event_espresso'),
5552
-                    $context,
5553
-                    'EEM_Base',
5554
-                    implode(',', $valid_cap_contexts)
5555
-                )
5556
-            );
5557
-        }
5558
-    }
5559
-
5560
-
5561
-
5562
-    /**
5563
-     * Clears all the models field caches. This is only useful when a sub-class
5564
-     * might have added a field or something and these caches might be invalidated
5565
-     */
5566
-    protected function _invalidate_field_caches()
5567
-    {
5568
-        $this->_cache_foreign_key_to_fields = array();
5569
-        $this->_cached_fields = null;
5570
-        $this->_cached_fields_non_db_only = null;
5571
-    }
3448
+		}
3449
+		return $null_friendly_where_conditions;
3450
+	}
3451
+
3452
+
3453
+
3454
+	/**
3455
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3456
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3457
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3458
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3459
+	 *
3460
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3461
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3462
+	 */
3463
+	private function _get_default_where_conditions($model_relation_path = null)
3464
+	{
3465
+		if ($this->_ignore_where_strategy) {
3466
+			return array();
3467
+		}
3468
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3469
+	}
3470
+
3471
+
3472
+
3473
+	/**
3474
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3475
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3476
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3477
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3478
+	 * Similar to _get_default_where_conditions
3479
+	 *
3480
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3481
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3482
+	 */
3483
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3484
+	{
3485
+		if ($this->_ignore_where_strategy) {
3486
+			return array();
3487
+		}
3488
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3489
+	}
3490
+
3491
+
3492
+
3493
+	/**
3494
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3495
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3496
+	 *
3497
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3498
+	 * @return string
3499
+	 * @throws \EE_Error
3500
+	 */
3501
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3502
+	{
3503
+		$selects = $this->_get_columns_to_select_for_this_model();
3504
+		foreach (
3505
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3506
+			$name_of_other_model_included
3507
+		) {
3508
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3509
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3510
+			foreach ($other_model_selects as $key => $value) {
3511
+				$selects[] = $value;
3512
+			}
3513
+		}
3514
+		return implode(", ", $selects);
3515
+	}
3516
+
3517
+
3518
+
3519
+	/**
3520
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3521
+	 * So that's going to be the columns for all the fields on the model
3522
+	 *
3523
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3524
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3525
+	 */
3526
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3527
+	{
3528
+		$fields = $this->field_settings();
3529
+		$selects = array();
3530
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3531
+			$this->get_this_model_name());
3532
+		foreach ($fields as $field_obj) {
3533
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3534
+						 . $field_obj->get_table_alias()
3535
+						 . "."
3536
+						 . $field_obj->get_table_column()
3537
+						 . " AS '"
3538
+						 . $table_alias_with_model_relation_chain_prefix
3539
+						 . $field_obj->get_table_alias()
3540
+						 . "."
3541
+						 . $field_obj->get_table_column()
3542
+						 . "'";
3543
+		}
3544
+		//make sure we are also getting the PKs of each table
3545
+		$tables = $this->get_tables();
3546
+		if (count($tables) > 1) {
3547
+			foreach ($tables as $table_obj) {
3548
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3549
+									   . $table_obj->get_fully_qualified_pk_column();
3550
+				if ( ! in_array($qualified_pk_column, $selects)) {
3551
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3552
+				}
3553
+			}
3554
+		}
3555
+		return $selects;
3556
+	}
3557
+
3558
+
3559
+
3560
+	/**
3561
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3562
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3563
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3564
+	 * SQL for joining, and the data types
3565
+	 *
3566
+	 * @param null|string                 $original_query_param
3567
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3568
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3569
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3570
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3571
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3572
+	 *                                                          or 'Registration's
3573
+	 * @param string                      $original_query_param what it originally was (eg
3574
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3575
+	 *                                                          matches $query_param
3576
+	 * @throws EE_Error
3577
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3578
+	 */
3579
+	private function _extract_related_model_info_from_query_param(
3580
+		$query_param,
3581
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3582
+		$query_param_type,
3583
+		$original_query_param = null
3584
+	) {
3585
+		if ($original_query_param === null) {
3586
+			$original_query_param = $query_param;
3587
+		}
3588
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3589
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3590
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3591
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3592
+		//check to see if we have a field on this model
3593
+		$this_model_fields = $this->field_settings(true);
3594
+		if (array_key_exists($query_param, $this_model_fields)) {
3595
+			if ($allow_fields) {
3596
+				return;
3597
+			} else {
3598
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3599
+					"event_espresso"),
3600
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3601
+			}
3602
+		} //check if this is a special logic query param
3603
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3604
+			if ($allow_logic_query_params) {
3605
+				return;
3606
+			} else {
3607
+				throw new EE_Error(
3608
+					sprintf(
3609
+						__('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',
3610
+							'event_espresso'),
3611
+						implode('", "', $this->_logic_query_param_keys),
3612
+						$query_param,
3613
+						get_class($this),
3614
+						'<br />',
3615
+						"\t"
3616
+						. ' $passed_in_query_info = <pre>'
3617
+						. print_r($passed_in_query_info, true)
3618
+						. '</pre>'
3619
+						. "\n\t"
3620
+						. ' $query_param_type = '
3621
+						. $query_param_type
3622
+						. "\n\t"
3623
+						. ' $original_query_param = '
3624
+						. $original_query_param
3625
+					)
3626
+				);
3627
+			}
3628
+		} //check if it's a custom selection
3629
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3630
+			return;
3631
+		}
3632
+		//check if has a model name at the beginning
3633
+		//and
3634
+		//check if it's a field on a related model
3635
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3636
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3637
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3638
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3639
+				if ($query_param === '') {
3640
+					//nothing left to $query_param
3641
+					//we should actually end in a field name, not a model like this!
3642
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3643
+						"event_espresso"),
3644
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3645
+				} else {
3646
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3647
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3648
+						$passed_in_query_info, $query_param_type, $original_query_param);
3649
+					return;
3650
+				}
3651
+			} elseif ($query_param === $valid_related_model_name) {
3652
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3653
+				return;
3654
+			}
3655
+		}
3656
+		//ok so $query_param didn't start with a model name
3657
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3658
+		//it's wack, that's what it is
3659
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3660
+			"event_espresso"),
3661
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3662
+	}
3663
+
3664
+
3665
+
3666
+	/**
3667
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3668
+	 * and store it on $passed_in_query_info
3669
+	 *
3670
+	 * @param string                      $model_name
3671
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3672
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3673
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3674
+	 *                                                          and are adding a join to 'Payment' with the original
3675
+	 *                                                          query param key
3676
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3677
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3678
+	 *                                                          Payment wants to add default query params so that it
3679
+	 *                                                          will know what models to prepend onto its default query
3680
+	 *                                                          params or in case it wants to rename tables (in case
3681
+	 *                                                          there are multiple joins to the same table)
3682
+	 * @return void
3683
+	 * @throws \EE_Error
3684
+	 */
3685
+	private function _add_join_to_model(
3686
+		$model_name,
3687
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3688
+		$original_query_param
3689
+	) {
3690
+		$relation_obj = $this->related_settings_for($model_name);
3691
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3692
+		//check if the relation is HABTM, because then we're essentially doing two joins
3693
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3694
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3695
+			$join_model_obj = $relation_obj->get_join_model();
3696
+			//replace the model specified with the join model for this relation chain, whi
3697
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3698
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3699
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3700
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3701
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3702
+			$passed_in_query_info->merge($new_query_info);
3703
+		}
3704
+		//now just join to the other table pointed to by the relation object, and add its data types
3705
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3706
+			array($model_relation_chain => $model_name),
3707
+			$relation_obj->get_join_statement($model_relation_chain));
3708
+		$passed_in_query_info->merge($new_query_info);
3709
+	}
3710
+
3711
+
3712
+
3713
+	/**
3714
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3715
+	 *
3716
+	 * @param array $where_params like EEM_Base::get_all
3717
+	 * @return string of SQL
3718
+	 * @throws \EE_Error
3719
+	 */
3720
+	private function _construct_where_clause($where_params)
3721
+	{
3722
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3723
+		if ($SQL) {
3724
+			return " WHERE " . $SQL;
3725
+		} else {
3726
+			return '';
3727
+		}
3728
+	}
3729
+
3730
+
3731
+
3732
+	/**
3733
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3734
+	 * and should be passed HAVING parameters, not WHERE parameters
3735
+	 *
3736
+	 * @param array $having_params
3737
+	 * @return string
3738
+	 * @throws \EE_Error
3739
+	 */
3740
+	private function _construct_having_clause($having_params)
3741
+	{
3742
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3743
+		if ($SQL) {
3744
+			return " HAVING " . $SQL;
3745
+		} else {
3746
+			return '';
3747
+		}
3748
+	}
3749
+
3750
+
3751
+
3752
+	/**
3753
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3754
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3755
+	 * EEM_Attendee.
3756
+	 *
3757
+	 * @param string $field_name
3758
+	 * @param string $model_name
3759
+	 * @return EE_Model_Field_Base
3760
+	 * @throws EE_Error
3761
+	 */
3762
+	protected function _get_field_on_model($field_name, $model_name)
3763
+	{
3764
+		$model_class = 'EEM_' . $model_name;
3765
+		$model_filepath = $model_class . ".model.php";
3766
+		if (is_readable($model_filepath)) {
3767
+			require_once($model_filepath);
3768
+			$model_instance = call_user_func($model_name . "::instance");
3769
+			/* @var $model_instance EEM_Base */
3770
+			return $model_instance->field_settings_for($field_name);
3771
+		} else {
3772
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3773
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3774
+		}
3775
+	}
3776
+
3777
+
3778
+
3779
+	/**
3780
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3781
+	 * Event_Meta.meta_value = 'foo'))"
3782
+	 *
3783
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3784
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3785
+	 * @throws EE_Error
3786
+	 * @return string of SQL
3787
+	 */
3788
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3789
+	{
3790
+		$where_clauses = array();
3791
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3792
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3793
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3794
+				switch ($query_param) {
3795
+					case 'not':
3796
+					case 'NOT':
3797
+						$where_clauses[] = "! ("
3798
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3799
+								$glue)
3800
+										   . ")";
3801
+						break;
3802
+					case 'and':
3803
+					case 'AND':
3804
+						$where_clauses[] = " ("
3805
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3806
+								' AND ')
3807
+										   . ")";
3808
+						break;
3809
+					case 'or':
3810
+					case 'OR':
3811
+						$where_clauses[] = " ("
3812
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3813
+								' OR ')
3814
+										   . ")";
3815
+						break;
3816
+				}
3817
+			} else {
3818
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3819
+				//if it's not a normal field, maybe it's a custom selection?
3820
+				if ( ! $field_obj) {
3821
+					if (isset($this->_custom_selections[$query_param][1])) {
3822
+						$field_obj = $this->_custom_selections[$query_param][1];
3823
+					} else {
3824
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3825
+							"event_espresso"), $query_param));
3826
+					}
3827
+				}
3828
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3829
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3830
+			}
3831
+		}
3832
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3833
+	}
3834
+
3835
+
3836
+
3837
+	/**
3838
+	 * Takes the input parameter and extract the table name (alias) and column name
3839
+	 *
3840
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3841
+	 * @throws EE_Error
3842
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3843
+	 */
3844
+	private function _deduce_column_name_from_query_param($query_param)
3845
+	{
3846
+		$field = $this->_deduce_field_from_query_param($query_param);
3847
+		if ($field) {
3848
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3849
+				$query_param);
3850
+			return $table_alias_prefix . $field->get_qualified_column();
3851
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
3852
+			//maybe it's custom selection item?
3853
+			//if so, just use it as the "column name"
3854
+			return $query_param;
3855
+		} else {
3856
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3857
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3858
+		}
3859
+	}
3860
+
3861
+
3862
+
3863
+	/**
3864
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3865
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3866
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3867
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3868
+	 *
3869
+	 * @param string $condition_query_param_key
3870
+	 * @return string
3871
+	 */
3872
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3873
+	{
3874
+		$pos_of_star = strpos($condition_query_param_key, '*');
3875
+		if ($pos_of_star === false) {
3876
+			return $condition_query_param_key;
3877
+		} else {
3878
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3879
+			return $condition_query_param_sans_star;
3880
+		}
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3887
+	 *
3888
+	 * @param                            mixed      array | string    $op_and_value
3889
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3890
+	 * @throws EE_Error
3891
+	 * @return string
3892
+	 */
3893
+	private function _construct_op_and_value($op_and_value, $field_obj)
3894
+	{
3895
+		if (is_array($op_and_value)) {
3896
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3897
+			if ( ! $operator) {
3898
+				$php_array_like_string = array();
3899
+				foreach ($op_and_value as $key => $value) {
3900
+					$php_array_like_string[] = "$key=>$value";
3901
+				}
3902
+				throw new EE_Error(
3903
+					sprintf(
3904
+						__(
3905
+							"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))",
3906
+							"event_espresso"
3907
+						),
3908
+						implode(",", $php_array_like_string)
3909
+					)
3910
+				);
3911
+			}
3912
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3913
+		} else {
3914
+			$operator = '=';
3915
+			$value = $op_and_value;
3916
+		}
3917
+		//check to see if the value is actually another field
3918
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3919
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3920
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3921
+			//in this case, the value should be an array, or at least a comma-separated list
3922
+			//it will need to handle a little differently
3923
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
3924
+			//note: $cleaned_value has already been run through $wpdb->prepare()
3925
+			return $operator . SP . $cleaned_value;
3926
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3927
+			//the value should be an array with count of two.
3928
+			if (count($value) !== 2) {
3929
+				throw new EE_Error(
3930
+					sprintf(
3931
+						__(
3932
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3933
+							'event_espresso'
3934
+						),
3935
+						"BETWEEN"
3936
+					)
3937
+				);
3938
+			}
3939
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
3940
+			return $operator . SP . $cleaned_value;
3941
+		} elseif (in_array($operator, $this->_null_style_operators)) {
3942
+			if ($value !== null) {
3943
+				throw new EE_Error(
3944
+					sprintf(
3945
+						__(
3946
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3947
+							"event_espresso"
3948
+						),
3949
+						$value,
3950
+						$operator
3951
+					)
3952
+				);
3953
+			}
3954
+			return $operator;
3955
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
3956
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
3957
+			//remove other junk. So just treat it as a string.
3958
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3959
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3960
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3961
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3962
+			throw new EE_Error(
3963
+				sprintf(
3964
+					__(
3965
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3966
+						'event_espresso'
3967
+					),
3968
+					$operator,
3969
+					$operator
3970
+				)
3971
+			);
3972
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
3973
+			throw new EE_Error(
3974
+				sprintf(
3975
+					__(
3976
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3977
+						'event_espresso'
3978
+					),
3979
+					$operator,
3980
+					$operator
3981
+				)
3982
+			);
3983
+		} else {
3984
+			throw new EE_Error(
3985
+				sprintf(
3986
+					__(
3987
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3988
+						"event_espresso"
3989
+					),
3990
+					http_build_query($op_and_value)
3991
+				)
3992
+			);
3993
+		}
3994
+	}
3995
+
3996
+
3997
+
3998
+	/**
3999
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4000
+	 *
4001
+	 * @param array                      $values
4002
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4003
+	 *                                              '%s'
4004
+	 * @return string
4005
+	 * @throws \EE_Error
4006
+	 */
4007
+	public function _construct_between_value($values, $field_obj)
4008
+	{
4009
+		$cleaned_values = array();
4010
+		foreach ($values as $value) {
4011
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4012
+		}
4013
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4014
+	}
4015
+
4016
+
4017
+
4018
+	/**
4019
+	 * Takes an array or a comma-separated list of $values and cleans them
4020
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4021
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4022
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4023
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4024
+	 *
4025
+	 * @param mixed                      $values    array or comma-separated string
4026
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4027
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4028
+	 * @throws \EE_Error
4029
+	 */
4030
+	public function _construct_in_value($values, $field_obj)
4031
+	{
4032
+		//check if the value is a CSV list
4033
+		if (is_string($values)) {
4034
+			//in which case, turn it into an array
4035
+			$values = explode(",", $values);
4036
+		}
4037
+		$cleaned_values = array();
4038
+		foreach ($values as $value) {
4039
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4040
+		}
4041
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4042
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4043
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4044
+		if (empty($cleaned_values)) {
4045
+			$all_fields = $this->field_settings();
4046
+			$a_field = array_shift($all_fields);
4047
+			$main_table = $this->_get_main_table();
4048
+			$cleaned_values[] = "SELECT "
4049
+								. $a_field->get_table_column()
4050
+								. " FROM "
4051
+								. $main_table->get_table_name()
4052
+								. " WHERE FALSE";
4053
+		}
4054
+		return "(" . implode(",", $cleaned_values) . ")";
4055
+	}
4056
+
4057
+
4058
+
4059
+	/**
4060
+	 * @param mixed                      $value
4061
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4062
+	 * @throws EE_Error
4063
+	 * @return false|null|string
4064
+	 */
4065
+	private function _wpdb_prepare_using_field($value, $field_obj)
4066
+	{
4067
+		/** @type WPDB $wpdb */
4068
+		global $wpdb;
4069
+		if ($field_obj instanceof EE_Model_Field_Base) {
4070
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4071
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4072
+		} else {//$field_obj should really just be a data type
4073
+			if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4074
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4075
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4076
+			}
4077
+			return $wpdb->prepare($field_obj, $value);
4078
+		}
4079
+	}
4080
+
4081
+
4082
+
4083
+	/**
4084
+	 * Takes the input parameter and finds the model field that it indicates.
4085
+	 *
4086
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4087
+	 * @throws EE_Error
4088
+	 * @return EE_Model_Field_Base
4089
+	 */
4090
+	protected function _deduce_field_from_query_param($query_param_name)
4091
+	{
4092
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4093
+		//which will help us find the database table and column
4094
+		$query_param_parts = explode(".", $query_param_name);
4095
+		if (empty($query_param_parts)) {
4096
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4097
+				'event_espresso'), $query_param_name));
4098
+		}
4099
+		$number_of_parts = count($query_param_parts);
4100
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4101
+		if ($number_of_parts === 1) {
4102
+			$field_name = $last_query_param_part;
4103
+			$model_obj = $this;
4104
+		} else {// $number_of_parts >= 2
4105
+			//the last part is the column name, and there are only 2parts. therefore...
4106
+			$field_name = $last_query_param_part;
4107
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4108
+		}
4109
+		try {
4110
+			return $model_obj->field_settings_for($field_name);
4111
+		} catch (EE_Error $e) {
4112
+			return null;
4113
+		}
4114
+	}
4115
+
4116
+
4117
+
4118
+	/**
4119
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4120
+	 * alias and column which corresponds to it
4121
+	 *
4122
+	 * @param string $field_name
4123
+	 * @throws EE_Error
4124
+	 * @return string
4125
+	 */
4126
+	public function _get_qualified_column_for_field($field_name)
4127
+	{
4128
+		$all_fields = $this->field_settings();
4129
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4130
+		if ($field) {
4131
+			return $field->get_qualified_column();
4132
+		} else {
4133
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4134
+				'event_espresso'), $field_name, get_class($this)));
4135
+		}
4136
+	}
4137
+
4138
+
4139
+
4140
+	/**
4141
+	 * constructs the select use on special limit joins
4142
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4143
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4144
+	 * (as that is typically where the limits would be set).
4145
+	 *
4146
+	 * @param  string       $table_alias The table the select is being built for
4147
+	 * @param  mixed|string $limit       The limit for this select
4148
+	 * @return string                The final select join element for the query.
4149
+	 */
4150
+	public function _construct_limit_join_select($table_alias, $limit)
4151
+	{
4152
+		$SQL = '';
4153
+		foreach ($this->_tables as $table_obj) {
4154
+			if ($table_obj instanceof EE_Primary_Table) {
4155
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4156
+					? $table_obj->get_select_join_limit($limit)
4157
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4158
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4159
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4160
+					? $table_obj->get_select_join_limit_join($limit)
4161
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4162
+			}
4163
+		}
4164
+		return $SQL;
4165
+	}
4166
+
4167
+
4168
+
4169
+	/**
4170
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4171
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4172
+	 *
4173
+	 * @return string SQL
4174
+	 * @throws \EE_Error
4175
+	 */
4176
+	public function _construct_internal_join()
4177
+	{
4178
+		$SQL = $this->_get_main_table()->get_table_sql();
4179
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4180
+		return $SQL;
4181
+	}
4182
+
4183
+
4184
+
4185
+	/**
4186
+	 * Constructs the SQL for joining all the tables on this model.
4187
+	 * Normally $alias should be the primary table's alias, but in cases where
4188
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4189
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4190
+	 * alias, this will construct SQL like:
4191
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4192
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4193
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4194
+	 *
4195
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4196
+	 * @return string
4197
+	 */
4198
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4199
+	{
4200
+		$SQL = '';
4201
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4202
+		foreach ($this->_tables as $table_obj) {
4203
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4204
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4205
+					//so we're joining to this table, meaning the table is already in
4206
+					//the FROM statement, BUT the primary table isn't. So we want
4207
+					//to add the inverse join sql
4208
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4209
+				} else {
4210
+					//just add a regular JOIN to this table from the primary table
4211
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4212
+				}
4213
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4214
+		}
4215
+		return $SQL;
4216
+	}
4217
+
4218
+
4219
+
4220
+	/**
4221
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4222
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4223
+	 * their data type (eg, '%s', '%d', etc)
4224
+	 *
4225
+	 * @return array
4226
+	 */
4227
+	public function _get_data_types()
4228
+	{
4229
+		$data_types = array();
4230
+		foreach ($this->field_settings() as $field_obj) {
4231
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4232
+			/** @var $field_obj EE_Model_Field_Base */
4233
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4234
+		}
4235
+		return $data_types;
4236
+	}
4237
+
4238
+
4239
+
4240
+	/**
4241
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4242
+	 *
4243
+	 * @param string $model_name
4244
+	 * @throws EE_Error
4245
+	 * @return EEM_Base
4246
+	 */
4247
+	public function get_related_model_obj($model_name)
4248
+	{
4249
+		$model_classname = "EEM_" . $model_name;
4250
+		if ( ! class_exists($model_classname)) {
4251
+			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",
4252
+				'event_espresso'), $model_name, $model_classname));
4253
+		}
4254
+		return call_user_func($model_classname . "::instance");
4255
+	}
4256
+
4257
+
4258
+
4259
+	/**
4260
+	 * Returns the array of EE_ModelRelations for this model.
4261
+	 *
4262
+	 * @return EE_Model_Relation_Base[]
4263
+	 */
4264
+	public function relation_settings()
4265
+	{
4266
+		return $this->_model_relations;
4267
+	}
4268
+
4269
+
4270
+
4271
+	/**
4272
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4273
+	 * because without THOSE models, this model probably doesn't have much purpose.
4274
+	 * (Eg, without an event, datetimes have little purpose.)
4275
+	 *
4276
+	 * @return EE_Belongs_To_Relation[]
4277
+	 */
4278
+	public function belongs_to_relations()
4279
+	{
4280
+		$belongs_to_relations = array();
4281
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4282
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4283
+				$belongs_to_relations[$model_name] = $relation_obj;
4284
+			}
4285
+		}
4286
+		return $belongs_to_relations;
4287
+	}
4288
+
4289
+
4290
+
4291
+	/**
4292
+	 * Returns the specified EE_Model_Relation, or throws an exception
4293
+	 *
4294
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4295
+	 * @throws EE_Error
4296
+	 * @return EE_Model_Relation_Base
4297
+	 */
4298
+	public function related_settings_for($relation_name)
4299
+	{
4300
+		$relatedModels = $this->relation_settings();
4301
+		if ( ! array_key_exists($relation_name, $relatedModels)) {
4302
+			throw new EE_Error(
4303
+				sprintf(
4304
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4305
+						'event_espresso'),
4306
+					$relation_name,
4307
+					$this->_get_class_name(),
4308
+					implode(', ', array_keys($relatedModels))
4309
+				)
4310
+			);
4311
+		}
4312
+		return $relatedModels[$relation_name];
4313
+	}
4314
+
4315
+
4316
+
4317
+	/**
4318
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4319
+	 * fields
4320
+	 *
4321
+	 * @param string $fieldName
4322
+	 * @throws EE_Error
4323
+	 * @return EE_Model_Field_Base
4324
+	 */
4325
+	public function field_settings_for($fieldName)
4326
+	{
4327
+		$fieldSettings = $this->field_settings(true);
4328
+		if ( ! array_key_exists($fieldName, $fieldSettings)) {
4329
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4330
+				get_class($this)));
4331
+		}
4332
+		return $fieldSettings[$fieldName];
4333
+	}
4334
+
4335
+
4336
+
4337
+	/**
4338
+	 * Checks if this field exists on this model
4339
+	 *
4340
+	 * @param string $fieldName a key in the model's _field_settings array
4341
+	 * @return boolean
4342
+	 */
4343
+	public function has_field($fieldName)
4344
+	{
4345
+		$fieldSettings = $this->field_settings(true);
4346
+		if (isset($fieldSettings[$fieldName])) {
4347
+			return true;
4348
+		} else {
4349
+			return false;
4350
+		}
4351
+	}
4352
+
4353
+
4354
+
4355
+	/**
4356
+	 * Returns whether or not this model has a relation to the specified model
4357
+	 *
4358
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4359
+	 * @return boolean
4360
+	 */
4361
+	public function has_relation($relation_name)
4362
+	{
4363
+		$relations = $this->relation_settings();
4364
+		if (isset($relations[$relation_name])) {
4365
+			return true;
4366
+		} else {
4367
+			return false;
4368
+		}
4369
+	}
4370
+
4371
+
4372
+
4373
+	/**
4374
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4375
+	 * Eg, on EE_Answer that would be ANS_ID field object
4376
+	 *
4377
+	 * @param $field_obj
4378
+	 * @return boolean
4379
+	 */
4380
+	public function is_primary_key_field($field_obj)
4381
+	{
4382
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4383
+	}
4384
+
4385
+
4386
+
4387
+	/**
4388
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4389
+	 * Eg, on EE_Answer that would be ANS_ID field object
4390
+	 *
4391
+	 * @return EE_Model_Field_Base
4392
+	 * @throws EE_Error
4393
+	 */
4394
+	public function get_primary_key_field()
4395
+	{
4396
+		if ($this->_primary_key_field === null) {
4397
+			foreach ($this->field_settings(true) as $field_obj) {
4398
+				if ($this->is_primary_key_field($field_obj)) {
4399
+					$this->_primary_key_field = $field_obj;
4400
+					break;
4401
+				}
4402
+			}
4403
+			if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4404
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4405
+					get_class($this)));
4406
+			}
4407
+		}
4408
+		return $this->_primary_key_field;
4409
+	}
4410
+
4411
+
4412
+
4413
+	/**
4414
+	 * Returns whether or not not there is a primary key on this model.
4415
+	 * Internally does some caching.
4416
+	 *
4417
+	 * @return boolean
4418
+	 */
4419
+	public function has_primary_key_field()
4420
+	{
4421
+		if ($this->_has_primary_key_field === null) {
4422
+			try {
4423
+				$this->get_primary_key_field();
4424
+				$this->_has_primary_key_field = true;
4425
+			} catch (EE_Error $e) {
4426
+				$this->_has_primary_key_field = false;
4427
+			}
4428
+		}
4429
+		return $this->_has_primary_key_field;
4430
+	}
4431
+
4432
+
4433
+
4434
+	/**
4435
+	 * Finds the first field of type $field_class_name.
4436
+	 *
4437
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4438
+	 *                                 EE_Foreign_Key_Field, etc
4439
+	 * @return EE_Model_Field_Base or null if none is found
4440
+	 */
4441
+	public function get_a_field_of_type($field_class_name)
4442
+	{
4443
+		foreach ($this->field_settings() as $field) {
4444
+			if ($field instanceof $field_class_name) {
4445
+				return $field;
4446
+			}
4447
+		}
4448
+		return null;
4449
+	}
4450
+
4451
+
4452
+
4453
+	/**
4454
+	 * Gets a foreign key field pointing to model.
4455
+	 *
4456
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4457
+	 * @return EE_Foreign_Key_Field_Base
4458
+	 * @throws EE_Error
4459
+	 */
4460
+	public function get_foreign_key_to($model_name)
4461
+	{
4462
+		if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4463
+			foreach ($this->field_settings() as $field) {
4464
+				if (
4465
+					$field instanceof EE_Foreign_Key_Field_Base
4466
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4467
+				) {
4468
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4469
+					break;
4470
+				}
4471
+			}
4472
+			if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4473
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4474
+					'event_espresso'), $model_name, get_class($this)));
4475
+			}
4476
+		}
4477
+		return $this->_cache_foreign_key_to_fields[$model_name];
4478
+	}
4479
+
4480
+
4481
+
4482
+	/**
4483
+	 * Gets the actual table for the table alias
4484
+	 *
4485
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4486
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4487
+	 *                            Either one works
4488
+	 * @return EE_Table_Base
4489
+	 */
4490
+	public function get_table_for_alias($table_alias)
4491
+	{
4492
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4493
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4494
+	}
4495
+
4496
+
4497
+
4498
+	/**
4499
+	 * Returns a flat array of all field son this model, instead of organizing them
4500
+	 * by table_alias as they are in the constructor.
4501
+	 *
4502
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4503
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4504
+	 */
4505
+	public function field_settings($include_db_only_fields = false)
4506
+	{
4507
+		if ($include_db_only_fields) {
4508
+			if ($this->_cached_fields === null) {
4509
+				$this->_cached_fields = array();
4510
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4511
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4512
+						$this->_cached_fields[$field_name] = $field_obj;
4513
+					}
4514
+				}
4515
+			}
4516
+			return $this->_cached_fields;
4517
+		} else {
4518
+			if ($this->_cached_fields_non_db_only === null) {
4519
+				$this->_cached_fields_non_db_only = array();
4520
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4521
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4522
+						/** @var $field_obj EE_Model_Field_Base */
4523
+						if ( ! $field_obj->is_db_only_field()) {
4524
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4525
+						}
4526
+					}
4527
+				}
4528
+			}
4529
+			return $this->_cached_fields_non_db_only;
4530
+		}
4531
+	}
4532
+
4533
+
4534
+
4535
+	/**
4536
+	 *        cycle though array of attendees and create objects out of each item
4537
+	 *
4538
+	 * @access        private
4539
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4540
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4541
+	 *                           numerically indexed)
4542
+	 * @throws \EE_Error
4543
+	 */
4544
+	protected function _create_objects($rows = array())
4545
+	{
4546
+		$array_of_objects = array();
4547
+		if (empty($rows)) {
4548
+			return array();
4549
+		}
4550
+		$count_if_model_has_no_primary_key = 0;
4551
+		$has_primary_key = $this->has_primary_key_field();
4552
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4553
+		foreach ((array)$rows as $row) {
4554
+			if (empty($row)) {
4555
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4556
+				return array();
4557
+			}
4558
+			//check if we've already set this object in the results array,
4559
+			//in which case there's no need to process it further (again)
4560
+			if ($has_primary_key) {
4561
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4562
+					$row,
4563
+					$primary_key_field->get_qualified_column(),
4564
+					$primary_key_field->get_table_column()
4565
+				);
4566
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4567
+					continue;
4568
+				}
4569
+			}
4570
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4571
+			if ( ! $classInstance) {
4572
+				throw new EE_Error(
4573
+					sprintf(
4574
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4575
+						$this->get_this_model_name(),
4576
+						http_build_query($row)
4577
+					)
4578
+				);
4579
+			}
4580
+			//set the timezone on the instantiated objects
4581
+			$classInstance->set_timezone($this->_timezone);
4582
+			//make sure if there is any timezone setting present that we set the timezone for the object
4583
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4584
+			$array_of_objects[$key] = $classInstance;
4585
+			//also, for all the relations of type BelongsTo, see if we can cache
4586
+			//those related models
4587
+			//(we could do this for other relations too, but if there are conditions
4588
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4589
+			//so it requires a little more thought than just caching them immediately...)
4590
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4591
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4592
+					//check if this model's INFO is present. If so, cache it on the model
4593
+					$other_model = $relation_obj->get_other_model();
4594
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4595
+					//if we managed to make a model object from the results, cache it on the main model object
4596
+					if ($other_model_obj_maybe) {
4597
+						//set timezone on these other model objects if they are present
4598
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4599
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4600
+					}
4601
+				}
4602
+			}
4603
+		}
4604
+		return $array_of_objects;
4605
+	}
4606
+
4607
+
4608
+
4609
+	/**
4610
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4611
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4612
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4613
+	 * object (as set in the model_field!).
4614
+	 *
4615
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4616
+	 */
4617
+	public function create_default_object()
4618
+	{
4619
+		$this_model_fields_and_values = array();
4620
+		//setup the row using default values;
4621
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4622
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4623
+		}
4624
+		$className = $this->_get_class_name();
4625
+		$classInstance = EE_Registry::instance()
4626
+									->load_class($className, array($this_model_fields_and_values), false, false);
4627
+		return $classInstance;
4628
+	}
4629
+
4630
+
4631
+
4632
+	/**
4633
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4634
+	 *                             or an stdClass where each property is the name of a column,
4635
+	 * @return EE_Base_Class
4636
+	 * @throws \EE_Error
4637
+	 */
4638
+	public function instantiate_class_from_array_or_object($cols_n_values)
4639
+	{
4640
+		if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4641
+			$cols_n_values = get_object_vars($cols_n_values);
4642
+		}
4643
+		$primary_key = null;
4644
+		//make sure the array only has keys that are fields/columns on this model
4645
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4646
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4647
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4648
+		}
4649
+		$className = $this->_get_class_name();
4650
+		//check we actually found results that we can use to build our model object
4651
+		//if not, return null
4652
+		if ($this->has_primary_key_field()) {
4653
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4654
+				return null;
4655
+			}
4656
+		} else if ($this->unique_indexes()) {
4657
+			$first_column = reset($this_model_fields_n_values);
4658
+			if (empty($first_column)) {
4659
+				return null;
4660
+			}
4661
+		}
4662
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4663
+		if ($primary_key) {
4664
+			$classInstance = $this->get_from_entity_map($primary_key);
4665
+			if ( ! $classInstance) {
4666
+				$classInstance = EE_Registry::instance()
4667
+											->load_class($className,
4668
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4669
+				// add this new object to the entity map
4670
+				$classInstance = $this->add_to_entity_map($classInstance);
4671
+			}
4672
+		} else {
4673
+			$classInstance = EE_Registry::instance()
4674
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4675
+											true, false);
4676
+		}
4677
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4678
+		$this->set_timezone($classInstance->get_timezone());
4679
+		return $classInstance;
4680
+	}
4681
+
4682
+
4683
+
4684
+	/**
4685
+	 * Gets the model object from the  entity map if it exists
4686
+	 *
4687
+	 * @param int|string $id the ID of the model object
4688
+	 * @return EE_Base_Class
4689
+	 */
4690
+	public function get_from_entity_map($id)
4691
+	{
4692
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4693
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4694
+	}
4695
+
4696
+
4697
+
4698
+	/**
4699
+	 * add_to_entity_map
4700
+	 * Adds the object to the model's entity mappings
4701
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4702
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4703
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4704
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4705
+	 *        then this method should be called immediately after the update query
4706
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4707
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4708
+	 *
4709
+	 * @param    EE_Base_Class $object
4710
+	 * @throws EE_Error
4711
+	 * @return \EE_Base_Class
4712
+	 */
4713
+	public function add_to_entity_map(EE_Base_Class $object)
4714
+	{
4715
+		$className = $this->_get_class_name();
4716
+		if ( ! $object instanceof $className) {
4717
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4718
+				is_object($object) ? get_class($object) : $object, $className));
4719
+		}
4720
+		/** @var $object EE_Base_Class */
4721
+		if ( ! $object->ID()) {
4722
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4723
+				"event_espresso"), get_class($this)));
4724
+		}
4725
+		// double check it's not already there
4726
+		$classInstance = $this->get_from_entity_map($object->ID());
4727
+		if ($classInstance) {
4728
+			return $classInstance;
4729
+		} else {
4730
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4731
+			return $object;
4732
+		}
4733
+	}
4734
+
4735
+
4736
+
4737
+	/**
4738
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4739
+	 * if no identifier is provided, then the entire entity map is emptied
4740
+	 *
4741
+	 * @param int|string $id the ID of the model object
4742
+	 * @return boolean
4743
+	 */
4744
+	public function clear_entity_map($id = null)
4745
+	{
4746
+		if (empty($id)) {
4747
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4748
+			return true;
4749
+		}
4750
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4751
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4752
+			return true;
4753
+		}
4754
+		return false;
4755
+	}
4756
+
4757
+
4758
+
4759
+	/**
4760
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4761
+	 * Given an array where keys are column (or column alias) names and values,
4762
+	 * returns an array of their corresponding field names and database values
4763
+	 *
4764
+	 * @param array $cols_n_values
4765
+	 * @return array
4766
+	 */
4767
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4768
+	{
4769
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4770
+	}
4771
+
4772
+
4773
+
4774
+	/**
4775
+	 * _deduce_fields_n_values_from_cols_n_values
4776
+	 * Given an array where keys are column (or column alias) names and values,
4777
+	 * returns an array of their corresponding field names and database values
4778
+	 *
4779
+	 * @param string $cols_n_values
4780
+	 * @return array
4781
+	 */
4782
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4783
+	{
4784
+		$this_model_fields_n_values = array();
4785
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
4786
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4787
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4788
+			//there is a primary key on this table and its not set. Use defaults for all its columns
4789
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
4790
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4791
+					if ( ! $field_obj->is_db_only_field()) {
4792
+						//prepare field as if its coming from db
4793
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4794
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4795
+					}
4796
+				}
4797
+			} else {
4798
+				//the table's rows existed. Use their values
4799
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4800
+					if ( ! $field_obj->is_db_only_field()) {
4801
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4802
+							$cols_n_values, $field_obj->get_qualified_column(),
4803
+							$field_obj->get_table_column()
4804
+						);
4805
+					}
4806
+				}
4807
+			}
4808
+		}
4809
+		return $this_model_fields_n_values;
4810
+	}
4811
+
4812
+
4813
+
4814
+	/**
4815
+	 * @param $cols_n_values
4816
+	 * @param $qualified_column
4817
+	 * @param $regular_column
4818
+	 * @return null
4819
+	 */
4820
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4821
+	{
4822
+		$value = null;
4823
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4824
+		//does the field on the model relate to this column retrieved from the db?
4825
+		//or is it a db-only field? (not relating to the model)
4826
+		if (isset($cols_n_values[$qualified_column])) {
4827
+			$value = $cols_n_values[$qualified_column];
4828
+		} elseif (isset($cols_n_values[$regular_column])) {
4829
+			$value = $cols_n_values[$regular_column];
4830
+		}
4831
+		return $value;
4832
+	}
4833
+
4834
+
4835
+
4836
+	/**
4837
+	 * refresh_entity_map_from_db
4838
+	 * Makes sure the model object in the entity map at $id assumes the values
4839
+	 * of the database (opposite of EE_base_Class::save())
4840
+	 *
4841
+	 * @param int|string $id
4842
+	 * @return EE_Base_Class
4843
+	 * @throws \EE_Error
4844
+	 */
4845
+	public function refresh_entity_map_from_db($id)
4846
+	{
4847
+		$obj_in_map = $this->get_from_entity_map($id);
4848
+		if ($obj_in_map) {
4849
+			$wpdb_results = $this->_get_all_wpdb_results(
4850
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4851
+			);
4852
+			if ($wpdb_results && is_array($wpdb_results)) {
4853
+				$one_row = reset($wpdb_results);
4854
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4855
+					$obj_in_map->set_from_db($field_name, $db_value);
4856
+				}
4857
+				//clear the cache of related model objects
4858
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4859
+					$obj_in_map->clear_cache($relation_name, null, true);
4860
+				}
4861
+			}
4862
+			return $obj_in_map;
4863
+		} else {
4864
+			return $this->get_one_by_ID($id);
4865
+		}
4866
+	}
4867
+
4868
+
4869
+
4870
+	/**
4871
+	 * refresh_entity_map_with
4872
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
4873
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4874
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4875
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4876
+	 *
4877
+	 * @param int|string    $id
4878
+	 * @param EE_Base_Class $replacing_model_obj
4879
+	 * @return \EE_Base_Class
4880
+	 * @throws \EE_Error
4881
+	 */
4882
+	public function refresh_entity_map_with($id, $replacing_model_obj)
4883
+	{
4884
+		$obj_in_map = $this->get_from_entity_map($id);
4885
+		if ($obj_in_map) {
4886
+			if ($replacing_model_obj instanceof EE_Base_Class) {
4887
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4888
+					$obj_in_map->set($field_name, $value);
4889
+				}
4890
+				//make the model object in the entity map's cache match the $replacing_model_obj
4891
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4892
+					$obj_in_map->clear_cache($relation_name, null, true);
4893
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4894
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4895
+					}
4896
+				}
4897
+			}
4898
+			return $obj_in_map;
4899
+		} else {
4900
+			$this->add_to_entity_map($replacing_model_obj);
4901
+			return $replacing_model_obj;
4902
+		}
4903
+	}
4904
+
4905
+
4906
+
4907
+	/**
4908
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4909
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4910
+	 * require_once($this->_getClassName().".class.php");
4911
+	 *
4912
+	 * @return string
4913
+	 */
4914
+	private function _get_class_name()
4915
+	{
4916
+		return "EE_" . $this->get_this_model_name();
4917
+	}
4918
+
4919
+
4920
+
4921
+	/**
4922
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
4923
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4924
+	 * it would be 'Events'.
4925
+	 *
4926
+	 * @param int $quantity
4927
+	 * @return string
4928
+	 */
4929
+	public function item_name($quantity = 1)
4930
+	{
4931
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4932
+	}
4933
+
4934
+
4935
+
4936
+	/**
4937
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
4938
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
4939
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
4940
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
4941
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
4942
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
4943
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
4944
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
4945
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
4946
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
4947
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
4948
+	 *        return $previousReturnValue.$returnString;
4949
+	 * }
4950
+	 * require('EEM_Answer.model.php');
4951
+	 * $answer=EEM_Answer::instance();
4952
+	 * echo $answer->my_callback('monkeys',100);
4953
+	 * //will output "you called my_callback! and passed args:monkeys,100"
4954
+	 *
4955
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
4956
+	 * @param array  $args       array of original arguments passed to the function
4957
+	 * @throws EE_Error
4958
+	 * @return mixed whatever the plugin which calls add_filter decides
4959
+	 */
4960
+	public function __call($methodName, $args)
4961
+	{
4962
+		$className = get_class($this);
4963
+		$tagName = "FHEE__{$className}__{$methodName}";
4964
+		if ( ! has_filter($tagName)) {
4965
+			throw new EE_Error(
4966
+				sprintf(
4967
+					__('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 );',
4968
+						'event_espresso'),
4969
+					$methodName,
4970
+					$className,
4971
+					$tagName,
4972
+					'<br />'
4973
+				)
4974
+			);
4975
+		}
4976
+		return apply_filters($tagName, null, $this, $args);
4977
+	}
4978
+
4979
+
4980
+
4981
+	/**
4982
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
4983
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
4984
+	 *
4985
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
4986
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
4987
+	 *                                                       the object's class name
4988
+	 *                                                       or object's ID
4989
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
4990
+	 *                                                       exists in the database. If it does not, we add it
4991
+	 * @throws EE_Error
4992
+	 * @return EE_Base_Class
4993
+	 */
4994
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
4995
+	{
4996
+		$className = $this->_get_class_name();
4997
+		if ($base_class_obj_or_id instanceof $className) {
4998
+			$model_object = $base_class_obj_or_id;
4999
+		} else {
5000
+			$primary_key_field = $this->get_primary_key_field();
5001
+			if (
5002
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5003
+				&& (
5004
+					is_int($base_class_obj_or_id)
5005
+					|| is_string($base_class_obj_or_id)
5006
+				)
5007
+			) {
5008
+				// assume it's an ID.
5009
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5010
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5011
+			} else if (
5012
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5013
+				&& is_string($base_class_obj_or_id)
5014
+			) {
5015
+				// assume its a string representation of the object
5016
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5017
+			} else {
5018
+				throw new EE_Error(
5019
+					sprintf(
5020
+						__(
5021
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5022
+							'event_espresso'
5023
+						),
5024
+						$base_class_obj_or_id,
5025
+						$this->_get_class_name(),
5026
+						print_r($base_class_obj_or_id, true)
5027
+					)
5028
+				);
5029
+			}
5030
+		}
5031
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5032
+			$model_object->save();
5033
+		}
5034
+		return $model_object;
5035
+	}
5036
+
5037
+
5038
+
5039
+	/**
5040
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5041
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5042
+	 * returns it ID.
5043
+	 *
5044
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5045
+	 * @return int|string depending on the type of this model object's ID
5046
+	 * @throws EE_Error
5047
+	 */
5048
+	public function ensure_is_ID($base_class_obj_or_id)
5049
+	{
5050
+		$className = $this->_get_class_name();
5051
+		if ($base_class_obj_or_id instanceof $className) {
5052
+			/** @var $base_class_obj_or_id EE_Base_Class */
5053
+			$id = $base_class_obj_or_id->ID();
5054
+		} elseif (is_int($base_class_obj_or_id)) {
5055
+			//assume it's an ID
5056
+			$id = $base_class_obj_or_id;
5057
+		} elseif (is_string($base_class_obj_or_id)) {
5058
+			//assume its a string representation of the object
5059
+			$id = $base_class_obj_or_id;
5060
+		} else {
5061
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5062
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5063
+				print_r($base_class_obj_or_id, true)));
5064
+		}
5065
+		return $id;
5066
+	}
5067
+
5068
+
5069
+
5070
+	/**
5071
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5072
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5073
+	 * been sanitized and converted into the appropriate domain.
5074
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5075
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5076
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5077
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5078
+	 * $EVT = EEM_Event::instance(); $old_setting =
5079
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5080
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5081
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5082
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5083
+	 *
5084
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5085
+	 * @return void
5086
+	 */
5087
+	public function assume_values_already_prepared_by_model_object(
5088
+		$values_already_prepared = self::not_prepared_by_model_object
5089
+	) {
5090
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5091
+	}
5092
+
5093
+
5094
+
5095
+	/**
5096
+	 * Read comments for assume_values_already_prepared_by_model_object()
5097
+	 *
5098
+	 * @return int
5099
+	 */
5100
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5101
+	{
5102
+		return $this->_values_already_prepared_by_model_object;
5103
+	}
5104
+
5105
+
5106
+
5107
+	/**
5108
+	 * Gets all the indexes on this model
5109
+	 *
5110
+	 * @return EE_Index[]
5111
+	 */
5112
+	public function indexes()
5113
+	{
5114
+		return $this->_indexes;
5115
+	}
5116
+
5117
+
5118
+
5119
+	/**
5120
+	 * Gets all the Unique Indexes on this model
5121
+	 *
5122
+	 * @return EE_Unique_Index[]
5123
+	 */
5124
+	public function unique_indexes()
5125
+	{
5126
+		$unique_indexes = array();
5127
+		foreach ($this->_indexes as $name => $index) {
5128
+			if ($index instanceof EE_Unique_Index) {
5129
+				$unique_indexes [$name] = $index;
5130
+			}
5131
+		}
5132
+		return $unique_indexes;
5133
+	}
5134
+
5135
+
5136
+
5137
+	/**
5138
+	 * Gets all the fields which, when combined, make the primary key.
5139
+	 * This is usually just an array with 1 element (the primary key), but in cases
5140
+	 * where there is no primary key, it's a combination of fields as defined
5141
+	 * on a primary index
5142
+	 *
5143
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5144
+	 * @throws \EE_Error
5145
+	 */
5146
+	public function get_combined_primary_key_fields()
5147
+	{
5148
+		foreach ($this->indexes() as $index) {
5149
+			if ($index instanceof EE_Primary_Key_Index) {
5150
+				return $index->fields();
5151
+			}
5152
+		}
5153
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5154
+	}
5155
+
5156
+
5157
+
5158
+	/**
5159
+	 * Used to build a primary key string (when the model has no primary key),
5160
+	 * which can be used a unique string to identify this model object.
5161
+	 *
5162
+	 * @param array $cols_n_values keys are field names, values are their values
5163
+	 * @return string
5164
+	 * @throws \EE_Error
5165
+	 */
5166
+	public function get_index_primary_key_string($cols_n_values)
5167
+	{
5168
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5169
+			$this->get_combined_primary_key_fields());
5170
+		return http_build_query($cols_n_values_for_primary_key_index);
5171
+	}
5172
+
5173
+
5174
+
5175
+	/**
5176
+	 * Gets the field values from the primary key string
5177
+	 *
5178
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5179
+	 * @param string $index_primary_key_string
5180
+	 * @return null|array
5181
+	 * @throws \EE_Error
5182
+	 */
5183
+	public function parse_index_primary_key_string($index_primary_key_string)
5184
+	{
5185
+		$key_fields = $this->get_combined_primary_key_fields();
5186
+		//check all of them are in the $id
5187
+		$key_vals_in_combined_pk = array();
5188
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5189
+		foreach ($key_fields as $key_field_name => $field_obj) {
5190
+			if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5191
+				return null;
5192
+			}
5193
+		}
5194
+		return $key_vals_in_combined_pk;
5195
+	}
5196
+
5197
+
5198
+
5199
+	/**
5200
+	 * verifies that an array of key-value pairs for model fields has a key
5201
+	 * for each field comprising the primary key index
5202
+	 *
5203
+	 * @param array $key_vals
5204
+	 * @return boolean
5205
+	 * @throws \EE_Error
5206
+	 */
5207
+	public function has_all_combined_primary_key_fields($key_vals)
5208
+	{
5209
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5210
+		foreach ($keys_it_should_have as $key) {
5211
+			if ( ! isset($key_vals[$key])) {
5212
+				return false;
5213
+			}
5214
+		}
5215
+		return true;
5216
+	}
5217
+
5218
+
5219
+
5220
+	/**
5221
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5222
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5223
+	 *
5224
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5225
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5226
+	 * @throws EE_Error
5227
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5228
+	 *                                                              indexed)
5229
+	 */
5230
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5231
+	{
5232
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5233
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5234
+		} elseif (is_array($model_object_or_attributes_array)) {
5235
+			$attributes_array = $model_object_or_attributes_array;
5236
+		} else {
5237
+			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",
5238
+				"event_espresso"), $model_object_or_attributes_array));
5239
+		}
5240
+		//even copies obviously won't have the same ID, so remove the primary key
5241
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5242
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5243
+			unset($attributes_array[$this->primary_key_name()]);
5244
+		}
5245
+		if (isset($query_params[0])) {
5246
+			$query_params[0] = array_merge($attributes_array, $query_params);
5247
+		} else {
5248
+			$query_params[0] = $attributes_array;
5249
+		}
5250
+		return $this->get_all($query_params);
5251
+	}
5252
+
5253
+
5254
+
5255
+	/**
5256
+	 * Gets the first copy we find. See get_all_copies for more details
5257
+	 *
5258
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5259
+	 * @param array $query_params
5260
+	 * @return EE_Base_Class
5261
+	 * @throws \EE_Error
5262
+	 */
5263
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5264
+	{
5265
+		if ( ! is_array($query_params)) {
5266
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5267
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5268
+					gettype($query_params)), '4.6.0');
5269
+			$query_params = array();
5270
+		}
5271
+		$query_params['limit'] = 1;
5272
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5273
+		if (is_array($copies)) {
5274
+			return array_shift($copies);
5275
+		} else {
5276
+			return null;
5277
+		}
5278
+	}
5279
+
5280
+
5281
+
5282
+	/**
5283
+	 * Updates the item with the specified id. Ignores default query parameters because
5284
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5285
+	 *
5286
+	 * @param array      $fields_n_values keys are field names, values are their new values
5287
+	 * @param int|string $id              the value of the primary key to update
5288
+	 * @return int number of rows updated
5289
+	 * @throws \EE_Error
5290
+	 */
5291
+	public function update_by_ID($fields_n_values, $id)
5292
+	{
5293
+		$query_params = array(
5294
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5295
+			'default_where_conditions' => 'other_models_only',
5296
+		);
5297
+		return $this->update($fields_n_values, $query_params);
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * Changes an operator which was supplied to the models into one usable in SQL
5304
+	 *
5305
+	 * @param string $operator_supplied
5306
+	 * @return string an operator which can be used in SQL
5307
+	 * @throws EE_Error
5308
+	 */
5309
+	private function _prepare_operator_for_sql($operator_supplied)
5310
+	{
5311
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5312
+			: null;
5313
+		if ($sql_operator) {
5314
+			return $sql_operator;
5315
+		} else {
5316
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5317
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5318
+		}
5319
+	}
5320
+
5321
+
5322
+
5323
+	/**
5324
+	 * Gets an array where keys are the primary keys and values are their 'names'
5325
+	 * (as determined by the model object's name() function, which is often overridden)
5326
+	 *
5327
+	 * @param array $query_params like get_all's
5328
+	 * @return string[]
5329
+	 * @throws \EE_Error
5330
+	 */
5331
+	public function get_all_names($query_params = array())
5332
+	{
5333
+		$objs = $this->get_all($query_params);
5334
+		$names = array();
5335
+		foreach ($objs as $obj) {
5336
+			$names[$obj->ID()] = $obj->name();
5337
+		}
5338
+		return $names;
5339
+	}
5340
+
5341
+
5342
+
5343
+	/**
5344
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5345
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5346
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5347
+	 * array_keys() on $model_objects.
5348
+	 *
5349
+	 * @param \EE_Base_Class[] $model_objects
5350
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5351
+	 *                                               in the returned array
5352
+	 * @return array
5353
+	 * @throws \EE_Error
5354
+	 */
5355
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5356
+	{
5357
+		if ( ! $this->has_primary_key_field()) {
5358
+			if (WP_DEBUG) {
5359
+				EE_Error::add_error(
5360
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5361
+					__FILE__,
5362
+					__FUNCTION__,
5363
+					__LINE__
5364
+				);
5365
+			}
5366
+		}
5367
+		$IDs = array();
5368
+		foreach ($model_objects as $model_object) {
5369
+			$id = $model_object->ID();
5370
+			if ( ! $id) {
5371
+				if ($filter_out_empty_ids) {
5372
+					continue;
5373
+				}
5374
+				if (WP_DEBUG) {
5375
+					EE_Error::add_error(
5376
+						__(
5377
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5378
+							'event_espresso'
5379
+						),
5380
+						__FILE__,
5381
+						__FUNCTION__,
5382
+						__LINE__
5383
+					);
5384
+				}
5385
+			}
5386
+			$IDs[] = $id;
5387
+		}
5388
+		return $IDs;
5389
+	}
5390
+
5391
+
5392
+
5393
+	/**
5394
+	 * Returns the string used in capabilities relating to this model. If there
5395
+	 * are no capabilities that relate to this model returns false
5396
+	 *
5397
+	 * @return string|false
5398
+	 */
5399
+	public function cap_slug()
5400
+	{
5401
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5402
+	}
5403
+
5404
+
5405
+
5406
+	/**
5407
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5408
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5409
+	 * only returns the cap restrictions array in that context (ie, the array
5410
+	 * at that key)
5411
+	 *
5412
+	 * @param string $context
5413
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5414
+	 * @throws \EE_Error
5415
+	 */
5416
+	public function cap_restrictions($context = EEM_Base::caps_read)
5417
+	{
5418
+		EEM_Base::verify_is_valid_cap_context($context);
5419
+		//check if we ought to run the restriction generator first
5420
+		if (
5421
+			isset($this->_cap_restriction_generators[$context])
5422
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5423
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5424
+		) {
5425
+			$this->_cap_restrictions[$context] = array_merge(
5426
+				$this->_cap_restrictions[$context],
5427
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5428
+			);
5429
+		}
5430
+		//and make sure we've finalized the construction of each restriction
5431
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5432
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5433
+				$where_conditions_obj->_finalize_construct($this);
5434
+			}
5435
+		}
5436
+		return $this->_cap_restrictions[$context];
5437
+	}
5438
+
5439
+
5440
+
5441
+	/**
5442
+	 * Indicating whether or not this model thinks its a wp core model
5443
+	 *
5444
+	 * @return boolean
5445
+	 */
5446
+	public function is_wp_core_model()
5447
+	{
5448
+		return $this->_wp_core_model;
5449
+	}
5450
+
5451
+
5452
+
5453
+	/**
5454
+	 * Gets all the caps that are missing which impose a restriction on
5455
+	 * queries made in this context
5456
+	 *
5457
+	 * @param string $context one of EEM_Base::caps_ constants
5458
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5459
+	 * @throws \EE_Error
5460
+	 */
5461
+	public function caps_missing($context = EEM_Base::caps_read)
5462
+	{
5463
+		$missing_caps = array();
5464
+		$cap_restrictions = $this->cap_restrictions($context);
5465
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5466
+			if ( ! EE_Capabilities::instance()
5467
+								  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5468
+			) {
5469
+				$missing_caps[$cap] = $restriction_if_no_cap;
5470
+			}
5471
+		}
5472
+		return $missing_caps;
5473
+	}
5474
+
5475
+
5476
+
5477
+	/**
5478
+	 * Gets the mapping from capability contexts to action strings used in capability names
5479
+	 *
5480
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5481
+	 * one of 'read', 'edit', or 'delete'
5482
+	 */
5483
+	public function cap_contexts_to_cap_action_map()
5484
+	{
5485
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5486
+			$this);
5487
+	}
5488
+
5489
+
5490
+
5491
+	/**
5492
+	 * Gets the action string for the specified capability context
5493
+	 *
5494
+	 * @param string $context
5495
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5496
+	 * @throws \EE_Error
5497
+	 */
5498
+	public function cap_action_for_context($context)
5499
+	{
5500
+		$mapping = $this->cap_contexts_to_cap_action_map();
5501
+		if (isset($mapping[$context])) {
5502
+			return $mapping[$context];
5503
+		}
5504
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5505
+			return $action;
5506
+		}
5507
+		throw new EE_Error(
5508
+			sprintf(
5509
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5510
+				$context,
5511
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5512
+			)
5513
+		);
5514
+	}
5515
+
5516
+
5517
+
5518
+	/**
5519
+	 * Returns all the capability contexts which are valid when querying models
5520
+	 *
5521
+	 * @return array
5522
+	 */
5523
+	static public function valid_cap_contexts()
5524
+	{
5525
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5526
+			self::caps_read,
5527
+			self::caps_read_admin,
5528
+			self::caps_edit,
5529
+			self::caps_delete,
5530
+		));
5531
+	}
5532
+
5533
+
5534
+
5535
+	/**
5536
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5537
+	 *
5538
+	 * @param string $context
5539
+	 * @return bool
5540
+	 * @throws \EE_Error
5541
+	 */
5542
+	static public function verify_is_valid_cap_context($context)
5543
+	{
5544
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5545
+		if (in_array($context, $valid_cap_contexts)) {
5546
+			return true;
5547
+		} else {
5548
+			throw new EE_Error(
5549
+				sprintf(
5550
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5551
+						'event_espresso'),
5552
+					$context,
5553
+					'EEM_Base',
5554
+					implode(',', $valid_cap_contexts)
5555
+				)
5556
+			);
5557
+		}
5558
+	}
5559
+
5560
+
5561
+
5562
+	/**
5563
+	 * Clears all the models field caches. This is only useful when a sub-class
5564
+	 * might have added a field or something and these caches might be invalidated
5565
+	 */
5566
+	protected function _invalidate_field_caches()
5567
+	{
5568
+		$this->_cache_foreign_key_to_fields = array();
5569
+		$this->_cached_fields = null;
5570
+		$this->_cached_fields_non_db_only = null;
5571
+	}
5572 5572
 
5573 5573
 
5574 5574
 
Please login to merge, or discard this patch.
core/middleware/EE_Recommended_Versions.core.php 2 patches
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -18,162 +18,162 @@  discard block
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * converts a Request to a Response
23
-     *
24
-     * @param    EE_Request  $request
25
-     * @param    EE_Response $response
26
-     * @return    EE_Response
27
-     */
28
-    public function handle_request(EE_Request $request, EE_Response $response)
29
-    {
30
-        $this->_request = $request;
31
-        $this->_response = $response;
32
-        //$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
33
-        //$this->_response->set_notice( 1, 'hey look at this' );
34
-        // check required WP version
35
-        if ( ! $this->_minimum_wp_version_required()) {
36
-            $this->_request->un_set('activate', true);
37
-            add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
38
-            //$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
39
-            $this->_response->terminate_request();
40
-            $this->_response->deactivate_plugin();
41
-        }
42
-        // check required PHP version
43
-        if ( ! $this->_minimum_php_version_required()) {
44
-            $this->_request->un_set('activate', true);
45
-            add_action('admin_notices', array($this, 'minimum_php_version_error'), 1);
46
-            //$this->_response->add_output( "\n<br />" . 'minimum_php_version_error' );
47
-            $this->_response->terminate_request();
48
-            $this->_response->deactivate_plugin();
49
-        }
50
-        // check recommended PHP version
51
-        if ( ! $this->_minimum_php_version_recommended()) {
52
-            $this->_display_minimum_recommended_php_version_notice();
53
-        }
54
-        $this->_response = $this->process_request_stack($this->_request, $this->_response);
55
-        //$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
56
-        return $this->_response;
57
-    }
58
-
59
-
60
-
61
-    /**
62
-     *    _check_wp_version
63
-     *
64
-     * @access private
65
-     * @param string $min_version
66
-     * @return boolean
67
-     */
68
-    private function _check_wp_version($min_version = EE_MIN_WP_VER_REQUIRED)
69
-    {
70
-        global $wp_version;
71
-        return version_compare($wp_version, $min_version, '>=') ? true : false;
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     *    _minimum_wp_version_required
78
-     *
79
-     * @access private
80
-     * @return boolean
81
-     */
82
-    private function _minimum_wp_version_required()
83
-    {
84
-        return $this->_check_wp_version(EE_MIN_WP_VER_REQUIRED);
85
-    }
86
-
87
-
88
-
89
-    /**
90
-     *    _check_php_version
91
-     *
92
-     * @access private
93
-     * @param string $min_version
94
-     * @return boolean
95
-     */
96
-    private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
97
-    {
98
-        return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
99
-    }
100
-
101
-
102
-
103
-    /**
104
-     *    _minimum_php_version_required
105
-     *
106
-     * @access private
107
-     * @return boolean
108
-     */
109
-    private function _minimum_php_version_required()
110
-    {
111
-        return $this->_check_php_version(EE_MIN_PHP_VER_REQUIRED);
112
-    }
113
-
114
-
115
-
116
-    /**
117
-     *    _minimum_php_version_recommended
118
-     *
119
-     * @access private
120
-     * @return boolean
121
-     */
122
-    private function _minimum_php_version_recommended()
123
-    {
124
-        return $this->_check_php_version(EE_MIN_PHP_VER_RECOMMENDED);
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     *    minimum_wp_version_error
131
-     *
132
-     * @return void
133
-     */
134
-    public function minimum_wp_version_error()
135
-    {
136
-        global $wp_version;
137
-        ?>
21
+	/**
22
+	 * converts a Request to a Response
23
+	 *
24
+	 * @param    EE_Request  $request
25
+	 * @param    EE_Response $response
26
+	 * @return    EE_Response
27
+	 */
28
+	public function handle_request(EE_Request $request, EE_Response $response)
29
+	{
30
+		$this->_request = $request;
31
+		$this->_response = $response;
32
+		//$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
33
+		//$this->_response->set_notice( 1, 'hey look at this' );
34
+		// check required WP version
35
+		if ( ! $this->_minimum_wp_version_required()) {
36
+			$this->_request->un_set('activate', true);
37
+			add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
38
+			//$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
39
+			$this->_response->terminate_request();
40
+			$this->_response->deactivate_plugin();
41
+		}
42
+		// check required PHP version
43
+		if ( ! $this->_minimum_php_version_required()) {
44
+			$this->_request->un_set('activate', true);
45
+			add_action('admin_notices', array($this, 'minimum_php_version_error'), 1);
46
+			//$this->_response->add_output( "\n<br />" . 'minimum_php_version_error' );
47
+			$this->_response->terminate_request();
48
+			$this->_response->deactivate_plugin();
49
+		}
50
+		// check recommended PHP version
51
+		if ( ! $this->_minimum_php_version_recommended()) {
52
+			$this->_display_minimum_recommended_php_version_notice();
53
+		}
54
+		$this->_response = $this->process_request_stack($this->_request, $this->_response);
55
+		//$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
56
+		return $this->_response;
57
+	}
58
+
59
+
60
+
61
+	/**
62
+	 *    _check_wp_version
63
+	 *
64
+	 * @access private
65
+	 * @param string $min_version
66
+	 * @return boolean
67
+	 */
68
+	private function _check_wp_version($min_version = EE_MIN_WP_VER_REQUIRED)
69
+	{
70
+		global $wp_version;
71
+		return version_compare($wp_version, $min_version, '>=') ? true : false;
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 *    _minimum_wp_version_required
78
+	 *
79
+	 * @access private
80
+	 * @return boolean
81
+	 */
82
+	private function _minimum_wp_version_required()
83
+	{
84
+		return $this->_check_wp_version(EE_MIN_WP_VER_REQUIRED);
85
+	}
86
+
87
+
88
+
89
+	/**
90
+	 *    _check_php_version
91
+	 *
92
+	 * @access private
93
+	 * @param string $min_version
94
+	 * @return boolean
95
+	 */
96
+	private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
97
+	{
98
+		return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
99
+	}
100
+
101
+
102
+
103
+	/**
104
+	 *    _minimum_php_version_required
105
+	 *
106
+	 * @access private
107
+	 * @return boolean
108
+	 */
109
+	private function _minimum_php_version_required()
110
+	{
111
+		return $this->_check_php_version(EE_MIN_PHP_VER_REQUIRED);
112
+	}
113
+
114
+
115
+
116
+	/**
117
+	 *    _minimum_php_version_recommended
118
+	 *
119
+	 * @access private
120
+	 * @return boolean
121
+	 */
122
+	private function _minimum_php_version_recommended()
123
+	{
124
+		return $this->_check_php_version(EE_MIN_PHP_VER_RECOMMENDED);
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 *    minimum_wp_version_error
131
+	 *
132
+	 * @return void
133
+	 */
134
+	public function minimum_wp_version_error()
135
+	{
136
+		global $wp_version;
137
+		?>
138 138
         <div class="error">
139 139
             <p>
140 140
                 <?php
141
-                printf(
142
-                        __('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
143
-                                'event_espresso'),
144
-                        EE_MIN_WP_VER_REQUIRED,
145
-                        $wp_version,
146
-                        '<br/>',
147
-                        '<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
148
-                );
149
-                ?>
141
+				printf(
142
+						__('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
143
+								'event_espresso'),
144
+						EE_MIN_WP_VER_REQUIRED,
145
+						$wp_version,
146
+						'<br/>',
147
+						'<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
148
+				);
149
+				?>
150 150
             </p>
151 151
         </div>
152 152
         <?php
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     *    _display_minimum_recommended_php_version_notice
159
-     *
160
-     * @access private
161
-     * @return void
162
-     */
163
-    private function _display_minimum_recommended_php_version_notice()
164
-    {
165
-        EE_Error::add_persistent_admin_notice(
166
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
167
-                sprintf(
168
-                        __('Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
169
-                                'event_espresso'),
170
-                        EE_MIN_PHP_VER_RECOMMENDED,
171
-                        PHP_VERSION,
172
-                        '<br/>',
173
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
174
-                )
175
-        );
176
-    }
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 *    _display_minimum_recommended_php_version_notice
159
+	 *
160
+	 * @access private
161
+	 * @return void
162
+	 */
163
+	private function _display_minimum_recommended_php_version_notice()
164
+	{
165
+		EE_Error::add_persistent_admin_notice(
166
+				'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
167
+				sprintf(
168
+						__('Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
169
+								'event_espresso'),
170
+						EE_MIN_PHP_VER_RECOMMENDED,
171
+						PHP_VERSION,
172
+						'<br/>',
173
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
174
+				)
175
+		);
176
+	}
177 177
 
178 178
 
179 179
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -163,7 +163,7 @@
 block discarded – undo
163 163
     private function _display_minimum_recommended_php_version_notice()
164 164
     {
165 165
         EE_Error::add_persistent_admin_notice(
166
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
166
+                'php_version_'.str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED).'_recommended',
167 167
                 sprintf(
168 168
                         __('Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
169 169
                                 'event_espresso'),
Please login to merge, or discard this patch.