Completed
Branch FET-3467-waitlists (4406f2)
by
unknown
46:31 queued 34:26
created
admin_pages/maintenance/templates/migration_options_from_ee4.template.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@
 block discarded – undo
68 68
     </div>
69 69
     <p><?php esc_html_e('Don\'t want to keep your old Event Espresso data? Alternatively, you can delete it all and start fresh.',
70 70
                 'event_espresso'); ?> <a
71
-                href="<?php echo $data_reset_page;?>"><?php esc_html_e('Visit the Maintenance Page and Reset Your Event Espresso Data',
71
+                href="<?php echo $data_reset_page; ?>"><?php esc_html_e('Visit the Maintenance Page and Reset Your Event Espresso Data',
72 72
                     'event_espresso'); ?></a></p>
73 73
     <?php do_action('AHEE__ee_migration_page__after_migration_options_table'); ?>
74 74
 </div>
75 75
\ No newline at end of file
Please login to merge, or discard this patch.
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -25,14 +25,14 @@  discard block
 block discarded – undo
25 25
             <tr>
26 26
                 <td>
27 27
                     <?php
28
-                    echo apply_filters(
29
-                            'FHEE__ee_migration_page__option_1_main',
30
-                            esc_html__('Before updating your database, you should first create a database backup',
31
-                                    "event_espresso"),
32
-                            $current_db_state,
33
-                            $next_db_state
34
-                    );
35
-                    ?>
28
+					echo apply_filters(
29
+							'FHEE__ee_migration_page__option_1_main',
30
+							esc_html__('Before updating your database, you should first create a database backup',
31
+									"event_espresso"),
32
+							$current_db_state,
33
+							$next_db_state
34
+					);
35
+					?>
36 36
                     <a id="display-migration-details"
37 37
                        class="display-the-hidden lt-grey-text smaller-text hide-if-no-js"
38 38
                        rel="migration-details"><?php esc_html_e('How Do I Make a Database Backup?', "event_espresso"); ?>
@@ -41,8 +41,8 @@  discard block
 block discarded – undo
41 41
                 <td>
42 42
                     <a id="db-backed-up"
43 43
                        class="toggle-migration-monitor button-primary"><?php echo apply_filters('FHEE__ee_migration_page__option_1_button_text',
44
-                                sprintf(esc_html__("My Database Is Backed Up, Continue", "event_espresso"), $current_db_state,
45
-                                        $next_db_state), $current_db_state, $next_db_state); ?></a>
44
+								sprintf(esc_html__("My Database Is Backed Up, Continue", "event_espresso"), $current_db_state,
45
+										$next_db_state), $current_db_state, $next_db_state); ?></a>
46 46
                 </td>
47 47
             </tr>
48 48
             <tr>
@@ -50,14 +50,14 @@  discard block
 block discarded – undo
50 50
                     <div id="migration-details-dv" style="display: none; padding: 1em;">
51 51
                         <p>
52 52
                             <?php
53
-                            printf(
54
-                                    esc_html__('%1$sClick Here to Learn How To Backup your Database Yourself%2$s. Or have one of our dedicated support technicians help you by %3$spurchasing a Priority Support Token.%2$s',
55
-                                            "event_espresso"),
56
-                                    '<a target="_blank" href="http://eventespresso.com/wiki/how-to-back-up-your-site/">',
57
-                                    "</a>",
58
-                                    "<a target=\"_blank\" href='http://eventespresso.com/product/priority-support-tokens/'>"
59
-                            );
60
-                            ?>
53
+							printf(
54
+									esc_html__('%1$sClick Here to Learn How To Backup your Database Yourself%2$s. Or have one of our dedicated support technicians help you by %3$spurchasing a Priority Support Token.%2$s',
55
+											"event_espresso"),
56
+									'<a target="_blank" href="http://eventespresso.com/wiki/how-to-back-up-your-site/">',
57
+									"</a>",
58
+									"<a target=\"_blank\" href='http://eventespresso.com/product/priority-support-tokens/'>"
59
+							);
60
+							?>
61 61
                         </p>
62 62
                         <?php do_action('AHEE__ee_migration_page__option_1_extra_details'); ?>
63 63
                     </div>
@@ -67,8 +67,8 @@  discard block
 block discarded – undo
67 67
         </table>
68 68
     </div>
69 69
     <p><?php esc_html_e('Don\'t want to keep your old Event Espresso data? Alternatively, you can delete it all and start fresh.',
70
-                'event_espresso'); ?> <a
70
+				'event_espresso'); ?> <a
71 71
                 href="<?php echo $data_reset_page;?>"><?php esc_html_e('Visit the Maintenance Page and Reset Your Event Espresso Data',
72
-                    'event_espresso'); ?></a></p>
72
+					'event_espresso'); ?></a></p>
73 73
     <?php do_action('AHEE__ee_migration_page__after_migration_options_table'); ?>
74 74
 </div>
75 75
\ No newline at end of file
Please login to merge, or discard this patch.
core/EE_Cart.core.php 3 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.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -203,7 +203,7 @@
 block discarded – undo
203 203
      */
204 204
     public function get_tickets()
205 205
     {
206
-        if ($this->_grand_total === null ) {
206
+        if ($this->_grand_total === null) {
207 207
             return array();
208 208
         }
209 209
         return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
Please login to merge, or discard this patch.
Indentation   +413 added lines, -413 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\interfaces\ResettableInterface;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 do_action('AHEE_log', __FILE__, __FUNCTION__, '');
8 8
 
@@ -23,418 +23,418 @@  discard block
 block discarded – undo
23 23
 class EE_Cart implements ResettableInterface
24 24
 {
25 25
 
26
-    /**
27
-     * instance of the EE_Cart object
28
-     *
29
-     * @access    private
30
-     * @var EE_Cart $_instance
31
-     */
32
-    private static $_instance;
33
-
34
-    /**
35
-     * instance of the EE_Session object
36
-     *
37
-     * @access    protected
38
-     * @var EE_Session $_session
39
-     */
40
-    protected $_session;
41
-
42
-    /**
43
-     * The total Line item which comprises all the children line-item subtotals,
44
-     * which in turn each have their line items.
45
-     * Typically, the line item structure will look like:
46
-     * grand total
47
-     * -tickets-sub-total
48
-     * --ticket1
49
-     * --ticket2
50
-     * --...
51
-     * -taxes-sub-total
52
-     * --tax1
53
-     * --tax2
54
-     *
55
-     * @var EE_Line_Item
56
-     */
57
-    private $_grand_total;
58
-
59
-
60
-
61
-    /**
62
-     * @singleton method used to instantiate class object
63
-     * @access    public
64
-     * @param EE_Line_Item $grand_total
65
-     * @param EE_Session   $session
66
-     * @return \EE_Cart
67
-     * @throws \EE_Error
68
-     */
69
-    public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
70
-    {
71
-        if ( ! empty($grand_total)) {
72
-            self::$_instance = new self($grand_total, $session);
73
-        }
74
-        // or maybe retrieve an existing one ?
75
-        if ( ! self::$_instance instanceof EE_Cart) {
76
-            // try getting the cart out of the session
77
-            $saved_cart = $session instanceof EE_Session ? $session->cart() : null;
78
-            self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
79
-            unset($saved_cart);
80
-        }
81
-        // verify that cart is ok and grand total line item exists
82
-        if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
83
-            self::$_instance = new self($grand_total, $session);
84
-        }
85
-        self::$_instance->get_grand_total();
86
-        // once everything is all said and done, save the cart to the EE_Session
87
-        add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
88
-        return self::$_instance;
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     * private constructor to prevent direct creation
95
-     *
96
-     * @Constructor
97
-     * @access private
98
-     * @param EE_Line_Item $grand_total
99
-     * @param EE_Session   $session
100
-     */
101
-    private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
102
-    {
103
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
104
-        $this->set_session($session);
105
-        if ($grand_total instanceof EE_Line_Item) {
106
-            $this->set_grand_total_line_item($grand_total);
107
-        }
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * Resets the cart completely (whereas empty_cart
114
-     *
115
-     * @param EE_Line_Item $grand_total
116
-     * @param EE_Session   $session
117
-     * @return EE_Cart
118
-     * @throws \EE_Error
119
-     */
120
-    public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
121
-    {
122
-        remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
123
-        if ($session instanceof EE_Session) {
124
-            $session->reset_cart();
125
-        }
126
-        self::$_instance = null;
127
-        return self::instance($grand_total, $session);
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * @return \EE_Session
134
-     */
135
-    public function session()
136
-    {
137
-        if ( ! $this->_session instanceof EE_Session) {
138
-            $this->set_session();
139
-        }
140
-        return $this->_session;
141
-    }
142
-
143
-
144
-
145
-    /**
146
-     * @param EE_Session $session
147
-     */
148
-    public function set_session(EE_Session $session = null)
149
-    {
150
-        $this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * Sets the cart to match the line item. Especially handy for loading an old cart where you
157
-     *  know the grand total line item on it
158
-     *
159
-     * @param EE_Line_Item $line_item
160
-     */
161
-    public function set_grand_total_line_item(EE_Line_Item $line_item)
162
-    {
163
-        $this->_grand_total = $line_item;
164
-    }
165
-
166
-
167
-
168
-    /**
169
-     * get_cart_from_reg_url_link
170
-     *
171
-     * @access public
172
-     * @param EE_Transaction $transaction
173
-     * @param EE_Session     $session
174
-     * @return \EE_Cart
175
-     * @throws \EE_Error
176
-     */
177
-    public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
178
-    {
179
-        $grand_total = $transaction->total_line_item();
180
-        $grand_total->get_items();
181
-        $grand_total->tax_descendants();
182
-        return EE_Cart::instance($grand_total, $session);
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
189
-     *
190
-     * @return EE_Line_Item
191
-     * @throws \EE_Error
192
-     */
193
-    private function _create_grand_total()
194
-    {
195
-        $this->_grand_total = EEH_Line_Item::create_total_line_item();
196
-        return $this->_grand_total;
197
-    }
198
-
199
-
200
-
201
-    /**
202
-     * Gets all the line items of object type Ticket
203
-     *
204
-     * @access public
205
-     * @return \EE_Line_Item[]
206
-     */
207
-    public function get_tickets()
208
-    {
209
-        if ($this->_grand_total === null ) {
210
-            return array();
211
-        }
212
-        return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
213
-    }
214
-
215
-
216
-
217
-    /**
218
-     * returns the total quantity of tickets in the cart
219
-     *
220
-     * @access public
221
-     * @return int
222
-     * @throws \EE_Error
223
-     */
224
-    public function all_ticket_quantity_count()
225
-    {
226
-        $tickets = $this->get_tickets();
227
-        if (empty($tickets)) {
228
-            return 0;
229
-        }
230
-        $count = 0;
231
-        foreach ($tickets as $ticket) {
232
-            $count += $ticket->get('LIN_quantity');
233
-        }
234
-        return $count;
235
-    }
236
-
237
-
238
-
239
-    /**
240
-     * Gets all the tax line items
241
-     *
242
-     * @return \EE_Line_Item[]
243
-     * @throws \EE_Error
244
-     */
245
-    public function get_taxes()
246
-    {
247
-        return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
248
-    }
249
-
250
-
251
-
252
-    /**
253
-     * Gets the total line item (which is a parent of all other line items) on this cart
254
-     *
255
-     * @return EE_Line_Item
256
-     * @throws \EE_Error
257
-     */
258
-    public function get_grand_total()
259
-    {
260
-        return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     * @process items for adding to cart
267
-     * @access  public
268
-     * @param EE_Ticket $ticket
269
-     * @param int       $qty
270
-     * @return TRUE on success, FALSE on fail
271
-     * @throws \EE_Error
272
-     */
273
-    public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
274
-    {
275
-        EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
276
-        return $this->save_cart() ? true : false;
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * get_cart_total_before_tax
283
-     *
284
-     * @access public
285
-     * @return float
286
-     * @throws \EE_Error
287
-     */
288
-    public function get_cart_total_before_tax()
289
-    {
290
-        return $this->get_grand_total()->recalculate_pre_tax_total();
291
-    }
292
-
293
-
294
-
295
-    /**
296
-     * gets the total amount of tax paid for items in this cart
297
-     *
298
-     * @access public
299
-     * @return float
300
-     * @throws \EE_Error
301
-     */
302
-    public function get_applied_taxes()
303
-    {
304
-        return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
305
-    }
306
-
307
-
308
-
309
-    /**
310
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
311
-     *
312
-     * @access public
313
-     * @return float
314
-     * @throws \EE_Error
315
-     */
316
-    public function get_cart_grand_total()
317
-    {
318
-        EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
319
-        return $this->get_grand_total()->total();
320
-    }
321
-
322
-
323
-
324
-    /**
325
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
326
-     *
327
-     * @access public
328
-     * @return float
329
-     * @throws \EE_Error
330
-     */
331
-    public function recalculate_all_cart_totals()
332
-    {
333
-        $pre_tax_total = $this->get_cart_total_before_tax();
334
-        $taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
335
-        $this->_grand_total->set_total($pre_tax_total + $taxes_total);
336
-        $this->_grand_total->save_this_and_descendants_to_txn();
337
-        return $this->get_grand_total()->total();
338
-    }
339
-
340
-
341
-
342
-    /**
343
-     * deletes an item from the cart
344
-     *
345
-     * @access public
346
-     * @param array|bool|string $line_item_codes
347
-     * @return int on success, FALSE on fail
348
-     * @throws \EE_Error
349
-     */
350
-    public function delete_items($line_item_codes = false)
351
-    {
352
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
353
-        return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
354
-    }
355
-
356
-
357
-
358
-    /**
359
-     * @remove ALL items from cart and zero ALL totals
360
-     * @access public
361
-     * @return bool
362
-     * @throws \EE_Error
363
-     */
364
-    public function empty_cart()
365
-    {
366
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
367
-        $this->_grand_total = $this->_create_grand_total();
368
-        return $this->save_cart(true);
369
-    }
370
-
371
-
372
-
373
-    /**
374
-     * @remove ALL items from cart and delete total as well
375
-     * @access public
376
-     * @return bool
377
-     * @throws \EE_Error
378
-     */
379
-    public function delete_cart()
380
-    {
381
-        $deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
382
-        if ($deleted) {
383
-            $deleted += $this->_grand_total->delete();
384
-            $this->_grand_total = null;
385
-        }
386
-        return $deleted;
387
-    }
388
-
389
-
390
-
391
-    /**
392
-     * @save   cart to session
393
-     * @access public
394
-     * @param bool $apply_taxes
395
-     * @return TRUE on success, FALSE on fail
396
-     * @throws \EE_Error
397
-     */
398
-    public function save_cart($apply_taxes = true)
399
-    {
400
-        if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
401
-            EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
402
-            //make sure we don't cache the transaction because it can get stale
403
-            if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
404
-                && $this->_grand_total->get_one_from_cache('Transaction')->ID()
405
-            ) {
406
-                $this->_grand_total->clear_cache('Transaction', null, true);
407
-            }
408
-        }
409
-        if ($this->session() instanceof EE_Session) {
410
-            return $this->session()->set_cart($this);
411
-        } else {
412
-            return false;
413
-        }
414
-    }
415
-
416
-
417
-
418
-    public function __wakeup()
419
-    {
420
-        if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
421
-            // $this->_grand_total is actually just an ID, so use it to get the object from the db
422
-            $this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
423
-        }
424
-    }
425
-
426
-
427
-
428
-    /**
429
-     * @return array
430
-     */
431
-    public function __sleep()
432
-    {
433
-        if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
434
-            $this->_grand_total = $this->_grand_total->ID();
435
-        }
436
-        return array('_grand_total');
437
-    }
26
+	/**
27
+	 * instance of the EE_Cart object
28
+	 *
29
+	 * @access    private
30
+	 * @var EE_Cart $_instance
31
+	 */
32
+	private static $_instance;
33
+
34
+	/**
35
+	 * instance of the EE_Session object
36
+	 *
37
+	 * @access    protected
38
+	 * @var EE_Session $_session
39
+	 */
40
+	protected $_session;
41
+
42
+	/**
43
+	 * The total Line item which comprises all the children line-item subtotals,
44
+	 * which in turn each have their line items.
45
+	 * Typically, the line item structure will look like:
46
+	 * grand total
47
+	 * -tickets-sub-total
48
+	 * --ticket1
49
+	 * --ticket2
50
+	 * --...
51
+	 * -taxes-sub-total
52
+	 * --tax1
53
+	 * --tax2
54
+	 *
55
+	 * @var EE_Line_Item
56
+	 */
57
+	private $_grand_total;
58
+
59
+
60
+
61
+	/**
62
+	 * @singleton method used to instantiate class object
63
+	 * @access    public
64
+	 * @param EE_Line_Item $grand_total
65
+	 * @param EE_Session   $session
66
+	 * @return \EE_Cart
67
+	 * @throws \EE_Error
68
+	 */
69
+	public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
70
+	{
71
+		if ( ! empty($grand_total)) {
72
+			self::$_instance = new self($grand_total, $session);
73
+		}
74
+		// or maybe retrieve an existing one ?
75
+		if ( ! self::$_instance instanceof EE_Cart) {
76
+			// try getting the cart out of the session
77
+			$saved_cart = $session instanceof EE_Session ? $session->cart() : null;
78
+			self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
79
+			unset($saved_cart);
80
+		}
81
+		// verify that cart is ok and grand total line item exists
82
+		if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
83
+			self::$_instance = new self($grand_total, $session);
84
+		}
85
+		self::$_instance->get_grand_total();
86
+		// once everything is all said and done, save the cart to the EE_Session
87
+		add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
88
+		return self::$_instance;
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 * private constructor to prevent direct creation
95
+	 *
96
+	 * @Constructor
97
+	 * @access private
98
+	 * @param EE_Line_Item $grand_total
99
+	 * @param EE_Session   $session
100
+	 */
101
+	private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
102
+	{
103
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
104
+		$this->set_session($session);
105
+		if ($grand_total instanceof EE_Line_Item) {
106
+			$this->set_grand_total_line_item($grand_total);
107
+		}
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * Resets the cart completely (whereas empty_cart
114
+	 *
115
+	 * @param EE_Line_Item $grand_total
116
+	 * @param EE_Session   $session
117
+	 * @return EE_Cart
118
+	 * @throws \EE_Error
119
+	 */
120
+	public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
121
+	{
122
+		remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
123
+		if ($session instanceof EE_Session) {
124
+			$session->reset_cart();
125
+		}
126
+		self::$_instance = null;
127
+		return self::instance($grand_total, $session);
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * @return \EE_Session
134
+	 */
135
+	public function session()
136
+	{
137
+		if ( ! $this->_session instanceof EE_Session) {
138
+			$this->set_session();
139
+		}
140
+		return $this->_session;
141
+	}
142
+
143
+
144
+
145
+	/**
146
+	 * @param EE_Session $session
147
+	 */
148
+	public function set_session(EE_Session $session = null)
149
+	{
150
+		$this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * Sets the cart to match the line item. Especially handy for loading an old cart where you
157
+	 *  know the grand total line item on it
158
+	 *
159
+	 * @param EE_Line_Item $line_item
160
+	 */
161
+	public function set_grand_total_line_item(EE_Line_Item $line_item)
162
+	{
163
+		$this->_grand_total = $line_item;
164
+	}
165
+
166
+
167
+
168
+	/**
169
+	 * get_cart_from_reg_url_link
170
+	 *
171
+	 * @access public
172
+	 * @param EE_Transaction $transaction
173
+	 * @param EE_Session     $session
174
+	 * @return \EE_Cart
175
+	 * @throws \EE_Error
176
+	 */
177
+	public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
178
+	{
179
+		$grand_total = $transaction->total_line_item();
180
+		$grand_total->get_items();
181
+		$grand_total->tax_descendants();
182
+		return EE_Cart::instance($grand_total, $session);
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
189
+	 *
190
+	 * @return EE_Line_Item
191
+	 * @throws \EE_Error
192
+	 */
193
+	private function _create_grand_total()
194
+	{
195
+		$this->_grand_total = EEH_Line_Item::create_total_line_item();
196
+		return $this->_grand_total;
197
+	}
198
+
199
+
200
+
201
+	/**
202
+	 * Gets all the line items of object type Ticket
203
+	 *
204
+	 * @access public
205
+	 * @return \EE_Line_Item[]
206
+	 */
207
+	public function get_tickets()
208
+	{
209
+		if ($this->_grand_total === null ) {
210
+			return array();
211
+		}
212
+		return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
213
+	}
214
+
215
+
216
+
217
+	/**
218
+	 * returns the total quantity of tickets in the cart
219
+	 *
220
+	 * @access public
221
+	 * @return int
222
+	 * @throws \EE_Error
223
+	 */
224
+	public function all_ticket_quantity_count()
225
+	{
226
+		$tickets = $this->get_tickets();
227
+		if (empty($tickets)) {
228
+			return 0;
229
+		}
230
+		$count = 0;
231
+		foreach ($tickets as $ticket) {
232
+			$count += $ticket->get('LIN_quantity');
233
+		}
234
+		return $count;
235
+	}
236
+
237
+
238
+
239
+	/**
240
+	 * Gets all the tax line items
241
+	 *
242
+	 * @return \EE_Line_Item[]
243
+	 * @throws \EE_Error
244
+	 */
245
+	public function get_taxes()
246
+	{
247
+		return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
248
+	}
249
+
250
+
251
+
252
+	/**
253
+	 * Gets the total line item (which is a parent of all other line items) on this cart
254
+	 *
255
+	 * @return EE_Line_Item
256
+	 * @throws \EE_Error
257
+	 */
258
+	public function get_grand_total()
259
+	{
260
+		return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 * @process items for adding to cart
267
+	 * @access  public
268
+	 * @param EE_Ticket $ticket
269
+	 * @param int       $qty
270
+	 * @return TRUE on success, FALSE on fail
271
+	 * @throws \EE_Error
272
+	 */
273
+	public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
274
+	{
275
+		EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
276
+		return $this->save_cart() ? true : false;
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * get_cart_total_before_tax
283
+	 *
284
+	 * @access public
285
+	 * @return float
286
+	 * @throws \EE_Error
287
+	 */
288
+	public function get_cart_total_before_tax()
289
+	{
290
+		return $this->get_grand_total()->recalculate_pre_tax_total();
291
+	}
292
+
293
+
294
+
295
+	/**
296
+	 * gets the total amount of tax paid for items in this cart
297
+	 *
298
+	 * @access public
299
+	 * @return float
300
+	 * @throws \EE_Error
301
+	 */
302
+	public function get_applied_taxes()
303
+	{
304
+		return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
305
+	}
306
+
307
+
308
+
309
+	/**
310
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
311
+	 *
312
+	 * @access public
313
+	 * @return float
314
+	 * @throws \EE_Error
315
+	 */
316
+	public function get_cart_grand_total()
317
+	{
318
+		EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
319
+		return $this->get_grand_total()->total();
320
+	}
321
+
322
+
323
+
324
+	/**
325
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
326
+	 *
327
+	 * @access public
328
+	 * @return float
329
+	 * @throws \EE_Error
330
+	 */
331
+	public function recalculate_all_cart_totals()
332
+	{
333
+		$pre_tax_total = $this->get_cart_total_before_tax();
334
+		$taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
335
+		$this->_grand_total->set_total($pre_tax_total + $taxes_total);
336
+		$this->_grand_total->save_this_and_descendants_to_txn();
337
+		return $this->get_grand_total()->total();
338
+	}
339
+
340
+
341
+
342
+	/**
343
+	 * deletes an item from the cart
344
+	 *
345
+	 * @access public
346
+	 * @param array|bool|string $line_item_codes
347
+	 * @return int on success, FALSE on fail
348
+	 * @throws \EE_Error
349
+	 */
350
+	public function delete_items($line_item_codes = false)
351
+	{
352
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
353
+		return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
354
+	}
355
+
356
+
357
+
358
+	/**
359
+	 * @remove ALL items from cart and zero ALL totals
360
+	 * @access public
361
+	 * @return bool
362
+	 * @throws \EE_Error
363
+	 */
364
+	public function empty_cart()
365
+	{
366
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
367
+		$this->_grand_total = $this->_create_grand_total();
368
+		return $this->save_cart(true);
369
+	}
370
+
371
+
372
+
373
+	/**
374
+	 * @remove ALL items from cart and delete total as well
375
+	 * @access public
376
+	 * @return bool
377
+	 * @throws \EE_Error
378
+	 */
379
+	public function delete_cart()
380
+	{
381
+		$deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
382
+		if ($deleted) {
383
+			$deleted += $this->_grand_total->delete();
384
+			$this->_grand_total = null;
385
+		}
386
+		return $deleted;
387
+	}
388
+
389
+
390
+
391
+	/**
392
+	 * @save   cart to session
393
+	 * @access public
394
+	 * @param bool $apply_taxes
395
+	 * @return TRUE on success, FALSE on fail
396
+	 * @throws \EE_Error
397
+	 */
398
+	public function save_cart($apply_taxes = true)
399
+	{
400
+		if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
401
+			EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
402
+			//make sure we don't cache the transaction because it can get stale
403
+			if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
404
+				&& $this->_grand_total->get_one_from_cache('Transaction')->ID()
405
+			) {
406
+				$this->_grand_total->clear_cache('Transaction', null, true);
407
+			}
408
+		}
409
+		if ($this->session() instanceof EE_Session) {
410
+			return $this->session()->set_cart($this);
411
+		} else {
412
+			return false;
413
+		}
414
+	}
415
+
416
+
417
+
418
+	public function __wakeup()
419
+	{
420
+		if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
421
+			// $this->_grand_total is actually just an ID, so use it to get the object from the db
422
+			$this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
423
+		}
424
+	}
425
+
426
+
427
+
428
+	/**
429
+	 * @return array
430
+	 */
431
+	public function __sleep()
432
+	{
433
+		if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
434
+			$this->_grand_total = $this->_grand_total->ID();
435
+		}
436
+		return array('_grand_total');
437
+	}
438 438
 
439 439
 
440 440
 }
Please login to merge, or discard this patch.
core/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   +1427 added lines, -1427 removed lines patch added patch discarded remove patch
@@ -19,1463 +19,1463 @@
 block discarded – undo
19 19
 class EE_Registry implements ResettableInterface
20 20
 {
21 21
 
22
-    /**
23
-     *    EE_Registry Object
24
-     *
25
-     * @var EE_Registry $_instance
26
-     * @access    private
27
-     */
28
-    private static $_instance = null;
29
-
30
-    /**
31
-     * @var EE_Dependency_Map $_dependency_map
32
-     * @access    protected
33
-     */
34
-    protected $_dependency_map = null;
35
-
36
-    /**
37
-     * @var array $_class_abbreviations
38
-     * @access    protected
39
-     */
40
-    protected $_class_abbreviations = array();
41
-
42
-    /**
43
-     * @access public
44
-     * @var \EventEspresso\core\services\commands\CommandBusInterface $BUS
45
-     */
46
-    public $BUS;
47
-
48
-    /**
49
-     *    EE_Cart Object
50
-     *
51
-     * @access    public
52
-     * @var    EE_Cart $CART
53
-     */
54
-    public $CART = null;
55
-
56
-    /**
57
-     *    EE_Config Object
58
-     *
59
-     * @access    public
60
-     * @var    EE_Config $CFG
61
-     */
62
-    public $CFG = null;
63
-
64
-    /**
65
-     * EE_Network_Config Object
66
-     *
67
-     * @access public
68
-     * @var EE_Network_Config $NET_CFG
69
-     */
70
-    public $NET_CFG = null;
71
-
72
-    /**
73
-     *    StdClass object for storing library classes in
74
-     *
75
-     * @public LIB
76
-     * @var StdClass $LIB
77
-     */
78
-    public $LIB = null;
79
-
80
-    /**
81
-     *    EE_Request_Handler Object
82
-     *
83
-     * @access    public
84
-     * @var    EE_Request_Handler $REQ
85
-     */
86
-    public $REQ = null;
87
-
88
-    /**
89
-     *    EE_Session Object
90
-     *
91
-     * @access    public
92
-     * @var    EE_Session $SSN
93
-     */
94
-    public $SSN = null;
95
-
96
-    /**
97
-     * holds the ee capabilities object.
98
-     *
99
-     * @since 4.5.0
100
-     * @var EE_Capabilities
101
-     */
102
-    public $CAP = null;
103
-
104
-    /**
105
-     * holds the EE_Message_Resource_Manager object.
106
-     *
107
-     * @since 4.9.0
108
-     * @var EE_Message_Resource_Manager
109
-     */
110
-    public $MRM = null;
111
-
112
-
113
-    /**
114
-     * Holds the Assets Registry instance
115
-     * @var Registry
116
-     */
117
-    public $AssetsRegistry = null;
118
-
119
-    /**
120
-     *    $addons - StdClass object for holding addons which have registered themselves to work with EE core
121
-     *
122
-     * @access    public
123
-     * @var    EE_Addon[]
124
-     */
125
-    public $addons = null;
126
-
127
-    /**
128
-     *    $models
129
-     * @access    public
130
-     * @var    EEM_Base[] $models keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
131
-     */
132
-    public $models = array();
133
-
134
-    /**
135
-     *    $modules
136
-     * @access    public
137
-     * @var    EED_Module[] $modules
138
-     */
139
-    public $modules = null;
140
-
141
-    /**
142
-     *    $shortcodes
143
-     * @access    public
144
-     * @var    EES_Shortcode[] $shortcodes
145
-     */
146
-    public $shortcodes = null;
147
-
148
-    /**
149
-     *    $widgets
150
-     * @access    public
151
-     * @var    WP_Widget[] $widgets
152
-     */
153
-    public $widgets = null;
154
-
155
-    /**
156
-     * $non_abstract_db_models
157
-     * @access public
158
-     * @var array this is an array of all implemented model names (i.e. not the parent abstract models, or models
159
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
160
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
161
-     * classnames (eg "EEM_Event")
162
-     */
163
-    public $non_abstract_db_models = array();
164
-
165
-
166
-    /**
167
-     *    $i18n_js_strings - internationalization for JS strings
168
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = __( 'string to translate.', 'event_espresso' );
169
-     *    in js file:  var translatedString = eei18n.string_key;
170
-     *
171
-     * @access    public
172
-     * @var    array
173
-     */
174
-    public static $i18n_js_strings = array();
175
-
176
-
177
-    /**
178
-     *    $main_file - path to espresso.php
179
-     *
180
-     * @access    public
181
-     * @var    array
182
-     */
183
-    public $main_file;
184
-
185
-    /**
186
-     * array of ReflectionClass objects where the key is the class name
187
-     *
188
-     * @access    public
189
-     * @var ReflectionClass[]
190
-     */
191
-    public $_reflectors;
192
-
193
-    /**
194
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
195
-     *
196
-     * @access    protected
197
-     * @var boolean $_cache_on
198
-     */
199
-    protected $_cache_on = true;
200
-
201
-
202
-
203
-    /**
204
-     * @singleton method used to instantiate class object
205
-     * @access    public
206
-     * @param  \EE_Dependency_Map $dependency_map
207
-     * @return \EE_Registry instance
208
-     */
209
-    public static function instance(\EE_Dependency_Map $dependency_map = null)
210
-    {
211
-        // check if class object is instantiated
212
-        if ( ! self::$_instance instanceof EE_Registry) {
213
-            self::$_instance = new EE_Registry($dependency_map);
214
-        }
215
-        return self::$_instance;
216
-    }
217
-
218
-
219
-
220
-    /**
221
-     *protected constructor to prevent direct creation
222
-     *
223
-     * @Constructor
224
-     * @access protected
225
-     * @param  \EE_Dependency_Map $dependency_map
226
-     */
227
-    protected function __construct(\EE_Dependency_Map $dependency_map)
228
-    {
229
-        $this->_dependency_map = $dependency_map;
230
-        $this->LIB = new stdClass();
231
-        $this->addons = new stdClass();
232
-        $this->modules = new stdClass();
233
-        $this->shortcodes = new stdClass();
234
-        $this->widgets = new stdClass();
235
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
236
-    }
237
-
238
-
239
-
240
-    /**
241
-     * initialize
242
-     */
243
-    public function initialize()
244
-    {
245
-        $this->_class_abbreviations = apply_filters(
246
-            'FHEE__EE_Registry____construct___class_abbreviations',
247
-            array(
248
-                'EE_Config'                                       => 'CFG',
249
-                'EE_Session'                                      => 'SSN',
250
-                'EE_Capabilities'                                 => 'CAP',
251
-                'EE_Cart'                                         => 'CART',
252
-                'EE_Network_Config'                               => 'NET_CFG',
253
-                'EE_Request_Handler'                              => 'REQ',
254
-                'EE_Message_Resource_Manager'                     => 'MRM',
255
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
256
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
257
-            )
258
-        );
259
-        $this->load_core('Base', array(), true);
260
-        // add our request and response objects to the cache
261
-        $request_loader = $this->_dependency_map->class_loader('EE_Request');
262
-        $this->_set_cached_class(
263
-            $request_loader(),
264
-            'EE_Request'
265
-        );
266
-        $response_loader = $this->_dependency_map->class_loader('EE_Response');
267
-        $this->_set_cached_class(
268
-            $response_loader(),
269
-            'EE_Response'
270
-        );
271
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
272
-    }
273
-
274
-
275
-
276
-    /**
277
-     *    init
278
-     *
279
-     * @access    public
280
-     * @return    void
281
-     */
282
-    public function init()
283
-    {
284
-        // Get current page protocol
285
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
286
-        // Output admin-ajax.php URL with same protocol as current page
287
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
288
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
289
-    }
290
-
291
-
292
-
293
-    /**
294
-     * localize_i18n_js_strings
295
-     *
296
-     * @return string
297
-     */
298
-    public static function localize_i18n_js_strings()
299
-    {
300
-        $i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
301
-        foreach ($i18n_js_strings as $key => $value) {
302
-            if (is_scalar($value)) {
303
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
304
-            }
305
-        }
306
-        return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
307
-    }
308
-
309
-
310
-
311
-    /**
312
-     * @param mixed string | EED_Module $module
313
-     */
314
-    public function add_module($module)
315
-    {
316
-        if ($module instanceof EED_Module) {
317
-            $module_class = get_class($module);
318
-            $this->modules->{$module_class} = $module;
319
-        } else {
320
-            if ( ! class_exists('EE_Module_Request_Router')) {
321
-                $this->load_core('Module_Request_Router');
322
-            }
323
-            $this->modules->{$module} = EE_Module_Request_Router::module_factory($module);
324
-        }
325
-    }
326
-
327
-
328
-
329
-    /**
330
-     * @param string $module_name
331
-     * @return mixed EED_Module | NULL
332
-     */
333
-    public function get_module($module_name = '')
334
-    {
335
-        return isset($this->modules->{$module_name}) ? $this->modules->{$module_name} : null;
336
-    }
337
-
338
-
339
-
340
-    /**
341
-     *    loads core classes - must be singletons
342
-     *
343
-     * @access    public
344
-     * @param string $class_name - simple class name ie: session
345
-     * @param mixed  $arguments
346
-     * @param bool   $load_only
347
-     * @return mixed
348
-     */
349
-    public function load_core($class_name, $arguments = array(), $load_only = false)
350
-    {
351
-        $core_paths = apply_filters(
352
-            'FHEE__EE_Registry__load_core__core_paths',
353
-            array(
354
-                EE_CORE,
355
-                EE_ADMIN,
356
-                EE_CPTS,
357
-                EE_CORE . 'data_migration_scripts' . DS,
358
-                EE_CORE . 'request_stack' . DS,
359
-                EE_CORE . 'middleware' . DS,
360
-            )
361
-        );
362
-        // retrieve instantiated class
363
-        return $this->_load($core_paths, 'EE_', $class_name, 'core', $arguments, false, true, $load_only);
364
-    }
365
-
366
-
367
-
368
-    /**
369
-     *    loads service classes
370
-     *
371
-     * @access    public
372
-     * @param string $class_name - simple class name ie: session
373
-     * @param mixed  $arguments
374
-     * @param bool   $load_only
375
-     * @return mixed
376
-     */
377
-    public function load_service($class_name, $arguments = array(), $load_only = false)
378
-    {
379
-        $service_paths = apply_filters(
380
-            'FHEE__EE_Registry__load_service__service_paths',
381
-            array(
382
-                EE_CORE . 'services' . DS,
383
-            )
384
-        );
385
-        // retrieve instantiated class
386
-        return $this->_load($service_paths, 'EE_', $class_name, 'class', $arguments, false, true, $load_only);
387
-    }
388
-
389
-
390
-
391
-    /**
392
-     *    loads data_migration_scripts
393
-     *
394
-     * @access    public
395
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
396
-     * @param mixed  $arguments
397
-     * @return EE_Data_Migration_Script_Base|mixed
398
-     */
399
-    public function load_dms($class_name, $arguments = array())
400
-    {
401
-        // retrieve instantiated class
402
-        return $this->_load(EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(), 'EE_DMS_', $class_name, 'dms', $arguments, false, false, false);
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     *    loads object creating classes - must be singletons
409
-     *
410
-     * @param string $class_name - simple class name ie: attendee
411
-     * @param mixed  $arguments  - an array of arguments to pass to the class
412
-     * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to instantiate
413
-     * @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)
414
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate (default)
415
-     * @return EE_Base_Class | bool
416
-     */
417
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
418
-    {
419
-        $paths = apply_filters('FHEE__EE_Registry__load_class__paths', array(
420
-            EE_CORE,
421
-            EE_CLASSES,
422
-            EE_BUSINESS,
423
-        ));
424
-        // retrieve instantiated class
425
-        return $this->_load($paths, 'EE_', $class_name, 'class', $arguments, $from_db, $cache, $load_only);
426
-    }
427
-
428
-
429
-
430
-    /**
431
-     *    loads helper classes - must be singletons
432
-     *
433
-     * @param string $class_name - simple class name ie: price
434
-     * @param mixed  $arguments
435
-     * @param bool   $load_only
436
-     * @return EEH_Base | bool
437
-     */
438
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
439
-    {
440
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
441
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
442
-        // retrieve instantiated class
443
-        return $this->_load($helper_paths, 'EEH_', $class_name, 'helper', $arguments, false, true, $load_only);
444
-    }
445
-
446
-
447
-
448
-    /**
449
-     *    loads core classes - must be singletons
450
-     *
451
-     * @access    public
452
-     * @param string $class_name - simple class name ie: session
453
-     * @param mixed  $arguments
454
-     * @param bool   $load_only
455
-     * @param bool   $cache      whether to cache the object or not.
456
-     * @return mixed
457
-     */
458
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
459
-    {
460
-        $paths = array(
461
-            EE_LIBRARIES,
462
-            EE_LIBRARIES . 'messages' . DS,
463
-            EE_LIBRARIES . 'shortcodes' . DS,
464
-            EE_LIBRARIES . 'qtips' . DS,
465
-            EE_LIBRARIES . 'payment_methods' . DS,
466
-        );
467
-        // retrieve instantiated class
468
-        return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, false, $cache, $load_only);
469
-    }
470
-
471
-
472
-
473
-    /**
474
-     *    loads model classes - must be singletons
475
-     *
476
-     * @param string $class_name - simple class name ie: price
477
-     * @param mixed  $arguments
478
-     * @param bool   $load_only
479
-     * @return EEM_Base | bool
480
-     */
481
-    public function load_model($class_name, $arguments = array(), $load_only = false)
482
-    {
483
-        $paths = apply_filters('FHEE__EE_Registry__load_model__paths', array(
484
-            EE_MODELS,
485
-            EE_CORE,
486
-        ));
487
-        // retrieve instantiated class
488
-        return $this->_load($paths, 'EEM_', $class_name, 'model', $arguments, false, true, $load_only);
489
-    }
490
-
491
-
492
-
493
-    /**
494
-     *    loads model classes - must be singletons
495
-     *
496
-     * @param string $class_name - simple class name ie: price
497
-     * @param mixed  $arguments
498
-     * @param bool   $load_only
499
-     * @return mixed | bool
500
-     */
501
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
502
-    {
503
-        $paths = array(
504
-            EE_MODELS . 'fields' . DS,
505
-            EE_MODELS . 'helpers' . DS,
506
-            EE_MODELS . 'relations' . DS,
507
-            EE_MODELS . 'strategies' . DS,
508
-        );
509
-        // retrieve instantiated class
510
-        return $this->_load($paths, 'EE_', $class_name, '', $arguments, false, true, $load_only);
511
-    }
512
-
513
-
514
-
515
-    /**
516
-     * Determines if $model_name is the name of an actual EE model.
517
-     *
518
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
519
-     * @return boolean
520
-     */
521
-    public function is_model_name($model_name)
522
-    {
523
-        return isset($this->models[$model_name]) ? true : false;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     *    generic class loader
530
-     *
531
-     * @param string $path_to_file - directory path to file location, not including filename
532
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
533
-     * @param string $type         - file type - core? class? helper? model?
534
-     * @param mixed  $arguments
535
-     * @param bool   $load_only
536
-     * @return mixed
537
-     */
538
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
539
-    {
540
-        // retrieve instantiated class
541
-        return $this->_load($path_to_file, '', $file_name, $type, $arguments, false, true, $load_only);
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     *    load_addon
548
-     *
549
-     * @param string $path_to_file - directory path to file location, not including filename
550
-     * @param string $class_name   - full class name  ie:  My_Class
551
-     * @param string $type         - file type - core? class? helper? model?
552
-     * @param mixed  $arguments
553
-     * @param bool   $load_only
554
-     * @return EE_Addon
555
-     */
556
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
557
-    {
558
-        // retrieve instantiated class
559
-        return $this->_load($path_to_file, 'addon', $class_name, $type, $arguments, false, true, $load_only);
560
-    }
561
-
562
-
563
-
564
-    /**
565
-     * instantiates, caches, and automatically resolves dependencies
566
-     * for classes that use a Fully Qualified Class Name.
567
-     * if the class is not capable of being loaded using PSR-4 autoloading,
568
-     * then you need to use one of the existing load_*() methods
569
-     * which can resolve the classname and filepath from the passed arguments
570
-     *
571
-     * @param bool|string $class_name   Fully Qualified Class Name
572
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
573
-     * @param bool        $cache        whether to cache the instantiated object for reuse
574
-     * @param bool        $from_db      some classes are instantiated from the db
575
-     *                                  and thus call a different method to instantiate
576
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
577
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
578
-     * @return mixed                    null = failure to load or instantiate class object.
579
-     *                                  object = class loaded and instantiated successfully.
580
-     *                                  bool = fail or success when $load_only is true
581
-     */
582
-    public function create(
583
-        $class_name = false,
584
-        $arguments = array(),
585
-        $cache = false,
586
-        $from_db = false,
587
-        $load_only = false,
588
-        $addon = false
589
-    ) {
590
-        $class_name = ltrim($class_name, '\\');
591
-        $class_name = $this->_dependency_map->get_alias($class_name);
592
-        if ( ! class_exists($class_name)) {
593
-            // maybe the class is registered with a preceding \
594
-            $class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
595
-            // still doesn't exist ?
596
-            if ( ! class_exists($class_name)) {
597
-                return null;
598
-            }
599
-        }
600
-        // if we're only loading the class and it already exists, then let's just return true immediately
601
-        if ($load_only) {
602
-            return true;
603
-        }
604
-        $addon = $addon ? 'addon' : '';
605
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
606
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
607
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
608
-        if ($this->_cache_on && $cache && ! $load_only) {
609
-            // return object if it's already cached
610
-            $cached_class = $this->_get_cached_class($class_name, $addon);
611
-            if ($cached_class !== null) {
612
-                return $cached_class;
613
-            }
614
-        }
615
-        // instantiate the requested object
616
-        $class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
617
-        if ($this->_cache_on && $cache) {
618
-            // save it for later... kinda like gum  { : $
619
-            $this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
620
-        }
621
-        $this->_cache_on = true;
622
-        return $class_obj;
623
-    }
624
-
625
-
626
-
627
-    /**
628
-     * instantiates, caches, and injects dependencies for classes
629
-     *
630
-     * @param array       $file_paths   an array of paths to folders to look in
631
-     * @param string      $class_prefix EE  or EEM or... ???
632
-     * @param bool|string $class_name   $class name
633
-     * @param string      $type         file type - core? class? helper? model?
634
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
635
-     * @param bool        $from_db      some classes are instantiated from the db
636
-     *                                  and thus call a different method to instantiate
637
-     * @param bool        $cache        whether to cache the instantiated object for reuse
638
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
639
-     * @return null|object|bool         null = failure to load or instantiate class object.
640
-     *                                  object = class loaded and instantiated successfully.
641
-     *                                  bool = fail or success when $load_only is true
642
-     */
643
-    protected function _load(
644
-        $file_paths = array(),
645
-        $class_prefix = 'EE_',
646
-        $class_name = false,
647
-        $type = 'class',
648
-        $arguments = array(),
649
-        $from_db = false,
650
-        $cache = true,
651
-        $load_only = false
652
-    ) {
653
-        $class_name = ltrim($class_name, '\\');
654
-        // strip php file extension
655
-        $class_name = str_replace('.php', '', trim($class_name));
656
-        // does the class have a prefix ?
657
-        if ( ! empty($class_prefix) && $class_prefix != 'addon') {
658
-            // make sure $class_prefix is uppercase
659
-            $class_prefix = strtoupper(trim($class_prefix));
660
-            // add class prefix ONCE!!!
661
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
662
-        }
663
-        $class_name = $this->_dependency_map->get_alias($class_name);
664
-        $class_exists = class_exists($class_name);
665
-        // if we're only loading the class and it already exists, then let's just return true immediately
666
-        if ($load_only && $class_exists) {
667
-            return true;
668
-        }
669
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
670
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
671
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
672
-        if ($this->_cache_on && $cache && ! $load_only) {
673
-            // return object if it's already cached
674
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix);
675
-            if ($cached_class !== null) {
676
-                return $cached_class;
677
-            }
678
-        }
679
-        // if the class doesn't already exist.. then we need to try and find the file and load it
680
-        if ( ! $class_exists) {
681
-            // get full path to file
682
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
683
-            // load the file
684
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
685
-            // if loading failed, or we are only loading a file but NOT instantiating an object
686
-            if ( ! $loaded || $load_only) {
687
-                // return boolean if only loading, or null if an object was expected
688
-                return $load_only ? $loaded : null;
689
-            }
690
-        }
691
-        // instantiate the requested object
692
-        $class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
693
-        if ($this->_cache_on && $cache) {
694
-            // save it for later... kinda like gum  { : $
695
-            $this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
696
-        }
697
-        $this->_cache_on = true;
698
-        return $class_obj;
699
-    }
700
-
701
-
702
-
703
-
704
-    /**
705
-     * _get_cached_class
706
-     * attempts to find a cached version of the requested class
707
-     * by looking in the following places:
708
-     *        $this->{$class_abbreviation}            ie:    $this->CART
709
-     *        $this->{$class_name}                        ie:    $this->Some_Class
710
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
711
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
712
-     *
713
-     * @access protected
714
-     * @param string $class_name
715
-     * @param string $class_prefix
716
-     * @return mixed
717
-     */
718
-    protected function _get_cached_class($class_name, $class_prefix = '')
719
-    {
720
-        if ($class_name === 'EE_Registry') {
721
-            return $this;
722
-        }
723
-        // have to specify something, but not anything that will conflict
724
-        $class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
725
-            ? $this->_class_abbreviations[ $class_name ]
726
-            : 'FANCY_BATMAN_PANTS';
727
-        $class_name = str_replace('\\', '_', $class_name);
728
-        // check if class has already been loaded, and return it if it has been
729
-        if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
730
-            return $this->{$class_abbreviation};
731
-        }
732
-        if (isset ($this->{$class_name})) {
733
-            return $this->{$class_name};
734
-        }
735
-        if (isset ($this->LIB->{$class_name})) {
736
-            return $this->LIB->{$class_name};
737
-        }
738
-        if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
739
-            return $this->addons->{$class_name};
740
-        }
741
-        return null;
742
-    }
743
-
744
-
745
-
746
-    /**
747
-     * removes a cached version of the requested class
748
-     *
749
-     * @param string $class_name
750
-     * @param boolean $addon
751
-     * @return boolean
752
-     */
753
-    public function clear_cached_class($class_name, $addon = false)
754
-    {
755
-        // have to specify something, but not anything that will conflict
756
-        $class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
757
-            ? $this->_class_abbreviations[ $class_name ]
758
-            : 'FANCY_BATMAN_PANTS';
759
-        $class_name = str_replace('\\', '_', $class_name);
760
-        // check if class has already been loaded, and return it if it has been
761
-        if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
762
-            $this->{$class_abbreviation} = null;
763
-            return true;
764
-        }
765
-        if (isset($this->{$class_name})) {
766
-            $this->{$class_name} = null;
767
-            return true;
768
-        }
769
-        if (isset($this->LIB->{$class_name})) {
770
-            unset($this->LIB->{$class_name});
771
-            return true;
772
-        }
773
-        if ($addon && isset($this->addons->{$class_name})) {
774
-            unset($this->addons->{$class_name});
775
-            return true;
776
-        }
777
-        return false;
778
-    }
779
-
780
-
781
-    /**
782
-     * _resolve_path
783
-     * attempts to find a full valid filepath for the requested class.
784
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
785
-     * then returns that path if the target file has been found and is readable
786
-     *
787
-     * @access protected
788
-     * @param string $class_name
789
-     * @param string $type
790
-     * @param array  $file_paths
791
-     * @return string | bool
792
-     */
793
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
794
-    {
795
-        // make sure $file_paths is an array
796
-        $file_paths = is_array($file_paths) ? $file_paths : array($file_paths);
797
-        // cycle thru paths
798
-        foreach ($file_paths as $key => $file_path) {
799
-            // convert all separators to proper DS, if no filepath, then use EE_CLASSES
800
-            $file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
801
-            // prep file type
802
-            $type = ! empty($type) ? trim($type, '.') . '.' : '';
803
-            // build full file path
804
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
805
-            //does the file exist and can be read ?
806
-            if (is_readable($file_paths[$key])) {
807
-                return $file_paths[$key];
808
-            }
809
-        }
810
-        return false;
811
-    }
812
-
813
-
814
-
815
-    /**
816
-     * _require_file
817
-     * basically just performs a require_once()
818
-     * but with some error handling
819
-     *
820
-     * @access protected
821
-     * @param  string $path
822
-     * @param  string $class_name
823
-     * @param  string $type
824
-     * @param  array  $file_paths
825
-     * @return boolean
826
-     * @throws \EE_Error
827
-     */
828
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
829
-    {
830
-        // don't give up! you gotta...
831
-        try {
832
-            //does the file exist and can it be read ?
833
-            if ( ! $path) {
834
-                // so sorry, can't find the file
835
-                throw new EE_Error (
836
-                    sprintf(
837
-                        __('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'),
838
-                        trim($type, '.'),
839
-                        $class_name,
840
-                        '<br />' . implode(',<br />', $file_paths)
841
-                    )
842
-                );
843
-            }
844
-            // get the file
845
-            require_once($path);
846
-            // if the class isn't already declared somewhere
847
-            if (class_exists($class_name, false) === false) {
848
-                // so sorry, not a class
849
-                throw new EE_Error(
850
-                    sprintf(
851
-                        __('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
852
-                        $type,
853
-                        $path,
854
-                        $class_name
855
-                    )
856
-                );
857
-            }
858
-        } catch (EE_Error $e) {
859
-            $e->get_error();
860
-            return false;
861
-        }
862
-        return true;
863
-    }
864
-
865
-
866
-
867
-    /**
868
-     * _create_object
869
-     * Attempts to instantiate the requested class via any of the
870
-     * commonly used instantiation methods employed throughout EE.
871
-     * The priority for instantiation is as follows:
872
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
873
-     *        - model objects via their 'new_instance_from_db' method
874
-     *        - model objects via their 'new_instance' method
875
-     *        - "singleton" classes" via their 'instance' method
876
-     *    - standard instantiable classes via their __constructor
877
-     * Prior to instantiation, if the classname exists in the dependency_map,
878
-     * then the constructor for the requested class will be examined to determine
879
-     * if any dependencies exist, and if they can be injected.
880
-     * If so, then those classes will be added to the array of arguments passed to the constructor
881
-     *
882
-     * @access protected
883
-     * @param string $class_name
884
-     * @param array  $arguments
885
-     * @param string $type
886
-     * @param bool   $from_db
887
-     * @return null | object
888
-     * @throws \EE_Error
889
-     */
890
-    protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
891
-    {
892
-        $class_obj = null;
893
-        $instantiation_mode = '0) none';
894
-        // don't give up! you gotta...
895
-        try {
896
-            // create reflection
897
-            $reflector = $this->get_ReflectionClass($class_name);
898
-            // make sure arguments are an array
899
-            $arguments = is_array($arguments) ? $arguments : array($arguments);
900
-            // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
901
-            // else wrap it in an additional array so that it doesn't get split into multiple parameters
902
-            $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
903
-                ? $arguments
904
-                : array($arguments);
905
-            // attempt to inject dependencies ?
906
-            if ($this->_dependency_map->has($class_name)) {
907
-                $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
908
-            }
909
-            // instantiate the class if possible
910
-            if ($reflector->isAbstract()) {
911
-                // nothing to instantiate, loading file was enough
912
-                // does not throw an exception so $instantiation_mode is unused
913
-                // $instantiation_mode = "1) no constructor abstract class";
914
-                $class_obj = true;
915
-            } else if ($reflector->getConstructor() === null && $reflector->isInstantiable() && empty($arguments)) {
916
-                // no constructor = static methods only... nothing to instantiate, loading file was enough
917
-                $instantiation_mode = "2) no constructor but instantiable";
918
-                $class_obj = $reflector->newInstance();
919
-            } else if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
920
-                $instantiation_mode = "3) new_instance_from_db()";
921
-                $class_obj = call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
922
-            } else if (method_exists($class_name, 'new_instance')) {
923
-                $instantiation_mode = "4) new_instance()";
924
-                $class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
925
-            } else if (method_exists($class_name, 'instance')) {
926
-                $instantiation_mode = "5) instance()";
927
-                $class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
928
-            } else if ($reflector->isInstantiable()) {
929
-                $instantiation_mode = "6) constructor";
930
-                $class_obj = $reflector->newInstanceArgs($arguments);
931
-            } else {
932
-                // heh ? something's not right !
933
-                throw new EE_Error(
934
-                    sprintf(
935
-                        __('The %s file %s could not be instantiated.', 'event_espresso'),
936
-                        $type,
937
-                        $class_name
938
-                    )
939
-                );
940
-            }
941
-        } catch (Exception $e) {
942
-            if ( ! $e instanceof EE_Error) {
943
-                $e = new EE_Error(
944
-                    sprintf(
945
-                        __('The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s', 'event_espresso'),
946
-                        $class_name,
947
-                        '<br />',
948
-                        $e->getMessage(),
949
-                        $instantiation_mode
950
-                    )
951
-                );
952
-            }
953
-            $e->get_error();
954
-        }
955
-        return $class_obj;
956
-    }
957
-
958
-
959
-
960
-    /**
961
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
962
-     * @param array $array
963
-     * @return bool
964
-     */
965
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
966
-    {
967
-        return ! empty($array) ? array_keys($array) === range(0, count($array) - 1) : true;
968
-    }
969
-
970
-
971
-
972
-    /**
973
-     * getReflectionClass
974
-     * checks if a ReflectionClass object has already been generated for a class
975
-     * and returns that instead of creating a new one
976
-     *
977
-     * @access public
978
-     * @param string $class_name
979
-     * @return ReflectionClass
980
-     */
981
-    public function get_ReflectionClass($class_name)
982
-    {
983
-        if (
984
-            ! isset($this->_reflectors[$class_name])
985
-            || ! $this->_reflectors[$class_name] instanceof ReflectionClass
986
-        ) {
987
-            $this->_reflectors[$class_name] = new ReflectionClass($class_name);
988
-        }
989
-        return $this->_reflectors[$class_name];
990
-    }
991
-
992
-
993
-
994
-    /**
995
-     * _resolve_dependencies
996
-     * examines the constructor for the requested class to determine
997
-     * if any dependencies exist, and if they can be injected.
998
-     * If so, then those classes will be added to the array of arguments passed to the constructor
999
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1000
-     * For example:
1001
-     *        if attempting to load a class "Foo" with the following constructor:
1002
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1003
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1004
-     *        but only IF they are NOT already present in the incoming arguments array,
1005
-     *        and the correct classes can be loaded
1006
-     *
1007
-     * @access protected
1008
-     * @param ReflectionClass $reflector
1009
-     * @param string          $class_name
1010
-     * @param array           $arguments
1011
-     * @return array
1012
-     * @throws \ReflectionException
1013
-     */
1014
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1015
-    {
1016
-        // let's examine the constructor
1017
-        $constructor = $reflector->getConstructor();
1018
-        // whu? huh? nothing?
1019
-        if ( ! $constructor) {
1020
-            return $arguments;
1021
-        }
1022
-        // get constructor parameters
1023
-        $params = $constructor->getParameters();
1024
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1025
-        $argument_keys = array_keys($arguments);
1026
-        // now loop thru all of the constructors expected parameters
1027
-        foreach ($params as $index => $param) {
1028
-            // is this a dependency for a specific class ?
1029
-            $param_class = $param->getClass() ? $param->getClass()->name : null;
1030
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1031
-            $param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1032
-                ? $this->_dependency_map->get_alias($param_class, $class_name)
1033
-                : $param_class;
1034
-            if (
1035
-                // param is not even a class
1036
-                empty($param_class)
1037
-                // and something already exists in the incoming arguments for this param
1038
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1039
-            ) {
1040
-                // so let's skip this argument and move on to the next
1041
-                continue;
1042
-            }
1043
-            if (
1044
-                // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1045
-                ! empty($param_class)
1046
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1047
-                && $arguments[$argument_keys[$index]] instanceof $param_class
1048
-            ) {
1049
-                // skip this argument and move on to the next
1050
-                continue;
1051
-            }
1052
-            if (
1053
-                // parameter is type hinted as a class, and should be injected
1054
-                ! empty($param_class)
1055
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1056
-            ) {
1057
-                $arguments = $this->_resolve_dependency($class_name, $param_class, $arguments, $index);
1058
-            } else {
1059
-                try {
1060
-                    $arguments[$index] = $param->getDefaultValue();
1061
-                } catch (ReflectionException $e) {
1062
-                    throw new ReflectionException(
1063
-                        sprintf(
1064
-                            __('%1$s for parameter "$%2$s"', 'event_espresso'),
1065
-                            $e->getMessage(),
1066
-                            $param->getName()
1067
-                        )
1068
-                    );
1069
-                }
1070
-            }
1071
-        }
1072
-        return $arguments;
1073
-    }
1074
-
1075
-
1076
-
1077
-    /**
1078
-     * @access protected
1079
-     * @param string $class_name
1080
-     * @param string $param_class
1081
-     * @param array  $arguments
1082
-     * @param mixed  $index
1083
-     * @return array
1084
-     */
1085
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1086
-    {
1087
-        $dependency = null;
1088
-        // should dependency be loaded from cache ?
1089
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $param_class)
1090
-                    !== EE_Dependency_Map::load_new_object
1091
-            ? true
1092
-            : false;
1093
-        // we might have a dependency...
1094
-        // let's MAYBE try and find it in our cache if that's what's been requested
1095
-        $cached_class = $cache_on ? $this->_get_cached_class($param_class) : null;
1096
-        // and grab it if it exists
1097
-        if ($cached_class instanceof $param_class) {
1098
-            $dependency = $cached_class;
1099
-        } else if ($param_class !== $class_name) {
1100
-            // obtain the loader method from the dependency map
1101
-            $loader = $this->_dependency_map->class_loader($param_class);
1102
-            // is loader a custom closure ?
1103
-            if ($loader instanceof Closure) {
1104
-                $dependency = $loader();
1105
-            } else {
1106
-                // set the cache on property for the recursive loading call
1107
-                $this->_cache_on = $cache_on;
1108
-                // if not, then let's try and load it via the registry
1109
-                if ($loader && method_exists($this, $loader)) {
1110
-                    $dependency = $this->{$loader}($param_class);
1111
-                } else {
1112
-                    $dependency = $this->create($param_class, array(), $cache_on);
1113
-                }
1114
-            }
1115
-        }
1116
-        // did we successfully find the correct dependency ?
1117
-        if ($dependency instanceof $param_class) {
1118
-            // then let's inject it into the incoming array of arguments at the correct location
1119
-            if (isset($argument_keys[$index])) {
1120
-                $arguments[$argument_keys[$index]] = $dependency;
1121
-            } else {
1122
-                $arguments[$index] = $dependency;
1123
-            }
1124
-        }
1125
-        return $arguments;
1126
-    }
1127
-
1128
-
1129
-
1130
-    /**
1131
-     * _set_cached_class
1132
-     * attempts to cache the instantiated class locally
1133
-     * in one of the following places, in the following order:
1134
-     *        $this->{class_abbreviation}   ie:    $this->CART
1135
-     *        $this->{$class_name}          ie:    $this->Some_Class
1136
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1137
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1138
-     *
1139
-     * @access protected
1140
-     * @param object $class_obj
1141
-     * @param string $class_name
1142
-     * @param string $class_prefix
1143
-     * @param bool   $from_db
1144
-     * @return void
1145
-     */
1146
-    protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1147
-    {
1148
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1149
-            return;
1150
-        }
1151
-        // return newly instantiated class
1152
-        if (isset($this->_class_abbreviations[$class_name])) {
1153
-            $class_abbreviation = $this->_class_abbreviations[$class_name];
1154
-            $this->{$class_abbreviation} = $class_obj;
1155
-            return;
1156
-        }
1157
-        $class_name = str_replace('\\', '_', $class_name);
1158
-        if (property_exists($this, $class_name)) {
1159
-            $this->{$class_name} = $class_obj;
1160
-            return;
1161
-        }
1162
-        if ($class_prefix === 'addon') {
1163
-            $this->addons->{$class_name} = $class_obj;
1164
-            return;
1165
-        }
1166
-        if ( ! $from_db) {
1167
-            $this->LIB->{$class_name} = $class_obj;
1168
-        }
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1175
-     *
1176
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1177
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1178
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1179
-     * @param array  $arguments
1180
-     * @return object
1181
-     */
1182
-    public static function factory($classname, $arguments = array())
1183
-    {
1184
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1185
-        if ($loader instanceof Closure) {
1186
-            return $loader($arguments);
1187
-        }
1188
-        if (method_exists(EE_Registry::instance(), $loader)) {
1189
-            return EE_Registry::instance()->{$loader}($classname, $arguments);
1190
-        }
1191
-        return null;
1192
-    }
1193
-
1194
-
1195
-
1196
-    /**
1197
-     * Gets the addon by its name/slug (not classname. For that, just
1198
-     * use the classname as the property name on EE_Config::instance()->addons)
1199
-     *
1200
-     * @param string $name
1201
-     * @return EE_Addon
1202
-     */
1203
-    public function get_addon_by_name($name)
1204
-    {
1205
-        foreach ($this->addons as $addon) {
1206
-            if ($addon->name() == $name) {
1207
-                return $addon;
1208
-            }
1209
-        }
1210
-        return null;
1211
-    }
1212
-
1213
-
1214
-
1215
-    /**
1216
-     * 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
1217
-     * the addon's classname. So if you just want to get the addon by classname, use EE_Config::instance()->addons->{classname}
1218
-     *
1219
-     * @return EE_Addon[] where the KEYS are the addon's name()
1220
-     */
1221
-    public function get_addons_by_name()
1222
-    {
1223
-        $addons = array();
1224
-        foreach ($this->addons as $addon) {
1225
-            $addons[$addon->name()] = $addon;
1226
-        }
1227
-        return $addons;
1228
-    }
1229
-
1230
-
1231
-
1232
-    /**
1233
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1234
-     * a stale copy of it around
1235
-     *
1236
-     * @param string $model_name
1237
-     * @return \EEM_Base
1238
-     * @throws \EE_Error
1239
-     */
1240
-    public function reset_model($model_name)
1241
-    {
1242
-        $model_class_name = strpos($model_name, 'EEM_') !== 0 ? "EEM_{$model_name}" : $model_name;
1243
-        if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1244
-            return null;
1245
-        }
1246
-        //get that model reset it and make sure we nuke the old reference to it
1247
-        if ($this->LIB->{$model_class_name} instanceof $model_class_name && is_callable(array($model_class_name, 'reset'))) {
1248
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1249
-        } else {
1250
-            throw new EE_Error(sprintf(__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1251
-        }
1252
-        return $this->LIB->{$model_class_name};
1253
-    }
1254
-
1255
-
1256
-
1257
-    /**
1258
-     * Resets the registry.
1259
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when switch_to_blog
1260
-     * is used in a multisite install.  Here is a list of things that are NOT reset.
1261
-     * - $_dependency_map
1262
-     * - $_class_abbreviations
1263
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1264
-     * - $REQ:  Still on the same request so no need to change.
1265
-     * - $CAP: There is no site specific state in the EE_Capability class.
1266
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only one Session
1267
-     *         can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1268
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1269
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1270
-     *             switch or on the restore.
1271
-     * - $modules
1272
-     * - $shortcodes
1273
-     * - $widgets
1274
-     *
1275
-     * @param boolean $hard             whether to reset data in the database too, or just refresh
1276
-     *                                  the Registry to its state at the beginning of the request
1277
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1278
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not sure if you CAN
1279
-     *                                  currently reinstantiate the singletons at the moment)
1280
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so client
1281
-     *                                  code instead can just change the model context to a different blog id if necessary
1282
-     * @return EE_Registry
1283
-     */
1284
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1285
-    {
1286
-        $instance = self::instance();
1287
-        $instance->_cache_on = true;
1288
-        // reset some "special" classes
1289
-        EEH_Activation::reset();
1290
-        $instance->CFG = $instance->CFG->reset($hard, $reinstantiate);
1291
-        $instance->CART = null;
1292
-        $instance->MRM = null;
1293
-        $instance->AssetsRegistry = null;
1294
-        $instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1295
-        //messages reset
1296
-        EED_Messages::reset();
1297
-        //handle of objects cached on LIB
1298
-        foreach (array('LIB', 'modules', 'shortcodes') as $cache) {
1299
-            foreach ($instance->{$cache} as $class_name => $class) {
1300
-                if (EE_Registry::_reset_and_unset_object($class, $reset_models)) {
1301
-                    unset($instance->{$cache}->{$class_name});
1302
-                }
1303
-            }
1304
-        }
1305
-        return $instance;
1306
-    }
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * if passed object implements ResettableInterface, then call it's reset() method
1312
-     * if passed object implements InterminableInterface, then return false,
1313
-     * to indicate that it should NOT be cleared from the Registry cache
1314
-     *
1315
-     * @param      $object
1316
-     * @param bool $reset_models
1317
-     * @return bool returns true if cached object should be unset
1318
-     */
1319
-    private static function _reset_and_unset_object($object, $reset_models)
1320
-    {
1321
-        static $count = 0;
1322
-        $count++;
1323
-        if ($object instanceof ResettableInterface) {
1324
-            if ($object instanceof EEM_Base) {
1325
-                if ($reset_models) {
1326
-                    $object->reset();
1327
-                    return true;
1328
-                }
1329
-                return false;
1330
-            }
1331
-            $object->reset();
1332
-            return true;
1333
-        }
1334
-        if ( ! $object instanceof InterminableInterface) {
1335
-            return true;
1336
-        }
1337
-        return false;
1338
-    }
1339
-
1340
-
1341
-
1342
-    /**
1343
-     * @override magic methods
1344
-     * @return void
1345
-     */
1346
-    public final function __destruct()
1347
-    {
1348
-    }
1349
-
1350
-
1351
-
1352
-    /**
1353
-     * @param $a
1354
-     * @param $b
1355
-     */
1356
-    public final function __call($a, $b)
1357
-    {
1358
-    }
1359
-
1360
-
1361
-
1362
-    /**
1363
-     * @param $a
1364
-     */
1365
-    public final function __get($a)
1366
-    {
1367
-    }
1368
-
1369
-
1370
-
1371
-    /**
1372
-     * @param $a
1373
-     * @param $b
1374
-     */
1375
-    public final function __set($a, $b)
1376
-    {
1377
-    }
1378
-
1379
-
1380
-
1381
-    /**
1382
-     * @param $a
1383
-     */
1384
-    public final function __isset($a)
1385
-    {
1386
-    }
22
+	/**
23
+	 *    EE_Registry Object
24
+	 *
25
+	 * @var EE_Registry $_instance
26
+	 * @access    private
27
+	 */
28
+	private static $_instance = null;
29
+
30
+	/**
31
+	 * @var EE_Dependency_Map $_dependency_map
32
+	 * @access    protected
33
+	 */
34
+	protected $_dependency_map = null;
35
+
36
+	/**
37
+	 * @var array $_class_abbreviations
38
+	 * @access    protected
39
+	 */
40
+	protected $_class_abbreviations = array();
41
+
42
+	/**
43
+	 * @access public
44
+	 * @var \EventEspresso\core\services\commands\CommandBusInterface $BUS
45
+	 */
46
+	public $BUS;
47
+
48
+	/**
49
+	 *    EE_Cart Object
50
+	 *
51
+	 * @access    public
52
+	 * @var    EE_Cart $CART
53
+	 */
54
+	public $CART = null;
55
+
56
+	/**
57
+	 *    EE_Config Object
58
+	 *
59
+	 * @access    public
60
+	 * @var    EE_Config $CFG
61
+	 */
62
+	public $CFG = null;
63
+
64
+	/**
65
+	 * EE_Network_Config Object
66
+	 *
67
+	 * @access public
68
+	 * @var EE_Network_Config $NET_CFG
69
+	 */
70
+	public $NET_CFG = null;
71
+
72
+	/**
73
+	 *    StdClass object for storing library classes in
74
+	 *
75
+	 * @public LIB
76
+	 * @var StdClass $LIB
77
+	 */
78
+	public $LIB = null;
79
+
80
+	/**
81
+	 *    EE_Request_Handler Object
82
+	 *
83
+	 * @access    public
84
+	 * @var    EE_Request_Handler $REQ
85
+	 */
86
+	public $REQ = null;
87
+
88
+	/**
89
+	 *    EE_Session Object
90
+	 *
91
+	 * @access    public
92
+	 * @var    EE_Session $SSN
93
+	 */
94
+	public $SSN = null;
95
+
96
+	/**
97
+	 * holds the ee capabilities object.
98
+	 *
99
+	 * @since 4.5.0
100
+	 * @var EE_Capabilities
101
+	 */
102
+	public $CAP = null;
103
+
104
+	/**
105
+	 * holds the EE_Message_Resource_Manager object.
106
+	 *
107
+	 * @since 4.9.0
108
+	 * @var EE_Message_Resource_Manager
109
+	 */
110
+	public $MRM = null;
111
+
112
+
113
+	/**
114
+	 * Holds the Assets Registry instance
115
+	 * @var Registry
116
+	 */
117
+	public $AssetsRegistry = null;
118
+
119
+	/**
120
+	 *    $addons - StdClass object for holding addons which have registered themselves to work with EE core
121
+	 *
122
+	 * @access    public
123
+	 * @var    EE_Addon[]
124
+	 */
125
+	public $addons = null;
126
+
127
+	/**
128
+	 *    $models
129
+	 * @access    public
130
+	 * @var    EEM_Base[] $models keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
131
+	 */
132
+	public $models = array();
133
+
134
+	/**
135
+	 *    $modules
136
+	 * @access    public
137
+	 * @var    EED_Module[] $modules
138
+	 */
139
+	public $modules = null;
140
+
141
+	/**
142
+	 *    $shortcodes
143
+	 * @access    public
144
+	 * @var    EES_Shortcode[] $shortcodes
145
+	 */
146
+	public $shortcodes = null;
147
+
148
+	/**
149
+	 *    $widgets
150
+	 * @access    public
151
+	 * @var    WP_Widget[] $widgets
152
+	 */
153
+	public $widgets = null;
154
+
155
+	/**
156
+	 * $non_abstract_db_models
157
+	 * @access public
158
+	 * @var array this is an array of all implemented model names (i.e. not the parent abstract models, or models
159
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
160
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
161
+	 * classnames (eg "EEM_Event")
162
+	 */
163
+	public $non_abstract_db_models = array();
164
+
165
+
166
+	/**
167
+	 *    $i18n_js_strings - internationalization for JS strings
168
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = __( 'string to translate.', 'event_espresso' );
169
+	 *    in js file:  var translatedString = eei18n.string_key;
170
+	 *
171
+	 * @access    public
172
+	 * @var    array
173
+	 */
174
+	public static $i18n_js_strings = array();
175
+
176
+
177
+	/**
178
+	 *    $main_file - path to espresso.php
179
+	 *
180
+	 * @access    public
181
+	 * @var    array
182
+	 */
183
+	public $main_file;
184
+
185
+	/**
186
+	 * array of ReflectionClass objects where the key is the class name
187
+	 *
188
+	 * @access    public
189
+	 * @var ReflectionClass[]
190
+	 */
191
+	public $_reflectors;
192
+
193
+	/**
194
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
195
+	 *
196
+	 * @access    protected
197
+	 * @var boolean $_cache_on
198
+	 */
199
+	protected $_cache_on = true;
200
+
201
+
202
+
203
+	/**
204
+	 * @singleton method used to instantiate class object
205
+	 * @access    public
206
+	 * @param  \EE_Dependency_Map $dependency_map
207
+	 * @return \EE_Registry instance
208
+	 */
209
+	public static function instance(\EE_Dependency_Map $dependency_map = null)
210
+	{
211
+		// check if class object is instantiated
212
+		if ( ! self::$_instance instanceof EE_Registry) {
213
+			self::$_instance = new EE_Registry($dependency_map);
214
+		}
215
+		return self::$_instance;
216
+	}
217
+
218
+
219
+
220
+	/**
221
+	 *protected constructor to prevent direct creation
222
+	 *
223
+	 * @Constructor
224
+	 * @access protected
225
+	 * @param  \EE_Dependency_Map $dependency_map
226
+	 */
227
+	protected function __construct(\EE_Dependency_Map $dependency_map)
228
+	{
229
+		$this->_dependency_map = $dependency_map;
230
+		$this->LIB = new stdClass();
231
+		$this->addons = new stdClass();
232
+		$this->modules = new stdClass();
233
+		$this->shortcodes = new stdClass();
234
+		$this->widgets = new stdClass();
235
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
236
+	}
237
+
238
+
239
+
240
+	/**
241
+	 * initialize
242
+	 */
243
+	public function initialize()
244
+	{
245
+		$this->_class_abbreviations = apply_filters(
246
+			'FHEE__EE_Registry____construct___class_abbreviations',
247
+			array(
248
+				'EE_Config'                                       => 'CFG',
249
+				'EE_Session'                                      => 'SSN',
250
+				'EE_Capabilities'                                 => 'CAP',
251
+				'EE_Cart'                                         => 'CART',
252
+				'EE_Network_Config'                               => 'NET_CFG',
253
+				'EE_Request_Handler'                              => 'REQ',
254
+				'EE_Message_Resource_Manager'                     => 'MRM',
255
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
256
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
257
+			)
258
+		);
259
+		$this->load_core('Base', array(), true);
260
+		// add our request and response objects to the cache
261
+		$request_loader = $this->_dependency_map->class_loader('EE_Request');
262
+		$this->_set_cached_class(
263
+			$request_loader(),
264
+			'EE_Request'
265
+		);
266
+		$response_loader = $this->_dependency_map->class_loader('EE_Response');
267
+		$this->_set_cached_class(
268
+			$response_loader(),
269
+			'EE_Response'
270
+		);
271
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
272
+	}
273
+
274
+
275
+
276
+	/**
277
+	 *    init
278
+	 *
279
+	 * @access    public
280
+	 * @return    void
281
+	 */
282
+	public function init()
283
+	{
284
+		// Get current page protocol
285
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
286
+		// Output admin-ajax.php URL with same protocol as current page
287
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
288
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
289
+	}
290
+
291
+
292
+
293
+	/**
294
+	 * localize_i18n_js_strings
295
+	 *
296
+	 * @return string
297
+	 */
298
+	public static function localize_i18n_js_strings()
299
+	{
300
+		$i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
301
+		foreach ($i18n_js_strings as $key => $value) {
302
+			if (is_scalar($value)) {
303
+				$i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
304
+			}
305
+		}
306
+		return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
307
+	}
308
+
309
+
310
+
311
+	/**
312
+	 * @param mixed string | EED_Module $module
313
+	 */
314
+	public function add_module($module)
315
+	{
316
+		if ($module instanceof EED_Module) {
317
+			$module_class = get_class($module);
318
+			$this->modules->{$module_class} = $module;
319
+		} else {
320
+			if ( ! class_exists('EE_Module_Request_Router')) {
321
+				$this->load_core('Module_Request_Router');
322
+			}
323
+			$this->modules->{$module} = EE_Module_Request_Router::module_factory($module);
324
+		}
325
+	}
326
+
327
+
328
+
329
+	/**
330
+	 * @param string $module_name
331
+	 * @return mixed EED_Module | NULL
332
+	 */
333
+	public function get_module($module_name = '')
334
+	{
335
+		return isset($this->modules->{$module_name}) ? $this->modules->{$module_name} : null;
336
+	}
337
+
338
+
339
+
340
+	/**
341
+	 *    loads core classes - must be singletons
342
+	 *
343
+	 * @access    public
344
+	 * @param string $class_name - simple class name ie: session
345
+	 * @param mixed  $arguments
346
+	 * @param bool   $load_only
347
+	 * @return mixed
348
+	 */
349
+	public function load_core($class_name, $arguments = array(), $load_only = false)
350
+	{
351
+		$core_paths = apply_filters(
352
+			'FHEE__EE_Registry__load_core__core_paths',
353
+			array(
354
+				EE_CORE,
355
+				EE_ADMIN,
356
+				EE_CPTS,
357
+				EE_CORE . 'data_migration_scripts' . DS,
358
+				EE_CORE . 'request_stack' . DS,
359
+				EE_CORE . 'middleware' . DS,
360
+			)
361
+		);
362
+		// retrieve instantiated class
363
+		return $this->_load($core_paths, 'EE_', $class_name, 'core', $arguments, false, true, $load_only);
364
+	}
365
+
366
+
367
+
368
+	/**
369
+	 *    loads service classes
370
+	 *
371
+	 * @access    public
372
+	 * @param string $class_name - simple class name ie: session
373
+	 * @param mixed  $arguments
374
+	 * @param bool   $load_only
375
+	 * @return mixed
376
+	 */
377
+	public function load_service($class_name, $arguments = array(), $load_only = false)
378
+	{
379
+		$service_paths = apply_filters(
380
+			'FHEE__EE_Registry__load_service__service_paths',
381
+			array(
382
+				EE_CORE . 'services' . DS,
383
+			)
384
+		);
385
+		// retrieve instantiated class
386
+		return $this->_load($service_paths, 'EE_', $class_name, 'class', $arguments, false, true, $load_only);
387
+	}
388
+
389
+
390
+
391
+	/**
392
+	 *    loads data_migration_scripts
393
+	 *
394
+	 * @access    public
395
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
396
+	 * @param mixed  $arguments
397
+	 * @return EE_Data_Migration_Script_Base|mixed
398
+	 */
399
+	public function load_dms($class_name, $arguments = array())
400
+	{
401
+		// retrieve instantiated class
402
+		return $this->_load(EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(), 'EE_DMS_', $class_name, 'dms', $arguments, false, false, false);
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 *    loads object creating classes - must be singletons
409
+	 *
410
+	 * @param string $class_name - simple class name ie: attendee
411
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
412
+	 * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to instantiate
413
+	 * @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)
414
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate (default)
415
+	 * @return EE_Base_Class | bool
416
+	 */
417
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
418
+	{
419
+		$paths = apply_filters('FHEE__EE_Registry__load_class__paths', array(
420
+			EE_CORE,
421
+			EE_CLASSES,
422
+			EE_BUSINESS,
423
+		));
424
+		// retrieve instantiated class
425
+		return $this->_load($paths, 'EE_', $class_name, 'class', $arguments, $from_db, $cache, $load_only);
426
+	}
427
+
428
+
429
+
430
+	/**
431
+	 *    loads helper classes - must be singletons
432
+	 *
433
+	 * @param string $class_name - simple class name ie: price
434
+	 * @param mixed  $arguments
435
+	 * @param bool   $load_only
436
+	 * @return EEH_Base | bool
437
+	 */
438
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
439
+	{
440
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
441
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
442
+		// retrieve instantiated class
443
+		return $this->_load($helper_paths, 'EEH_', $class_name, 'helper', $arguments, false, true, $load_only);
444
+	}
445
+
446
+
447
+
448
+	/**
449
+	 *    loads core classes - must be singletons
450
+	 *
451
+	 * @access    public
452
+	 * @param string $class_name - simple class name ie: session
453
+	 * @param mixed  $arguments
454
+	 * @param bool   $load_only
455
+	 * @param bool   $cache      whether to cache the object or not.
456
+	 * @return mixed
457
+	 */
458
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
459
+	{
460
+		$paths = array(
461
+			EE_LIBRARIES,
462
+			EE_LIBRARIES . 'messages' . DS,
463
+			EE_LIBRARIES . 'shortcodes' . DS,
464
+			EE_LIBRARIES . 'qtips' . DS,
465
+			EE_LIBRARIES . 'payment_methods' . DS,
466
+		);
467
+		// retrieve instantiated class
468
+		return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, false, $cache, $load_only);
469
+	}
470
+
471
+
472
+
473
+	/**
474
+	 *    loads model classes - must be singletons
475
+	 *
476
+	 * @param string $class_name - simple class name ie: price
477
+	 * @param mixed  $arguments
478
+	 * @param bool   $load_only
479
+	 * @return EEM_Base | bool
480
+	 */
481
+	public function load_model($class_name, $arguments = array(), $load_only = false)
482
+	{
483
+		$paths = apply_filters('FHEE__EE_Registry__load_model__paths', array(
484
+			EE_MODELS,
485
+			EE_CORE,
486
+		));
487
+		// retrieve instantiated class
488
+		return $this->_load($paths, 'EEM_', $class_name, 'model', $arguments, false, true, $load_only);
489
+	}
490
+
491
+
492
+
493
+	/**
494
+	 *    loads model classes - must be singletons
495
+	 *
496
+	 * @param string $class_name - simple class name ie: price
497
+	 * @param mixed  $arguments
498
+	 * @param bool   $load_only
499
+	 * @return mixed | bool
500
+	 */
501
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
502
+	{
503
+		$paths = array(
504
+			EE_MODELS . 'fields' . DS,
505
+			EE_MODELS . 'helpers' . DS,
506
+			EE_MODELS . 'relations' . DS,
507
+			EE_MODELS . 'strategies' . DS,
508
+		);
509
+		// retrieve instantiated class
510
+		return $this->_load($paths, 'EE_', $class_name, '', $arguments, false, true, $load_only);
511
+	}
512
+
513
+
514
+
515
+	/**
516
+	 * Determines if $model_name is the name of an actual EE model.
517
+	 *
518
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
519
+	 * @return boolean
520
+	 */
521
+	public function is_model_name($model_name)
522
+	{
523
+		return isset($this->models[$model_name]) ? true : false;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 *    generic class loader
530
+	 *
531
+	 * @param string $path_to_file - directory path to file location, not including filename
532
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
533
+	 * @param string $type         - file type - core? class? helper? model?
534
+	 * @param mixed  $arguments
535
+	 * @param bool   $load_only
536
+	 * @return mixed
537
+	 */
538
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
539
+	{
540
+		// retrieve instantiated class
541
+		return $this->_load($path_to_file, '', $file_name, $type, $arguments, false, true, $load_only);
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 *    load_addon
548
+	 *
549
+	 * @param string $path_to_file - directory path to file location, not including filename
550
+	 * @param string $class_name   - full class name  ie:  My_Class
551
+	 * @param string $type         - file type - core? class? helper? model?
552
+	 * @param mixed  $arguments
553
+	 * @param bool   $load_only
554
+	 * @return EE_Addon
555
+	 */
556
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
557
+	{
558
+		// retrieve instantiated class
559
+		return $this->_load($path_to_file, 'addon', $class_name, $type, $arguments, false, true, $load_only);
560
+	}
561
+
562
+
563
+
564
+	/**
565
+	 * instantiates, caches, and automatically resolves dependencies
566
+	 * for classes that use a Fully Qualified Class Name.
567
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
568
+	 * then you need to use one of the existing load_*() methods
569
+	 * which can resolve the classname and filepath from the passed arguments
570
+	 *
571
+	 * @param bool|string $class_name   Fully Qualified Class Name
572
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
573
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
574
+	 * @param bool        $from_db      some classes are instantiated from the db
575
+	 *                                  and thus call a different method to instantiate
576
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
577
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
578
+	 * @return mixed                    null = failure to load or instantiate class object.
579
+	 *                                  object = class loaded and instantiated successfully.
580
+	 *                                  bool = fail or success when $load_only is true
581
+	 */
582
+	public function create(
583
+		$class_name = false,
584
+		$arguments = array(),
585
+		$cache = false,
586
+		$from_db = false,
587
+		$load_only = false,
588
+		$addon = false
589
+	) {
590
+		$class_name = ltrim($class_name, '\\');
591
+		$class_name = $this->_dependency_map->get_alias($class_name);
592
+		if ( ! class_exists($class_name)) {
593
+			// maybe the class is registered with a preceding \
594
+			$class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
595
+			// still doesn't exist ?
596
+			if ( ! class_exists($class_name)) {
597
+				return null;
598
+			}
599
+		}
600
+		// if we're only loading the class and it already exists, then let's just return true immediately
601
+		if ($load_only) {
602
+			return true;
603
+		}
604
+		$addon = $addon ? 'addon' : '';
605
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
606
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
607
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
608
+		if ($this->_cache_on && $cache && ! $load_only) {
609
+			// return object if it's already cached
610
+			$cached_class = $this->_get_cached_class($class_name, $addon);
611
+			if ($cached_class !== null) {
612
+				return $cached_class;
613
+			}
614
+		}
615
+		// instantiate the requested object
616
+		$class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
617
+		if ($this->_cache_on && $cache) {
618
+			// save it for later... kinda like gum  { : $
619
+			$this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
620
+		}
621
+		$this->_cache_on = true;
622
+		return $class_obj;
623
+	}
624
+
625
+
626
+
627
+	/**
628
+	 * instantiates, caches, and injects dependencies for classes
629
+	 *
630
+	 * @param array       $file_paths   an array of paths to folders to look in
631
+	 * @param string      $class_prefix EE  or EEM or... ???
632
+	 * @param bool|string $class_name   $class name
633
+	 * @param string      $type         file type - core? class? helper? model?
634
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
635
+	 * @param bool        $from_db      some classes are instantiated from the db
636
+	 *                                  and thus call a different method to instantiate
637
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
638
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
639
+	 * @return null|object|bool         null = failure to load or instantiate class object.
640
+	 *                                  object = class loaded and instantiated successfully.
641
+	 *                                  bool = fail or success when $load_only is true
642
+	 */
643
+	protected function _load(
644
+		$file_paths = array(),
645
+		$class_prefix = 'EE_',
646
+		$class_name = false,
647
+		$type = 'class',
648
+		$arguments = array(),
649
+		$from_db = false,
650
+		$cache = true,
651
+		$load_only = false
652
+	) {
653
+		$class_name = ltrim($class_name, '\\');
654
+		// strip php file extension
655
+		$class_name = str_replace('.php', '', trim($class_name));
656
+		// does the class have a prefix ?
657
+		if ( ! empty($class_prefix) && $class_prefix != 'addon') {
658
+			// make sure $class_prefix is uppercase
659
+			$class_prefix = strtoupper(trim($class_prefix));
660
+			// add class prefix ONCE!!!
661
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
662
+		}
663
+		$class_name = $this->_dependency_map->get_alias($class_name);
664
+		$class_exists = class_exists($class_name);
665
+		// if we're only loading the class and it already exists, then let's just return true immediately
666
+		if ($load_only && $class_exists) {
667
+			return true;
668
+		}
669
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
670
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
671
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
672
+		if ($this->_cache_on && $cache && ! $load_only) {
673
+			// return object if it's already cached
674
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix);
675
+			if ($cached_class !== null) {
676
+				return $cached_class;
677
+			}
678
+		}
679
+		// if the class doesn't already exist.. then we need to try and find the file and load it
680
+		if ( ! $class_exists) {
681
+			// get full path to file
682
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
683
+			// load the file
684
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
685
+			// if loading failed, or we are only loading a file but NOT instantiating an object
686
+			if ( ! $loaded || $load_only) {
687
+				// return boolean if only loading, or null if an object was expected
688
+				return $load_only ? $loaded : null;
689
+			}
690
+		}
691
+		// instantiate the requested object
692
+		$class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
693
+		if ($this->_cache_on && $cache) {
694
+			// save it for later... kinda like gum  { : $
695
+			$this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
696
+		}
697
+		$this->_cache_on = true;
698
+		return $class_obj;
699
+	}
700
+
701
+
702
+
703
+
704
+	/**
705
+	 * _get_cached_class
706
+	 * attempts to find a cached version of the requested class
707
+	 * by looking in the following places:
708
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
709
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
710
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
711
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
712
+	 *
713
+	 * @access protected
714
+	 * @param string $class_name
715
+	 * @param string $class_prefix
716
+	 * @return mixed
717
+	 */
718
+	protected function _get_cached_class($class_name, $class_prefix = '')
719
+	{
720
+		if ($class_name === 'EE_Registry') {
721
+			return $this;
722
+		}
723
+		// have to specify something, but not anything that will conflict
724
+		$class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
725
+			? $this->_class_abbreviations[ $class_name ]
726
+			: 'FANCY_BATMAN_PANTS';
727
+		$class_name = str_replace('\\', '_', $class_name);
728
+		// check if class has already been loaded, and return it if it has been
729
+		if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
730
+			return $this->{$class_abbreviation};
731
+		}
732
+		if (isset ($this->{$class_name})) {
733
+			return $this->{$class_name};
734
+		}
735
+		if (isset ($this->LIB->{$class_name})) {
736
+			return $this->LIB->{$class_name};
737
+		}
738
+		if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
739
+			return $this->addons->{$class_name};
740
+		}
741
+		return null;
742
+	}
743
+
744
+
745
+
746
+	/**
747
+	 * removes a cached version of the requested class
748
+	 *
749
+	 * @param string $class_name
750
+	 * @param boolean $addon
751
+	 * @return boolean
752
+	 */
753
+	public function clear_cached_class($class_name, $addon = false)
754
+	{
755
+		// have to specify something, but not anything that will conflict
756
+		$class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
757
+			? $this->_class_abbreviations[ $class_name ]
758
+			: 'FANCY_BATMAN_PANTS';
759
+		$class_name = str_replace('\\', '_', $class_name);
760
+		// check if class has already been loaded, and return it if it has been
761
+		if (isset($this->{$class_abbreviation}) && ! is_null($this->{$class_abbreviation})) {
762
+			$this->{$class_abbreviation} = null;
763
+			return true;
764
+		}
765
+		if (isset($this->{$class_name})) {
766
+			$this->{$class_name} = null;
767
+			return true;
768
+		}
769
+		if (isset($this->LIB->{$class_name})) {
770
+			unset($this->LIB->{$class_name});
771
+			return true;
772
+		}
773
+		if ($addon && isset($this->addons->{$class_name})) {
774
+			unset($this->addons->{$class_name});
775
+			return true;
776
+		}
777
+		return false;
778
+	}
779
+
780
+
781
+	/**
782
+	 * _resolve_path
783
+	 * attempts to find a full valid filepath for the requested class.
784
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
785
+	 * then returns that path if the target file has been found and is readable
786
+	 *
787
+	 * @access protected
788
+	 * @param string $class_name
789
+	 * @param string $type
790
+	 * @param array  $file_paths
791
+	 * @return string | bool
792
+	 */
793
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
794
+	{
795
+		// make sure $file_paths is an array
796
+		$file_paths = is_array($file_paths) ? $file_paths : array($file_paths);
797
+		// cycle thru paths
798
+		foreach ($file_paths as $key => $file_path) {
799
+			// convert all separators to proper DS, if no filepath, then use EE_CLASSES
800
+			$file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
801
+			// prep file type
802
+			$type = ! empty($type) ? trim($type, '.') . '.' : '';
803
+			// build full file path
804
+			$file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
805
+			//does the file exist and can be read ?
806
+			if (is_readable($file_paths[$key])) {
807
+				return $file_paths[$key];
808
+			}
809
+		}
810
+		return false;
811
+	}
812
+
813
+
814
+
815
+	/**
816
+	 * _require_file
817
+	 * basically just performs a require_once()
818
+	 * but with some error handling
819
+	 *
820
+	 * @access protected
821
+	 * @param  string $path
822
+	 * @param  string $class_name
823
+	 * @param  string $type
824
+	 * @param  array  $file_paths
825
+	 * @return boolean
826
+	 * @throws \EE_Error
827
+	 */
828
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
829
+	{
830
+		// don't give up! you gotta...
831
+		try {
832
+			//does the file exist and can it be read ?
833
+			if ( ! $path) {
834
+				// so sorry, can't find the file
835
+				throw new EE_Error (
836
+					sprintf(
837
+						__('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'),
838
+						trim($type, '.'),
839
+						$class_name,
840
+						'<br />' . implode(',<br />', $file_paths)
841
+					)
842
+				);
843
+			}
844
+			// get the file
845
+			require_once($path);
846
+			// if the class isn't already declared somewhere
847
+			if (class_exists($class_name, false) === false) {
848
+				// so sorry, not a class
849
+				throw new EE_Error(
850
+					sprintf(
851
+						__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
852
+						$type,
853
+						$path,
854
+						$class_name
855
+					)
856
+				);
857
+			}
858
+		} catch (EE_Error $e) {
859
+			$e->get_error();
860
+			return false;
861
+		}
862
+		return true;
863
+	}
864
+
865
+
866
+
867
+	/**
868
+	 * _create_object
869
+	 * Attempts to instantiate the requested class via any of the
870
+	 * commonly used instantiation methods employed throughout EE.
871
+	 * The priority for instantiation is as follows:
872
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
873
+	 *        - model objects via their 'new_instance_from_db' method
874
+	 *        - model objects via their 'new_instance' method
875
+	 *        - "singleton" classes" via their 'instance' method
876
+	 *    - standard instantiable classes via their __constructor
877
+	 * Prior to instantiation, if the classname exists in the dependency_map,
878
+	 * then the constructor for the requested class will be examined to determine
879
+	 * if any dependencies exist, and if they can be injected.
880
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
881
+	 *
882
+	 * @access protected
883
+	 * @param string $class_name
884
+	 * @param array  $arguments
885
+	 * @param string $type
886
+	 * @param bool   $from_db
887
+	 * @return null | object
888
+	 * @throws \EE_Error
889
+	 */
890
+	protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
891
+	{
892
+		$class_obj = null;
893
+		$instantiation_mode = '0) none';
894
+		// don't give up! you gotta...
895
+		try {
896
+			// create reflection
897
+			$reflector = $this->get_ReflectionClass($class_name);
898
+			// make sure arguments are an array
899
+			$arguments = is_array($arguments) ? $arguments : array($arguments);
900
+			// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
901
+			// else wrap it in an additional array so that it doesn't get split into multiple parameters
902
+			$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
903
+				? $arguments
904
+				: array($arguments);
905
+			// attempt to inject dependencies ?
906
+			if ($this->_dependency_map->has($class_name)) {
907
+				$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
908
+			}
909
+			// instantiate the class if possible
910
+			if ($reflector->isAbstract()) {
911
+				// nothing to instantiate, loading file was enough
912
+				// does not throw an exception so $instantiation_mode is unused
913
+				// $instantiation_mode = "1) no constructor abstract class";
914
+				$class_obj = true;
915
+			} else if ($reflector->getConstructor() === null && $reflector->isInstantiable() && empty($arguments)) {
916
+				// no constructor = static methods only... nothing to instantiate, loading file was enough
917
+				$instantiation_mode = "2) no constructor but instantiable";
918
+				$class_obj = $reflector->newInstance();
919
+			} else if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
920
+				$instantiation_mode = "3) new_instance_from_db()";
921
+				$class_obj = call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
922
+			} else if (method_exists($class_name, 'new_instance')) {
923
+				$instantiation_mode = "4) new_instance()";
924
+				$class_obj = call_user_func_array(array($class_name, 'new_instance'), $arguments);
925
+			} else if (method_exists($class_name, 'instance')) {
926
+				$instantiation_mode = "5) instance()";
927
+				$class_obj = call_user_func_array(array($class_name, 'instance'), $arguments);
928
+			} else if ($reflector->isInstantiable()) {
929
+				$instantiation_mode = "6) constructor";
930
+				$class_obj = $reflector->newInstanceArgs($arguments);
931
+			} else {
932
+				// heh ? something's not right !
933
+				throw new EE_Error(
934
+					sprintf(
935
+						__('The %s file %s could not be instantiated.', 'event_espresso'),
936
+						$type,
937
+						$class_name
938
+					)
939
+				);
940
+			}
941
+		} catch (Exception $e) {
942
+			if ( ! $e instanceof EE_Error) {
943
+				$e = new EE_Error(
944
+					sprintf(
945
+						__('The following error occurred while attempting to instantiate "%1$s": %2$s %3$s %2$s instantiation mode : %4$s', 'event_espresso'),
946
+						$class_name,
947
+						'<br />',
948
+						$e->getMessage(),
949
+						$instantiation_mode
950
+					)
951
+				);
952
+			}
953
+			$e->get_error();
954
+		}
955
+		return $class_obj;
956
+	}
957
+
958
+
959
+
960
+	/**
961
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
962
+	 * @param array $array
963
+	 * @return bool
964
+	 */
965
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
966
+	{
967
+		return ! empty($array) ? array_keys($array) === range(0, count($array) - 1) : true;
968
+	}
969
+
970
+
971
+
972
+	/**
973
+	 * getReflectionClass
974
+	 * checks if a ReflectionClass object has already been generated for a class
975
+	 * and returns that instead of creating a new one
976
+	 *
977
+	 * @access public
978
+	 * @param string $class_name
979
+	 * @return ReflectionClass
980
+	 */
981
+	public function get_ReflectionClass($class_name)
982
+	{
983
+		if (
984
+			! isset($this->_reflectors[$class_name])
985
+			|| ! $this->_reflectors[$class_name] instanceof ReflectionClass
986
+		) {
987
+			$this->_reflectors[$class_name] = new ReflectionClass($class_name);
988
+		}
989
+		return $this->_reflectors[$class_name];
990
+	}
991
+
992
+
993
+
994
+	/**
995
+	 * _resolve_dependencies
996
+	 * examines the constructor for the requested class to determine
997
+	 * if any dependencies exist, and if they can be injected.
998
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
999
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1000
+	 * For example:
1001
+	 *        if attempting to load a class "Foo" with the following constructor:
1002
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1003
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1004
+	 *        but only IF they are NOT already present in the incoming arguments array,
1005
+	 *        and the correct classes can be loaded
1006
+	 *
1007
+	 * @access protected
1008
+	 * @param ReflectionClass $reflector
1009
+	 * @param string          $class_name
1010
+	 * @param array           $arguments
1011
+	 * @return array
1012
+	 * @throws \ReflectionException
1013
+	 */
1014
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1015
+	{
1016
+		// let's examine the constructor
1017
+		$constructor = $reflector->getConstructor();
1018
+		// whu? huh? nothing?
1019
+		if ( ! $constructor) {
1020
+			return $arguments;
1021
+		}
1022
+		// get constructor parameters
1023
+		$params = $constructor->getParameters();
1024
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1025
+		$argument_keys = array_keys($arguments);
1026
+		// now loop thru all of the constructors expected parameters
1027
+		foreach ($params as $index => $param) {
1028
+			// is this a dependency for a specific class ?
1029
+			$param_class = $param->getClass() ? $param->getClass()->name : null;
1030
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1031
+			$param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1032
+				? $this->_dependency_map->get_alias($param_class, $class_name)
1033
+				: $param_class;
1034
+			if (
1035
+				// param is not even a class
1036
+				empty($param_class)
1037
+				// and something already exists in the incoming arguments for this param
1038
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1039
+			) {
1040
+				// so let's skip this argument and move on to the next
1041
+				continue;
1042
+			}
1043
+			if (
1044
+				// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1045
+				! empty($param_class)
1046
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1047
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
1048
+			) {
1049
+				// skip this argument and move on to the next
1050
+				continue;
1051
+			}
1052
+			if (
1053
+				// parameter is type hinted as a class, and should be injected
1054
+				! empty($param_class)
1055
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1056
+			) {
1057
+				$arguments = $this->_resolve_dependency($class_name, $param_class, $arguments, $index);
1058
+			} else {
1059
+				try {
1060
+					$arguments[$index] = $param->getDefaultValue();
1061
+				} catch (ReflectionException $e) {
1062
+					throw new ReflectionException(
1063
+						sprintf(
1064
+							__('%1$s for parameter "$%2$s"', 'event_espresso'),
1065
+							$e->getMessage(),
1066
+							$param->getName()
1067
+						)
1068
+					);
1069
+				}
1070
+			}
1071
+		}
1072
+		return $arguments;
1073
+	}
1074
+
1075
+
1076
+
1077
+	/**
1078
+	 * @access protected
1079
+	 * @param string $class_name
1080
+	 * @param string $param_class
1081
+	 * @param array  $arguments
1082
+	 * @param mixed  $index
1083
+	 * @return array
1084
+	 */
1085
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index)
1086
+	{
1087
+		$dependency = null;
1088
+		// should dependency be loaded from cache ?
1089
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency($class_name, $param_class)
1090
+					!== EE_Dependency_Map::load_new_object
1091
+			? true
1092
+			: false;
1093
+		// we might have a dependency...
1094
+		// let's MAYBE try and find it in our cache if that's what's been requested
1095
+		$cached_class = $cache_on ? $this->_get_cached_class($param_class) : null;
1096
+		// and grab it if it exists
1097
+		if ($cached_class instanceof $param_class) {
1098
+			$dependency = $cached_class;
1099
+		} else if ($param_class !== $class_name) {
1100
+			// obtain the loader method from the dependency map
1101
+			$loader = $this->_dependency_map->class_loader($param_class);
1102
+			// is loader a custom closure ?
1103
+			if ($loader instanceof Closure) {
1104
+				$dependency = $loader();
1105
+			} else {
1106
+				// set the cache on property for the recursive loading call
1107
+				$this->_cache_on = $cache_on;
1108
+				// if not, then let's try and load it via the registry
1109
+				if ($loader && method_exists($this, $loader)) {
1110
+					$dependency = $this->{$loader}($param_class);
1111
+				} else {
1112
+					$dependency = $this->create($param_class, array(), $cache_on);
1113
+				}
1114
+			}
1115
+		}
1116
+		// did we successfully find the correct dependency ?
1117
+		if ($dependency instanceof $param_class) {
1118
+			// then let's inject it into the incoming array of arguments at the correct location
1119
+			if (isset($argument_keys[$index])) {
1120
+				$arguments[$argument_keys[$index]] = $dependency;
1121
+			} else {
1122
+				$arguments[$index] = $dependency;
1123
+			}
1124
+		}
1125
+		return $arguments;
1126
+	}
1127
+
1128
+
1129
+
1130
+	/**
1131
+	 * _set_cached_class
1132
+	 * attempts to cache the instantiated class locally
1133
+	 * in one of the following places, in the following order:
1134
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1135
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1136
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1137
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1138
+	 *
1139
+	 * @access protected
1140
+	 * @param object $class_obj
1141
+	 * @param string $class_name
1142
+	 * @param string $class_prefix
1143
+	 * @param bool   $from_db
1144
+	 * @return void
1145
+	 */
1146
+	protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1147
+	{
1148
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1149
+			return;
1150
+		}
1151
+		// return newly instantiated class
1152
+		if (isset($this->_class_abbreviations[$class_name])) {
1153
+			$class_abbreviation = $this->_class_abbreviations[$class_name];
1154
+			$this->{$class_abbreviation} = $class_obj;
1155
+			return;
1156
+		}
1157
+		$class_name = str_replace('\\', '_', $class_name);
1158
+		if (property_exists($this, $class_name)) {
1159
+			$this->{$class_name} = $class_obj;
1160
+			return;
1161
+		}
1162
+		if ($class_prefix === 'addon') {
1163
+			$this->addons->{$class_name} = $class_obj;
1164
+			return;
1165
+		}
1166
+		if ( ! $from_db) {
1167
+			$this->LIB->{$class_name} = $class_obj;
1168
+		}
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1175
+	 *
1176
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1177
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1178
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1179
+	 * @param array  $arguments
1180
+	 * @return object
1181
+	 */
1182
+	public static function factory($classname, $arguments = array())
1183
+	{
1184
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1185
+		if ($loader instanceof Closure) {
1186
+			return $loader($arguments);
1187
+		}
1188
+		if (method_exists(EE_Registry::instance(), $loader)) {
1189
+			return EE_Registry::instance()->{$loader}($classname, $arguments);
1190
+		}
1191
+		return null;
1192
+	}
1193
+
1194
+
1195
+
1196
+	/**
1197
+	 * Gets the addon by its name/slug (not classname. For that, just
1198
+	 * use the classname as the property name on EE_Config::instance()->addons)
1199
+	 *
1200
+	 * @param string $name
1201
+	 * @return EE_Addon
1202
+	 */
1203
+	public function get_addon_by_name($name)
1204
+	{
1205
+		foreach ($this->addons as $addon) {
1206
+			if ($addon->name() == $name) {
1207
+				return $addon;
1208
+			}
1209
+		}
1210
+		return null;
1211
+	}
1212
+
1213
+
1214
+
1215
+	/**
1216
+	 * 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
1217
+	 * the addon's classname. So if you just want to get the addon by classname, use EE_Config::instance()->addons->{classname}
1218
+	 *
1219
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1220
+	 */
1221
+	public function get_addons_by_name()
1222
+	{
1223
+		$addons = array();
1224
+		foreach ($this->addons as $addon) {
1225
+			$addons[$addon->name()] = $addon;
1226
+		}
1227
+		return $addons;
1228
+	}
1229
+
1230
+
1231
+
1232
+	/**
1233
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1234
+	 * a stale copy of it around
1235
+	 *
1236
+	 * @param string $model_name
1237
+	 * @return \EEM_Base
1238
+	 * @throws \EE_Error
1239
+	 */
1240
+	public function reset_model($model_name)
1241
+	{
1242
+		$model_class_name = strpos($model_name, 'EEM_') !== 0 ? "EEM_{$model_name}" : $model_name;
1243
+		if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1244
+			return null;
1245
+		}
1246
+		//get that model reset it and make sure we nuke the old reference to it
1247
+		if ($this->LIB->{$model_class_name} instanceof $model_class_name && is_callable(array($model_class_name, 'reset'))) {
1248
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1249
+		} else {
1250
+			throw new EE_Error(sprintf(__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1251
+		}
1252
+		return $this->LIB->{$model_class_name};
1253
+	}
1254
+
1255
+
1256
+
1257
+	/**
1258
+	 * Resets the registry.
1259
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when switch_to_blog
1260
+	 * is used in a multisite install.  Here is a list of things that are NOT reset.
1261
+	 * - $_dependency_map
1262
+	 * - $_class_abbreviations
1263
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1264
+	 * - $REQ:  Still on the same request so no need to change.
1265
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1266
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only one Session
1267
+	 *         can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1268
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1269
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1270
+	 *             switch or on the restore.
1271
+	 * - $modules
1272
+	 * - $shortcodes
1273
+	 * - $widgets
1274
+	 *
1275
+	 * @param boolean $hard             whether to reset data in the database too, or just refresh
1276
+	 *                                  the Registry to its state at the beginning of the request
1277
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1278
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not sure if you CAN
1279
+	 *                                  currently reinstantiate the singletons at the moment)
1280
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so client
1281
+	 *                                  code instead can just change the model context to a different blog id if necessary
1282
+	 * @return EE_Registry
1283
+	 */
1284
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1285
+	{
1286
+		$instance = self::instance();
1287
+		$instance->_cache_on = true;
1288
+		// reset some "special" classes
1289
+		EEH_Activation::reset();
1290
+		$instance->CFG = $instance->CFG->reset($hard, $reinstantiate);
1291
+		$instance->CART = null;
1292
+		$instance->MRM = null;
1293
+		$instance->AssetsRegistry = null;
1294
+		$instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1295
+		//messages reset
1296
+		EED_Messages::reset();
1297
+		//handle of objects cached on LIB
1298
+		foreach (array('LIB', 'modules', 'shortcodes') as $cache) {
1299
+			foreach ($instance->{$cache} as $class_name => $class) {
1300
+				if (EE_Registry::_reset_and_unset_object($class, $reset_models)) {
1301
+					unset($instance->{$cache}->{$class_name});
1302
+				}
1303
+			}
1304
+		}
1305
+		return $instance;
1306
+	}
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * if passed object implements ResettableInterface, then call it's reset() method
1312
+	 * if passed object implements InterminableInterface, then return false,
1313
+	 * to indicate that it should NOT be cleared from the Registry cache
1314
+	 *
1315
+	 * @param      $object
1316
+	 * @param bool $reset_models
1317
+	 * @return bool returns true if cached object should be unset
1318
+	 */
1319
+	private static function _reset_and_unset_object($object, $reset_models)
1320
+	{
1321
+		static $count = 0;
1322
+		$count++;
1323
+		if ($object instanceof ResettableInterface) {
1324
+			if ($object instanceof EEM_Base) {
1325
+				if ($reset_models) {
1326
+					$object->reset();
1327
+					return true;
1328
+				}
1329
+				return false;
1330
+			}
1331
+			$object->reset();
1332
+			return true;
1333
+		}
1334
+		if ( ! $object instanceof InterminableInterface) {
1335
+			return true;
1336
+		}
1337
+		return false;
1338
+	}
1339
+
1340
+
1341
+
1342
+	/**
1343
+	 * @override magic methods
1344
+	 * @return void
1345
+	 */
1346
+	public final function __destruct()
1347
+	{
1348
+	}
1349
+
1350
+
1351
+
1352
+	/**
1353
+	 * @param $a
1354
+	 * @param $b
1355
+	 */
1356
+	public final function __call($a, $b)
1357
+	{
1358
+	}
1359
+
1360
+
1361
+
1362
+	/**
1363
+	 * @param $a
1364
+	 */
1365
+	public final function __get($a)
1366
+	{
1367
+	}
1368
+
1369
+
1370
+
1371
+	/**
1372
+	 * @param $a
1373
+	 * @param $b
1374
+	 */
1375
+	public final function __set($a, $b)
1376
+	{
1377
+	}
1378
+
1379
+
1380
+
1381
+	/**
1382
+	 * @param $a
1383
+	 */
1384
+	public final function __isset($a)
1385
+	{
1386
+	}
1387 1387
 
1388 1388
 
1389 1389
 
1390
-    /**
1391
-     * @param $a
1392
-     */
1393
-    public final function __unset($a)
1394
-    {
1395
-    }
1390
+	/**
1391
+	 * @param $a
1392
+	 */
1393
+	public final function __unset($a)
1394
+	{
1395
+	}
1396 1396
 
1397 1397
 
1398 1398
 
1399
-    /**
1400
-     * @return array
1401
-     */
1402
-    public final function __sleep()
1403
-    {
1404
-        return array();
1405
-    }
1399
+	/**
1400
+	 * @return array
1401
+	 */
1402
+	public final function __sleep()
1403
+	{
1404
+		return array();
1405
+	}
1406 1406
 
1407 1407
 
1408 1408
 
1409
-    public final function __wakeup()
1410
-    {
1411
-    }
1409
+	public final function __wakeup()
1410
+	{
1411
+	}
1412 1412
 
1413 1413
 
1414 1414
 
1415
-    /**
1416
-     * @return string
1417
-     */
1418
-    public final function __toString()
1419
-    {
1420
-        return '';
1421
-    }
1415
+	/**
1416
+	 * @return string
1417
+	 */
1418
+	public final function __toString()
1419
+	{
1420
+		return '';
1421
+	}
1422 1422
 
1423 1423
 
1424 1424
 
1425
-    public final function __invoke()
1426
-    {
1427
-    }
1425
+	public final function __invoke()
1426
+	{
1427
+	}
1428 1428
 
1429 1429
 
1430 1430
 
1431
-    public final static function __set_state($array = array())
1432
-    {
1433
-        return EE_Registry::instance();
1434
-    }
1431
+	public final static function __set_state($array = array())
1432
+	{
1433
+		return EE_Registry::instance();
1434
+	}
1435 1435
 
1436 1436
 
1437 1437
 
1438
-    public final function __clone()
1439
-    {
1440
-    }
1438
+	public final function __clone()
1439
+	{
1440
+	}
1441 1441
 
1442 1442
 
1443 1443
 
1444
-    /**
1445
-     * @param $a
1446
-     * @param $b
1447
-     */
1448
-    public final static function __callStatic($a, $b)
1449
-    {
1450
-    }
1444
+	/**
1445
+	 * @param $a
1446
+	 * @param $b
1447
+	 */
1448
+	public final static function __callStatic($a, $b)
1449
+	{
1450
+	}
1451 1451
 
1452 1452
 
1453 1453
 
1454
-    /**
1455
-     * Gets all the custom post type models defined
1456
-     *
1457
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1458
-     */
1459
-    public function cpt_models()
1460
-    {
1461
-        $cpt_models = array();
1462
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1463
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1464
-                $cpt_models[$short_name] = $classname;
1465
-            }
1466
-        }
1467
-        return $cpt_models;
1468
-    }
1454
+	/**
1455
+	 * Gets all the custom post type models defined
1456
+	 *
1457
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1458
+	 */
1459
+	public function cpt_models()
1460
+	{
1461
+		$cpt_models = array();
1462
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1463
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1464
+				$cpt_models[$short_name] = $classname;
1465
+			}
1466
+		}
1467
+		return $cpt_models;
1468
+	}
1469 1469
 
1470 1470
 
1471 1471
 
1472
-    /**
1473
-     * @return \EE_Config
1474
-     */
1475
-    public static function CFG()
1476
-    {
1477
-        return self::instance()->CFG;
1478
-    }
1472
+	/**
1473
+	 * @return \EE_Config
1474
+	 */
1475
+	public static function CFG()
1476
+	{
1477
+		return self::instance()->CFG;
1478
+	}
1479 1479
 
1480 1480
 
1481 1481
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -297,13 +297,13 @@  discard block
 block discarded – undo
297 297
      */
298 298
     public static function localize_i18n_js_strings()
299 299
     {
300
-        $i18n_js_strings = (array)EE_Registry::$i18n_js_strings;
300
+        $i18n_js_strings = (array) EE_Registry::$i18n_js_strings;
301 301
         foreach ($i18n_js_strings as $key => $value) {
302 302
             if (is_scalar($value)) {
303
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
303
+                $i18n_js_strings[$key] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
304 304
             }
305 305
         }
306
-        return "/* <![CDATA[ */ var eei18n = " . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
306
+        return "/* <![CDATA[ */ var eei18n = ".wp_json_encode($i18n_js_strings).'; /* ]]> */';
307 307
     }
308 308
 
309 309
 
@@ -354,9 +354,9 @@  discard block
 block discarded – undo
354 354
                 EE_CORE,
355 355
                 EE_ADMIN,
356 356
                 EE_CPTS,
357
-                EE_CORE . 'data_migration_scripts' . DS,
358
-                EE_CORE . 'request_stack' . DS,
359
-                EE_CORE . 'middleware' . DS,
357
+                EE_CORE.'data_migration_scripts'.DS,
358
+                EE_CORE.'request_stack'.DS,
359
+                EE_CORE.'middleware'.DS,
360 360
             )
361 361
         );
362 362
         // retrieve instantiated class
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
         $service_paths = apply_filters(
380 380
             'FHEE__EE_Registry__load_service__service_paths',
381 381
             array(
382
-                EE_CORE . 'services' . DS,
382
+                EE_CORE.'services'.DS,
383 383
             )
384 384
         );
385 385
         // retrieve instantiated class
@@ -459,10 +459,10 @@  discard block
 block discarded – undo
459 459
     {
460 460
         $paths = array(
461 461
             EE_LIBRARIES,
462
-            EE_LIBRARIES . 'messages' . DS,
463
-            EE_LIBRARIES . 'shortcodes' . DS,
464
-            EE_LIBRARIES . 'qtips' . DS,
465
-            EE_LIBRARIES . 'payment_methods' . DS,
462
+            EE_LIBRARIES.'messages'.DS,
463
+            EE_LIBRARIES.'shortcodes'.DS,
464
+            EE_LIBRARIES.'qtips'.DS,
465
+            EE_LIBRARIES.'payment_methods'.DS,
466 466
         );
467 467
         // retrieve instantiated class
468 468
         return $this->_load($paths, 'EE_', $class_name, 'lib', $arguments, false, $cache, $load_only);
@@ -501,10 +501,10 @@  discard block
 block discarded – undo
501 501
     public function load_model_class($class_name, $arguments = array(), $load_only = true)
502 502
     {
503 503
         $paths = array(
504
-            EE_MODELS . 'fields' . DS,
505
-            EE_MODELS . 'helpers' . DS,
506
-            EE_MODELS . 'relations' . DS,
507
-            EE_MODELS . 'strategies' . DS,
504
+            EE_MODELS.'fields'.DS,
505
+            EE_MODELS.'helpers'.DS,
506
+            EE_MODELS.'relations'.DS,
507
+            EE_MODELS.'strategies'.DS,
508 508
         );
509 509
         // retrieve instantiated class
510 510
         return $this->_load($paths, 'EE_', $class_name, '', $arguments, false, true, $load_only);
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
         $class_name = $this->_dependency_map->get_alias($class_name);
592 592
         if ( ! class_exists($class_name)) {
593 593
             // maybe the class is registered with a preceding \
594
-            $class_name = strpos($class_name, '\\') !== 0 ? '\\' . $class_name : $class_name;
594
+            $class_name = strpos($class_name, '\\') !== 0 ? '\\'.$class_name : $class_name;
595 595
             // still doesn't exist ?
596 596
             if ( ! class_exists($class_name)) {
597 597
                 return null;
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
             // make sure $class_prefix is uppercase
659 659
             $class_prefix = strtoupper(trim($class_prefix));
660 660
             // add class prefix ONCE!!!
661
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
661
+            $class_name = $class_prefix.str_replace($class_prefix, '', $class_name);
662 662
         }
663 663
         $class_name = $this->_dependency_map->get_alias($class_name);
664 664
         $class_exists = class_exists($class_name);
@@ -721,8 +721,8 @@  discard block
 block discarded – undo
721 721
             return $this;
722 722
         }
723 723
         // have to specify something, but not anything that will conflict
724
-        $class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
725
-            ? $this->_class_abbreviations[ $class_name ]
724
+        $class_abbreviation = isset($this->_class_abbreviations[$class_name])
725
+            ? $this->_class_abbreviations[$class_name]
726 726
             : 'FANCY_BATMAN_PANTS';
727 727
         $class_name = str_replace('\\', '_', $class_name);
728 728
         // check if class has already been loaded, and return it if it has been
@@ -753,8 +753,8 @@  discard block
 block discarded – undo
753 753
     public function clear_cached_class($class_name, $addon = false)
754 754
     {
755 755
         // have to specify something, but not anything that will conflict
756
-        $class_abbreviation = isset($this->_class_abbreviations[ $class_name ])
757
-            ? $this->_class_abbreviations[ $class_name ]
756
+        $class_abbreviation = isset($this->_class_abbreviations[$class_name])
757
+            ? $this->_class_abbreviations[$class_name]
758 758
             : 'FANCY_BATMAN_PANTS';
759 759
         $class_name = str_replace('\\', '_', $class_name);
760 760
         // check if class has already been loaded, and return it if it has been
@@ -799,9 +799,9 @@  discard block
 block discarded – undo
799 799
             // convert all separators to proper DS, if no filepath, then use EE_CLASSES
800 800
             $file_path = $file_path ? str_replace(array('/', '\\'), DS, $file_path) : EE_CLASSES;
801 801
             // prep file type
802
-            $type = ! empty($type) ? trim($type, '.') . '.' : '';
802
+            $type = ! empty($type) ? trim($type, '.').'.' : '';
803 803
             // build full file path
804
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
804
+            $file_paths[$key] = rtrim($file_path, DS).DS.$class_name.'.'.$type.'php';
805 805
             //does the file exist and can be read ?
806 806
             if (is_readable($file_paths[$key])) {
807 807
                 return $file_paths[$key];
@@ -832,12 +832,12 @@  discard block
 block discarded – undo
832 832
             //does the file exist and can it be read ?
833 833
             if ( ! $path) {
834 834
                 // so sorry, can't find the file
835
-                throw new EE_Error (
835
+                throw new EE_Error(
836 836
                     sprintf(
837 837
                         __('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'),
838 838
                         trim($type, '.'),
839 839
                         $class_name,
840
-                        '<br />' . implode(',<br />', $file_paths)
840
+                        '<br />'.implode(',<br />', $file_paths)
841 841
                     )
842 842
                 );
843 843
             }
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.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      */
62 62
     public static function getTableAnalysis()
63 63
     {
64
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
64
+        if ( ! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
65 65
             self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
66 66
         }
67 67
         return self::$table_analysis;
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
      */
74 74
     public static function getTableManager()
75 75
     {
76
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
76
+        if ( ! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
77 77
             self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
78 78
         }
79 79
         return self::$table_manager;
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
         if ($which_to_include === 'old') {
190 190
             $cron_tasks = array_filter(
191 191
                 $cron_tasks,
192
-                function ($value) {
192
+                function($value) {
193 193
                     return $value === EEH_Activation::cron_task_no_longer_in_use;
194 194
                 }
195 195
             );
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
     {
220 220
 
221 221
         foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
222
-            if (! wp_next_scheduled($hook_name)) {
222
+            if ( ! wp_next_scheduled($hook_name)) {
223 223
                 /**
224 224
                  * This allows client code to define the initial start timestamp for this schedule.
225 225
                  */
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
             3
325 325
         );
326 326
         //EE_Config::reset();
327
-        if (! EE_Config::logging_enabled()) {
327
+        if ( ! EE_Config::logging_enabled()) {
328 328
             delete_option(EE_Config::LOG_NAME);
329 329
         }
330 330
     }
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
     public static function load_calendar_config()
340 340
     {
341 341
         // grab array of all plugin folders and loop thru it
342
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
342
+        $plugins = glob(WP_PLUGIN_DIR.DS.'*', GLOB_ONLYDIR);
343 343
         if (empty($plugins)) {
344 344
             return;
345 345
         }
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
                 || strpos($plugin, 'calendar') !== false
357 357
             ) {
358 358
                 // this is what we are looking for
359
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
359
+                $calendar_config = $plugin_path.DS.'EE_Calendar_Config.php';
360 360
                 // does it exist in this folder ?
361 361
                 if (is_readable($calendar_config)) {
362 362
                     // YEAH! let's load it
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
             ) {
490 490
                 //update Config with post ID
491 491
                 $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
492
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
492
+                if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
493 493
                     $msg = __(
494 494
                         'The Event Espresso critical page configuration settings could not be updated.',
495 495
                         'event_espresso'
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
     public static function get_page_by_ee_shortcode($ee_shortcode)
539 539
     {
540 540
         global $wpdb;
541
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
541
+        $shortcode_and_opening_bracket = '['.$ee_shortcode;
542 542
         $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
543 543
         if ($post_id) {
544 544
             return get_post($post_id);
@@ -564,11 +564,11 @@  discard block
 block discarded – undo
564 564
             'post_status'    => 'publish',
565 565
             'post_type'      => 'page',
566 566
             'comment_status' => 'closed',
567
-            'post_content'   => '[' . $critical_page['code'] . ']',
567
+            'post_content'   => '['.$critical_page['code'].']',
568 568
         );
569 569
 
570 570
         $post_id = wp_insert_post($post_args);
571
-        if (! $post_id) {
571
+        if ( ! $post_id) {
572 572
             $msg = sprintf(
573 573
                 __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
574 574
                 $critical_page['name']
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
             return $critical_page;
578 578
         }
579 579
         // get newly created post's details
580
-        if (! $critical_page['post'] = get_post($post_id)) {
580
+        if ( ! $critical_page['post'] = get_post($post_id)) {
581 581
             $msg = sprintf(
582 582
                 __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
583 583
                 $critical_page['name']
@@ -664,17 +664,17 @@  discard block
 block discarded – undo
664 664
             $role_to_check
665 665
         );
666 666
         if ($pre_filtered_id !== false) {
667
-            return (int)$pre_filtered_id;
667
+            return (int) $pre_filtered_id;
668 668
         }
669 669
         $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
670 670
         $query = $wpdb->prepare(
671 671
             "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
672
-            '%' . $role_to_check . '%'
672
+            '%'.$role_to_check.'%'
673 673
         );
674 674
         $user_id = $wpdb->get_var($query);
675 675
         $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
676
-        if ($user_id && (int)$user_id) {
677
-            self::$_default_creator_id = (int)$user_id;
676
+        if ($user_id && (int) $user_id) {
677
+            self::$_default_creator_id = (int) $user_id;
678 678
             return self::$_default_creator_id;
679 679
         } else {
680 680
             return null;
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
         }
710 710
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
711 711
         if ( ! function_exists('dbDelta')) {
712
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
712
+            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
713 713
         }
714 714
         $tableAnalysis = \EEH_Activation::getTableAnalysis();
715 715
         $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
@@ -920,13 +920,13 @@  discard block
 block discarded – undo
920 920
             // reset values array
921 921
             $QSG_values = array();
922 922
             // 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)
923
-            if (! in_array("$QSG_system", $question_groups)) {
923
+            if ( ! in_array("$QSG_system", $question_groups)) {
924 924
                 // add it
925 925
                 switch ($QSG_system) {
926 926
                     case 1:
927 927
                         $QSG_values = array(
928 928
                             'QSG_name'            => __('Personal Information', 'event_espresso'),
929
-                            'QSG_identifier'      => 'personal-information-' . time(),
929
+                            'QSG_identifier'      => 'personal-information-'.time(),
930 930
                             'QSG_desc'            => '',
931 931
                             'QSG_order'           => 1,
932 932
                             'QSG_show_group_name' => 1,
@@ -938,7 +938,7 @@  discard block
 block discarded – undo
938 938
                     case 2:
939 939
                         $QSG_values = array(
940 940
                             'QSG_name'            => __('Address Information', 'event_espresso'),
941
-                            'QSG_identifier'      => 'address-information-' . time(),
941
+                            'QSG_identifier'      => 'address-information-'.time(),
942 942
                             'QSG_desc'            => '',
943 943
                             'QSG_order'           => 2,
944 944
                             'QSG_show_group_name' => 1,
@@ -949,7 +949,7 @@  discard block
 block discarded – undo
949 949
                         break;
950 950
                 }
951 951
                 // make sure we have some values before inserting them
952
-                if (! empty($QSG_values)) {
952
+                if ( ! empty($QSG_values)) {
953 953
                     // insert system question
954 954
                     $wpdb->insert(
955 955
                         $table_name,
@@ -986,7 +986,7 @@  discard block
 block discarded – undo
986 986
             // reset values array
987 987
             $QST_values = array();
988 988
             // if we don't have what we should have
989
-            if (! in_array($QST_system, $questions)) {
989
+            if ( ! in_array($QST_system, $questions)) {
990 990
                 // add it
991 991
                 switch ($QST_system) {
992 992
                     case 'fname':
@@ -1138,7 +1138,7 @@  discard block
 block discarded – undo
1138 1138
                         );
1139 1139
                         break;
1140 1140
                 }
1141
-                if (! empty($QST_values)) {
1141
+                if ( ! empty($QST_values)) {
1142 1142
                     // insert system question
1143 1143
                     $wpdb->insert(
1144 1144
                         $table_name,
@@ -1199,7 +1199,7 @@  discard block
 block discarded – undo
1199 1199
      */
1200 1200
     public static function insert_default_payment_methods()
1201 1201
     {
1202
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1202
+        if ( ! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1203 1203
             EE_Registry::instance()->load_lib('Payment_Method_Manager');
1204 1204
             EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1205 1205
         } else {
@@ -1287,9 +1287,9 @@  discard block
 block discarded – undo
1287 1287
         $folders = array(
1288 1288
             EVENT_ESPRESSO_TEMPLATE_DIR,
1289 1289
             EVENT_ESPRESSO_GATEWAY_DIR,
1290
-            EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1291
-            EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1292
-            EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1290
+            EVENT_ESPRESSO_UPLOAD_DIR.'logs/',
1291
+            EVENT_ESPRESSO_UPLOAD_DIR.'css/',
1292
+            EVENT_ESPRESSO_UPLOAD_DIR.'tickets/',
1293 1293
         );
1294 1294
         foreach ($folders as $folder) {
1295 1295
             try {
@@ -1300,7 +1300,7 @@  discard block
 block discarded – undo
1300 1300
                     sprintf(
1301 1301
                         __('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1302 1302
                         $folder,
1303
-                        '<br />' . $e->getMessage()
1303
+                        '<br />'.$e->getMessage()
1304 1304
                     ),
1305 1305
                     __FILE__, __FUNCTION__, __LINE__
1306 1306
                 );
@@ -1311,7 +1311,7 @@  discard block
 block discarded – undo
1311 1311
         }
1312 1312
         //just add the .htaccess file to the logs directory to begin with. Even if logging
1313 1313
         //is disabled, there might be activation errors recorded in there
1314
-        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1314
+        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR.'logs/');
1315 1315
         //remember EE's folders are all good
1316 1316
         delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1317 1317
         return true;
@@ -1547,7 +1547,7 @@  discard block
 block discarded – undo
1547 1547
         // this creates an array for tracking events that have no active ticket prices created
1548 1548
         // this allows us to warn admins of the situation so that it can be corrected
1549 1549
         $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1550
-        if (! $espresso_no_ticket_prices) {
1550
+        if ( ! $espresso_no_ticket_prices) {
1551 1551
             add_option('ee_no_ticket_prices', array(), '', false);
1552 1552
         }
1553 1553
     }
@@ -1586,7 +1586,7 @@  discard block
 block discarded – undo
1586 1586
             }
1587 1587
         }
1588 1588
         //get all our CPTs
1589
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1589
+        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (".implode(",", $ee_post_types).")";
1590 1590
         $cpt_ids = $wpdb->get_col($query);
1591 1591
         //delete each post meta and term relations too
1592 1592
         foreach ($cpt_ids as $post_id) {
@@ -1726,7 +1726,7 @@  discard block
 block discarded – undo
1726 1726
         if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1727 1727
             $db_update_sans_ee4 = array();
1728 1728
             foreach ($espresso_db_update as $version => $times_activated) {
1729
-                if ((string)$version[0] === '3') {//if its NON EE4
1729
+                if ((string) $version[0] === '3') {//if its NON EE4
1730 1730
                     $db_update_sans_ee4[$version] = $times_activated;
1731 1731
                 }
1732 1732
             }
Please login to merge, or discard this patch.
Indentation   +1653 added lines, -1653 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\interfaces\ResettableInterface;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -17,244 +17,244 @@  discard block
 block discarded – undo
17 17
 class EEH_Activation implements ResettableInterface
18 18
 {
19 19
 
20
-    /**
21
-     * constant used to indicate a cron task is no longer in use
22
-     */
23
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
24
-
25
-    /**
26
-     * option name that will indicate whether or not we still
27
-     * need to create EE's folders in the uploads directory
28
-     * (because if EE was installed without file system access,
29
-     * we need to request credentials before we can create them)
30
-     */
31
-    const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
32
-
33
-    /**
34
-     * WP_User->ID
35
-     *
36
-     * @var int
37
-     */
38
-    private static $_default_creator_id;
39
-
40
-    /**
41
-     * indicates whether or not we've already verified core's default data during this request,
42
-     * because after migrations are done, any addons activated while in maintenance mode
43
-     * will want to setup their own default data, and they might hook into core's default data
44
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
45
-     * This prevents doing that for EVERY single addon.
46
-     *
47
-     * @var boolean
48
-     */
49
-    protected static $_initialized_db_content_already_in_this_request = false;
50
-
51
-    /**
52
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
53
-     */
54
-    private static $table_analysis;
55
-
56
-    /**
57
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
58
-     */
59
-    private static $table_manager;
60
-
61
-
62
-    /**
63
-     * @return \EventEspresso\core\services\database\TableAnalysis
64
-     */
65
-    public static function getTableAnalysis()
66
-    {
67
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
68
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
69
-        }
70
-        return self::$table_analysis;
71
-    }
72
-
73
-
74
-    /**
75
-     * @return \EventEspresso\core\services\database\TableManager
76
-     */
77
-    public static function getTableManager()
78
-    {
79
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
80
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
81
-        }
82
-        return self::$table_manager;
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
-     *    system_initialization
103
-     *    ensures the EE configuration settings are loaded with at least default options set
104
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
105
-     *
106
-     * @access public
107
-     * @static
108
-     * @return void
109
-     */
110
-    public static function system_initialization()
111
-    {
112
-        EEH_Activation::reset_and_update_config();
113
-        //which is fired BEFORE activation of plugin anyways
114
-        EEH_Activation::verify_default_pages_exist();
115
-    }
116
-
117
-
118
-    /**
119
-     * Sets the database schema and creates folders. This should
120
-     * be called on plugin activation and reactivation
121
-     *
122
-     * @return boolean success, whether the database and folders are setup properly
123
-     * @throws \EE_Error
124
-     */
125
-    public static function initialize_db_and_folders()
126
-    {
127
-        $good_filesystem = EEH_Activation::create_upload_directories();
128
-        $good_db         = EEH_Activation::create_database_tables();
129
-        return $good_filesystem && $good_db;
130
-    }
131
-
132
-
133
-    /**
134
-     * assuming we have an up-to-date database schema, this will populate it
135
-     * with default and initial data. This should be called
136
-     * upon activation of a new plugin, reactivation, and at the end
137
-     * of running migration scripts
138
-     *
139
-     * @throws \EE_Error
140
-     */
141
-    public static function initialize_db_content()
142
-    {
143
-        //let's avoid doing all this logic repeatedly, especially when addons are requesting it
144
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
145
-            return;
146
-        }
147
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
148
-
149
-        EEH_Activation::initialize_system_questions();
150
-        EEH_Activation::insert_default_status_codes();
151
-        EEH_Activation::generate_default_message_templates();
152
-        EEH_Activation::create_no_ticket_prices_array();
153
-        EE_Registry::instance()->CAP->init_caps();
154
-
155
-        EEH_Activation::validate_messages_system();
156
-        EEH_Activation::insert_default_payment_methods();
157
-        //in case we've
158
-        EEH_Activation::remove_cron_tasks();
159
-        EEH_Activation::create_cron_tasks();
160
-        // remove all TXN locks since that is being done via extra meta now
161
-        delete_option('ee_locked_transactions');
162
-        //also, check for CAF default db content
163
-        do_action('AHEE__EEH_Activation__initialize_db_content');
164
-        //also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
165
-        //which users really won't care about on initial activation
166
-        EE_Error::overwrite_success();
167
-    }
168
-
169
-
170
-    /**
171
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
172
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
173
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
174
-     * (null)
175
-     *
176
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
177
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
178
-     * @return array
179
-     * @throws \EE_Error
180
-     */
181
-    public static function get_cron_tasks($which_to_include)
182
-    {
183
-        $cron_tasks = apply_filters(
184
-            'FHEE__EEH_Activation__get_cron_tasks',
185
-            array(
186
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
20
+	/**
21
+	 * constant used to indicate a cron task is no longer in use
22
+	 */
23
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
24
+
25
+	/**
26
+	 * option name that will indicate whether or not we still
27
+	 * need to create EE's folders in the uploads directory
28
+	 * (because if EE was installed without file system access,
29
+	 * we need to request credentials before we can create them)
30
+	 */
31
+	const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
32
+
33
+	/**
34
+	 * WP_User->ID
35
+	 *
36
+	 * @var int
37
+	 */
38
+	private static $_default_creator_id;
39
+
40
+	/**
41
+	 * indicates whether or not we've already verified core's default data during this request,
42
+	 * because after migrations are done, any addons activated while in maintenance mode
43
+	 * will want to setup their own default data, and they might hook into core's default data
44
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
45
+	 * This prevents doing that for EVERY single addon.
46
+	 *
47
+	 * @var boolean
48
+	 */
49
+	protected static $_initialized_db_content_already_in_this_request = false;
50
+
51
+	/**
52
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
53
+	 */
54
+	private static $table_analysis;
55
+
56
+	/**
57
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
58
+	 */
59
+	private static $table_manager;
60
+
61
+
62
+	/**
63
+	 * @return \EventEspresso\core\services\database\TableAnalysis
64
+	 */
65
+	public static function getTableAnalysis()
66
+	{
67
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
68
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
69
+		}
70
+		return self::$table_analysis;
71
+	}
72
+
73
+
74
+	/**
75
+	 * @return \EventEspresso\core\services\database\TableManager
76
+	 */
77
+	public static function getTableManager()
78
+	{
79
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
80
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
81
+		}
82
+		return self::$table_manager;
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
+	 *    system_initialization
103
+	 *    ensures the EE configuration settings are loaded with at least default options set
104
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
105
+	 *
106
+	 * @access public
107
+	 * @static
108
+	 * @return void
109
+	 */
110
+	public static function system_initialization()
111
+	{
112
+		EEH_Activation::reset_and_update_config();
113
+		//which is fired BEFORE activation of plugin anyways
114
+		EEH_Activation::verify_default_pages_exist();
115
+	}
116
+
117
+
118
+	/**
119
+	 * Sets the database schema and creates folders. This should
120
+	 * be called on plugin activation and reactivation
121
+	 *
122
+	 * @return boolean success, whether the database and folders are setup properly
123
+	 * @throws \EE_Error
124
+	 */
125
+	public static function initialize_db_and_folders()
126
+	{
127
+		$good_filesystem = EEH_Activation::create_upload_directories();
128
+		$good_db         = EEH_Activation::create_database_tables();
129
+		return $good_filesystem && $good_db;
130
+	}
131
+
132
+
133
+	/**
134
+	 * assuming we have an up-to-date database schema, this will populate it
135
+	 * with default and initial data. This should be called
136
+	 * upon activation of a new plugin, reactivation, and at the end
137
+	 * of running migration scripts
138
+	 *
139
+	 * @throws \EE_Error
140
+	 */
141
+	public static function initialize_db_content()
142
+	{
143
+		//let's avoid doing all this logic repeatedly, especially when addons are requesting it
144
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
145
+			return;
146
+		}
147
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
148
+
149
+		EEH_Activation::initialize_system_questions();
150
+		EEH_Activation::insert_default_status_codes();
151
+		EEH_Activation::generate_default_message_templates();
152
+		EEH_Activation::create_no_ticket_prices_array();
153
+		EE_Registry::instance()->CAP->init_caps();
154
+
155
+		EEH_Activation::validate_messages_system();
156
+		EEH_Activation::insert_default_payment_methods();
157
+		//in case we've
158
+		EEH_Activation::remove_cron_tasks();
159
+		EEH_Activation::create_cron_tasks();
160
+		// remove all TXN locks since that is being done via extra meta now
161
+		delete_option('ee_locked_transactions');
162
+		//also, check for CAF default db content
163
+		do_action('AHEE__EEH_Activation__initialize_db_content');
164
+		//also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
165
+		//which users really won't care about on initial activation
166
+		EE_Error::overwrite_success();
167
+	}
168
+
169
+
170
+	/**
171
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
172
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
173
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
174
+	 * (null)
175
+	 *
176
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
177
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
178
+	 * @return array
179
+	 * @throws \EE_Error
180
+	 */
181
+	public static function get_cron_tasks($which_to_include)
182
+	{
183
+		$cron_tasks = apply_filters(
184
+			'FHEE__EEH_Activation__get_cron_tasks',
185
+			array(
186
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
187 187
 //				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
188
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
189
-                //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
190
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
191
-            )
192
-        );
193
-        if ($which_to_include === 'old') {
194
-            $cron_tasks = array_filter(
195
-                $cron_tasks,
196
-                function ($value) {
197
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
198
-                }
199
-            );
200
-        } elseif ($which_to_include === 'current') {
201
-            $cron_tasks = array_filter($cron_tasks);
202
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
203
-            throw new EE_Error(
204
-                sprintf(
205
-                    __(
206
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
207
-                        'event_espresso'
208
-                    ),
209
-                    $which_to_include
210
-                )
211
-            );
212
-        }
213
-        return $cron_tasks;
214
-    }
215
-
216
-
217
-    /**
218
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
219
-     *
220
-     * @throws \EE_Error
221
-     */
222
-    public static function create_cron_tasks()
223
-    {
224
-
225
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
226
-            if (! wp_next_scheduled($hook_name)) {
227
-                /**
228
-                 * This allows client code to define the initial start timestamp for this schedule.
229
-                 */
230
-                if (is_array($frequency)
231
-                    && count($frequency) === 2
232
-                    && isset($frequency[0], $frequency[1])
233
-                ) {
234
-                    $start_timestamp = $frequency[0];
235
-                    $frequency = $frequency[1];
236
-                } else {
237
-                    $start_timestamp = time();
238
-                }
239
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
240
-            }
241
-        }
242
-
243
-    }
244
-
245
-
246
-    /**
247
-     * Remove the currently-existing and now-removed cron tasks.
248
-     *
249
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
250
-     * @throws \EE_Error
251
-     */
252
-    public static function remove_cron_tasks($remove_all = true)
253
-    {
254
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
255
-        $crons                = _get_cron_array();
256
-        $crons                = is_array($crons) ? $crons : array();
257
-        /* reminder of what $crons look like:
188
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
189
+				//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
190
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
191
+			)
192
+		);
193
+		if ($which_to_include === 'old') {
194
+			$cron_tasks = array_filter(
195
+				$cron_tasks,
196
+				function ($value) {
197
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
198
+				}
199
+			);
200
+		} elseif ($which_to_include === 'current') {
201
+			$cron_tasks = array_filter($cron_tasks);
202
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
203
+			throw new EE_Error(
204
+				sprintf(
205
+					__(
206
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
207
+						'event_espresso'
208
+					),
209
+					$which_to_include
210
+				)
211
+			);
212
+		}
213
+		return $cron_tasks;
214
+	}
215
+
216
+
217
+	/**
218
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
219
+	 *
220
+	 * @throws \EE_Error
221
+	 */
222
+	public static function create_cron_tasks()
223
+	{
224
+
225
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
226
+			if (! wp_next_scheduled($hook_name)) {
227
+				/**
228
+				 * This allows client code to define the initial start timestamp for this schedule.
229
+				 */
230
+				if (is_array($frequency)
231
+					&& count($frequency) === 2
232
+					&& isset($frequency[0], $frequency[1])
233
+				) {
234
+					$start_timestamp = $frequency[0];
235
+					$frequency = $frequency[1];
236
+				} else {
237
+					$start_timestamp = time();
238
+				}
239
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
240
+			}
241
+		}
242
+
243
+	}
244
+
245
+
246
+	/**
247
+	 * Remove the currently-existing and now-removed cron tasks.
248
+	 *
249
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
250
+	 * @throws \EE_Error
251
+	 */
252
+	public static function remove_cron_tasks($remove_all = true)
253
+	{
254
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
255
+		$crons                = _get_cron_array();
256
+		$crons                = is_array($crons) ? $crons : array();
257
+		/* reminder of what $crons look like:
258 258
          * Top-level keys are timestamps, and their values are arrays.
259 259
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
260 260
          * and their values are arrays.
@@ -271,912 +271,912 @@  discard block
 block discarded – undo
271 271
          *					...
272 272
          *      ...
273 273
          */
274
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
275
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
276
-            if (is_array($hooks_to_fire_at_time)) {
277
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
278
-                    if (isset($ee_cron_tasks_to_remove[$hook_name])
279
-                        && is_array($ee_cron_tasks_to_remove[$hook_name])
280
-                    ) {
281
-                        unset($crons[$timestamp][$hook_name]);
282
-                    }
283
-                }
284
-                //also take care of any empty cron timestamps.
285
-                if (empty($hooks_to_fire_at_time)) {
286
-                    unset($crons[$timestamp]);
287
-                }
288
-            }
289
-        }
290
-        _set_cron_array($crons);
291
-    }
292
-
293
-
294
-    /**
295
-     *    CPT_initialization
296
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
297
-     *
298
-     * @access public
299
-     * @static
300
-     * @return void
301
-     */
302
-    public static function CPT_initialization()
303
-    {
304
-        // register Custom Post Types
305
-        EE_Registry::instance()->load_core('Register_CPTs');
306
-        flush_rewrite_rules();
307
-    }
308
-
309
-
310
-
311
-    /**
312
-     *    reset_and_update_config
313
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
314
-     * If there is old calendar config data saved, then it will get converted on activation.
315
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
316
-     *
317
-     * @access public
318
-     * @static
319
-     * @return void
320
-     */
321
-    public static function reset_and_update_config()
322
-    {
323
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
324
-        add_filter(
325
-            'FHEE__EE_Config___load_core_config__config_settings',
326
-            array('EEH_Activation', 'migrate_old_config_data'),
327
-            10,
328
-            3
329
-        );
330
-        //EE_Config::reset();
331
-        if (! EE_Config::logging_enabled()) {
332
-            delete_option(EE_Config::LOG_NAME);
333
-        }
334
-    }
335
-
336
-
337
-    /**
338
-     *    load_calendar_config
339
-     *
340
-     * @access    public
341
-     * @return    void
342
-     */
343
-    public static function load_calendar_config()
344
-    {
345
-        // grab array of all plugin folders and loop thru it
346
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
347
-        if (empty($plugins)) {
348
-            return;
349
-        }
350
-        foreach ($plugins as $plugin_path) {
351
-            // grab plugin folder name from path
352
-            $plugin = basename($plugin_path);
353
-            // drill down to Espresso plugins
354
-            // then to calendar related plugins
355
-            if (
356
-                strpos($plugin, 'espresso') !== false
357
-                || strpos($plugin, 'Espresso') !== false
358
-                || strpos($plugin, 'ee4') !== false
359
-                || strpos($plugin, 'EE4') !== false
360
-                || strpos($plugin, 'calendar') !== false
361
-            ) {
362
-                // this is what we are looking for
363
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
364
-                // does it exist in this folder ?
365
-                if (is_readable($calendar_config)) {
366
-                    // YEAH! let's load it
367
-                    require_once($calendar_config);
368
-                }
369
-            }
370
-        }
371
-    }
372
-
373
-
374
-
375
-    /**
376
-     *    _migrate_old_config_data
377
-     *
378
-     * @access    public
379
-     * @param array|stdClass $settings
380
-     * @param string         $config
381
-     * @param \EE_Config     $EE_Config
382
-     * @return \stdClass
383
-     */
384
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
385
-    {
386
-        $convert_from_array = array('addons');
387
-        // in case old settings were saved as an array
388
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
389
-            // convert existing settings to an object
390
-            $config_array = $settings;
391
-            $settings = new stdClass();
392
-            foreach ($config_array as $key => $value) {
393
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
394
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
395
-                } else {
396
-                    $settings->{$key} = $value;
397
-                }
398
-            }
399
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
400
-        }
401
-        return $settings;
402
-    }
403
-
404
-
405
-    /**
406
-     * deactivate_event_espresso
407
-     *
408
-     * @access public
409
-     * @static
410
-     * @return void
411
-     */
412
-    public static function deactivate_event_espresso()
413
-    {
414
-        // check permissions
415
-        if (current_user_can('activate_plugins')) {
416
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
417
-        }
418
-    }
419
-
420
-
421
-
422
-
423
-
424
-    /**
425
-     * verify_default_pages_exist
426
-     *
427
-     * @access public
428
-     * @static
429
-     * @return void
430
-     */
431
-    public static function verify_default_pages_exist()
432
-    {
433
-        $critical_page_problem = false;
434
-        $critical_pages = array(
435
-            array(
436
-                'id'   => 'reg_page_id',
437
-                'name' => __('Registration Checkout', 'event_espresso'),
438
-                'post' => null,
439
-                'code' => 'ESPRESSO_CHECKOUT',
440
-            ),
441
-            array(
442
-                'id'   => 'txn_page_id',
443
-                'name' => __('Transactions', 'event_espresso'),
444
-                'post' => null,
445
-                'code' => 'ESPRESSO_TXN_PAGE',
446
-            ),
447
-            array(
448
-                'id'   => 'thank_you_page_id',
449
-                'name' => __('Thank You', 'event_espresso'),
450
-                'post' => null,
451
-                'code' => 'ESPRESSO_THANK_YOU',
452
-            ),
453
-            array(
454
-                'id'   => 'cancel_page_id',
455
-                'name' => __('Registration Cancelled', 'event_espresso'),
456
-                'post' => null,
457
-                'code' => 'ESPRESSO_CANCELLED',
458
-            ),
459
-        );
460
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
461
-        foreach ($critical_pages as $critical_page) {
462
-            // is critical page ID set in config ?
463
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
464
-                // attempt to find post by ID
465
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
466
-            }
467
-            // no dice?
468
-            if ($critical_page['post'] === null) {
469
-                // attempt to find post by title
470
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
471
-                // still nothing?
472
-                if ($critical_page['post'] === null) {
473
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
474
-                    // REALLY? Still nothing ??!?!?
475
-                    if ($critical_page['post'] === null) {
476
-                        $msg = __(
477
-                            'The Event Espresso critical page configuration settings could not be updated.',
478
-                            'event_espresso'
479
-                        );
480
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
481
-                        break;
482
-                    }
483
-                }
484
-            }
485
-            // check that Post ID matches critical page ID in config
486
-            if (
487
-                isset($critical_page['post']->ID)
488
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
489
-            ) {
490
-                //update Config with post ID
491
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
492
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
493
-                    $msg = __(
494
-                        'The Event Espresso critical page configuration settings could not be updated.',
495
-                        'event_espresso'
496
-                    );
497
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
498
-                }
499
-            }
500
-            $critical_page_problem =
501
-                ! isset($critical_page['post']->post_status)
502
-                || $critical_page['post']->post_status !== 'publish'
503
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
504
-                    ? true
505
-                    : $critical_page_problem;
506
-        }
507
-        if ($critical_page_problem) {
508
-            $msg = sprintf(
509
-                __(
510
-                    'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
511
-                    'event_espresso'
512
-                ),
513
-                '<a href="'
514
-                . admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
515
-                . '">'
516
-                . __('Event Espresso Critical Pages Settings', 'event_espresso')
517
-                . '</a>'
518
-            );
519
-            EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
520
-        }
521
-        if (EE_Error::has_notices()) {
522
-            EE_Error::get_notices(false, true, true);
523
-        }
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * Returns the first post which uses the specified shortcode
530
-     *
531
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
532
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
533
-     *                             "[ESPRESSO_THANK_YOU"
534
-     *                             (we don't search for the closing shortcode bracket because they might have added
535
-     *                             parameter to the shortcode
536
-     * @return WP_Post or NULl
537
-     */
538
-    public static function get_page_by_ee_shortcode($ee_shortcode)
539
-    {
540
-        global $wpdb;
541
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
542
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
543
-        if ($post_id) {
544
-            return get_post($post_id);
545
-        } else {
546
-            return null;
547
-        }
548
-    }
549
-
550
-
551
-    /**
552
-     *    This function generates a post for critical espresso pages
553
-     *
554
-     * @access public
555
-     * @static
556
-     * @param array $critical_page
557
-     * @return array
558
-     */
559
-    public static function create_critical_page($critical_page)
560
-    {
561
-
562
-        $post_args = array(
563
-            'post_title'     => $critical_page['name'],
564
-            'post_status'    => 'publish',
565
-            'post_type'      => 'page',
566
-            'comment_status' => 'closed',
567
-            'post_content'   => '[' . $critical_page['code'] . ']',
568
-        );
569
-
570
-        $post_id = wp_insert_post($post_args);
571
-        if (! $post_id) {
572
-            $msg = sprintf(
573
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
574
-                $critical_page['name']
575
-            );
576
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
577
-            return $critical_page;
578
-        }
579
-        // get newly created post's details
580
-        if (! $critical_page['post'] = get_post($post_id)) {
581
-            $msg = sprintf(
582
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
583
-                $critical_page['name']
584
-            );
585
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
586
-        }
587
-
588
-        return $critical_page;
589
-
590
-    }
591
-
592
-
593
-
594
-
595
-    /**
596
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
597
-     * The role being used to check is filterable.
598
-     *
599
-     * @since  4.6.0
600
-     * @global WPDB $wpdb
601
-     * @return mixed null|int WP_user ID or NULL
602
-     */
603
-    public static function get_default_creator_id()
604
-    {
605
-        global $wpdb;
606
-        if ( ! empty(self::$_default_creator_id)) {
607
-            return self::$_default_creator_id;
608
-        }/**/
609
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
610
-        //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.
611
-        $pre_filtered_id = apply_filters(
612
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
613
-            false,
614
-            $role_to_check
615
-        );
616
-        if ($pre_filtered_id !== false) {
617
-            return (int)$pre_filtered_id;
618
-        }
619
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
620
-        $query = $wpdb->prepare(
621
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
622
-            '%' . $role_to_check . '%'
623
-        );
624
-        $user_id = $wpdb->get_var($query);
625
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
626
-        if ($user_id && (int)$user_id) {
627
-            self::$_default_creator_id = (int)$user_id;
628
-            return self::$_default_creator_id;
629
-        } else {
630
-            return null;
631
-        }
632
-    }
633
-
634
-
635
-
636
-    /**
637
-     * used by EE and EE addons during plugin activation to create tables.
638
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
639
-     * but includes extra logic regarding activations.
640
-     *
641
-     * @access public
642
-     * @static
643
-     * @param string  $table_name              without the $wpdb->prefix
644
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
645
-     *                                         table query)
646
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
647
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
648
-     *                                         and new once this function is done (ie, you really do want to CREATE a
649
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
650
-     *                                         you just want to verify the table exists and matches this definition
651
-     *                                         (and if it HAS data in it you want to leave it be)
652
-     * @return void
653
-     * @throws EE_Error if there are database errors
654
-     */
655
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
656
-    {
657
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
658
-            return;
659
-        }
660
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
661
-        if ( ! function_exists('dbDelta')) {
662
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
663
-        }
664
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
665
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
666
-        // do we need to first delete an existing version of this table ?
667
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
668
-            // ok, delete the table... but ONLY if it's empty
669
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
670
-            // table is NOT empty, are you SURE you want to delete this table ???
671
-            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
672
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
673
-            } else if ( ! $deleted_safely) {
674
-                // so we should be more cautious rather than just dropping tables so easily
675
-                error_log(
676
-                    sprintf(
677
-                        __(
678
-                            'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
679
-                            'event_espresso'
680
-                        ),
681
-                        $wp_table_name,
682
-                        '<br/>',
683
-                        'espresso_db_update'
684
-                    )
685
-                );
686
-            }
687
-        }
688
-        $engine = str_replace('ENGINE=', '', $engine);
689
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
690
-    }
691
-
692
-
693
-
694
-    /**
695
-     *    add_column_if_it_doesn't_exist
696
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
697
-     *
698
-     * @access     public
699
-     * @static
700
-     * @deprecated instead use TableManager::addColumn()
701
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
702
-     * @param string $column_name
703
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
704
-     *                            'VARCHAR(10)'
705
-     * @return bool|int
706
-     */
707
-    public static function add_column_if_it_doesnt_exist(
708
-        $table_name,
709
-        $column_name,
710
-        $column_info = 'INT UNSIGNED NOT NULL'
711
-    ) {
712
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
713
-    }
714
-
715
-
716
-    /**
717
-     * get_fields_on_table
718
-     * Gets all the fields on the database table.
719
-     *
720
-     * @access     public
721
-     * @deprecated instead use TableManager::getTableColumns()
722
-     * @static
723
-     * @param string $table_name , without prefixed $wpdb->prefix
724
-     * @return array of database column names
725
-     */
726
-    public static function get_fields_on_table($table_name = null)
727
-    {
728
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
729
-    }
730
-
731
-
732
-    /**
733
-     * db_table_is_empty
734
-     *
735
-     * @access     public\
736
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
737
-     * @static
738
-     * @param string $table_name
739
-     * @return bool
740
-     */
741
-    public static function db_table_is_empty($table_name)
742
-    {
743
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
744
-    }
745
-
746
-
747
-    /**
748
-     * delete_db_table_if_empty
749
-     *
750
-     * @access public
751
-     * @static
752
-     * @param string $table_name
753
-     * @return bool | int
754
-     */
755
-    public static function delete_db_table_if_empty($table_name)
756
-    {
757
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
758
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
759
-        }
760
-        return false;
761
-    }
762
-
763
-
764
-    /**
765
-     * delete_unused_db_table
766
-     *
767
-     * @access     public
768
-     * @static
769
-     * @deprecated instead use TableManager::dropTable()
770
-     * @param string $table_name
771
-     * @return bool | int
772
-     */
773
-    public static function delete_unused_db_table($table_name)
774
-    {
775
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
776
-    }
777
-
778
-
779
-    /**
780
-     * drop_index
781
-     *
782
-     * @access     public
783
-     * @static
784
-     * @deprecated instead use TableManager::dropIndex()
785
-     * @param string $table_name
786
-     * @param string $index_name
787
-     * @return bool | int
788
-     */
789
-    public static function drop_index($table_name, $index_name)
790
-    {
791
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
792
-    }
793
-
794
-
795
-
796
-    /**
797
-     * create_database_tables
798
-     *
799
-     * @access public
800
-     * @static
801
-     * @throws EE_Error
802
-     * @return boolean success (whether database is setup properly or not)
803
-     */
804
-    public static function create_database_tables()
805
-    {
806
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
807
-        //find the migration script that sets the database to be compatible with the code
808
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
809
-        if ($dms_name) {
810
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
811
-            $current_data_migration_script->set_migrating(false);
812
-            $current_data_migration_script->schema_changes_before_migration();
813
-            $current_data_migration_script->schema_changes_after_migration();
814
-            if ($current_data_migration_script->get_errors()) {
815
-                if (WP_DEBUG) {
816
-                    foreach ($current_data_migration_script->get_errors() as $error) {
817
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
818
-                    }
819
-                } else {
820
-                    EE_Error::add_error(
821
-                        __(
822
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
274
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
275
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
276
+			if (is_array($hooks_to_fire_at_time)) {
277
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
278
+					if (isset($ee_cron_tasks_to_remove[$hook_name])
279
+						&& is_array($ee_cron_tasks_to_remove[$hook_name])
280
+					) {
281
+						unset($crons[$timestamp][$hook_name]);
282
+					}
283
+				}
284
+				//also take care of any empty cron timestamps.
285
+				if (empty($hooks_to_fire_at_time)) {
286
+					unset($crons[$timestamp]);
287
+				}
288
+			}
289
+		}
290
+		_set_cron_array($crons);
291
+	}
292
+
293
+
294
+	/**
295
+	 *    CPT_initialization
296
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
297
+	 *
298
+	 * @access public
299
+	 * @static
300
+	 * @return void
301
+	 */
302
+	public static function CPT_initialization()
303
+	{
304
+		// register Custom Post Types
305
+		EE_Registry::instance()->load_core('Register_CPTs');
306
+		flush_rewrite_rules();
307
+	}
308
+
309
+
310
+
311
+	/**
312
+	 *    reset_and_update_config
313
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
314
+	 * If there is old calendar config data saved, then it will get converted on activation.
315
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
316
+	 *
317
+	 * @access public
318
+	 * @static
319
+	 * @return void
320
+	 */
321
+	public static function reset_and_update_config()
322
+	{
323
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
324
+		add_filter(
325
+			'FHEE__EE_Config___load_core_config__config_settings',
326
+			array('EEH_Activation', 'migrate_old_config_data'),
327
+			10,
328
+			3
329
+		);
330
+		//EE_Config::reset();
331
+		if (! EE_Config::logging_enabled()) {
332
+			delete_option(EE_Config::LOG_NAME);
333
+		}
334
+	}
335
+
336
+
337
+	/**
338
+	 *    load_calendar_config
339
+	 *
340
+	 * @access    public
341
+	 * @return    void
342
+	 */
343
+	public static function load_calendar_config()
344
+	{
345
+		// grab array of all plugin folders and loop thru it
346
+		$plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
347
+		if (empty($plugins)) {
348
+			return;
349
+		}
350
+		foreach ($plugins as $plugin_path) {
351
+			// grab plugin folder name from path
352
+			$plugin = basename($plugin_path);
353
+			// drill down to Espresso plugins
354
+			// then to calendar related plugins
355
+			if (
356
+				strpos($plugin, 'espresso') !== false
357
+				|| strpos($plugin, 'Espresso') !== false
358
+				|| strpos($plugin, 'ee4') !== false
359
+				|| strpos($plugin, 'EE4') !== false
360
+				|| strpos($plugin, 'calendar') !== false
361
+			) {
362
+				// this is what we are looking for
363
+				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
364
+				// does it exist in this folder ?
365
+				if (is_readable($calendar_config)) {
366
+					// YEAH! let's load it
367
+					require_once($calendar_config);
368
+				}
369
+			}
370
+		}
371
+	}
372
+
373
+
374
+
375
+	/**
376
+	 *    _migrate_old_config_data
377
+	 *
378
+	 * @access    public
379
+	 * @param array|stdClass $settings
380
+	 * @param string         $config
381
+	 * @param \EE_Config     $EE_Config
382
+	 * @return \stdClass
383
+	 */
384
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
385
+	{
386
+		$convert_from_array = array('addons');
387
+		// in case old settings were saved as an array
388
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
389
+			// convert existing settings to an object
390
+			$config_array = $settings;
391
+			$settings = new stdClass();
392
+			foreach ($config_array as $key => $value) {
393
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
394
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
395
+				} else {
396
+					$settings->{$key} = $value;
397
+				}
398
+			}
399
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
400
+		}
401
+		return $settings;
402
+	}
403
+
404
+
405
+	/**
406
+	 * deactivate_event_espresso
407
+	 *
408
+	 * @access public
409
+	 * @static
410
+	 * @return void
411
+	 */
412
+	public static function deactivate_event_espresso()
413
+	{
414
+		// check permissions
415
+		if (current_user_can('activate_plugins')) {
416
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
417
+		}
418
+	}
419
+
420
+
421
+
422
+
423
+
424
+	/**
425
+	 * verify_default_pages_exist
426
+	 *
427
+	 * @access public
428
+	 * @static
429
+	 * @return void
430
+	 */
431
+	public static function verify_default_pages_exist()
432
+	{
433
+		$critical_page_problem = false;
434
+		$critical_pages = array(
435
+			array(
436
+				'id'   => 'reg_page_id',
437
+				'name' => __('Registration Checkout', 'event_espresso'),
438
+				'post' => null,
439
+				'code' => 'ESPRESSO_CHECKOUT',
440
+			),
441
+			array(
442
+				'id'   => 'txn_page_id',
443
+				'name' => __('Transactions', 'event_espresso'),
444
+				'post' => null,
445
+				'code' => 'ESPRESSO_TXN_PAGE',
446
+			),
447
+			array(
448
+				'id'   => 'thank_you_page_id',
449
+				'name' => __('Thank You', 'event_espresso'),
450
+				'post' => null,
451
+				'code' => 'ESPRESSO_THANK_YOU',
452
+			),
453
+			array(
454
+				'id'   => 'cancel_page_id',
455
+				'name' => __('Registration Cancelled', 'event_espresso'),
456
+				'post' => null,
457
+				'code' => 'ESPRESSO_CANCELLED',
458
+			),
459
+		);
460
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
461
+		foreach ($critical_pages as $critical_page) {
462
+			// is critical page ID set in config ?
463
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
464
+				// attempt to find post by ID
465
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
466
+			}
467
+			// no dice?
468
+			if ($critical_page['post'] === null) {
469
+				// attempt to find post by title
470
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
471
+				// still nothing?
472
+				if ($critical_page['post'] === null) {
473
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
474
+					// REALLY? Still nothing ??!?!?
475
+					if ($critical_page['post'] === null) {
476
+						$msg = __(
477
+							'The Event Espresso critical page configuration settings could not be updated.',
478
+							'event_espresso'
479
+						);
480
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
481
+						break;
482
+					}
483
+				}
484
+			}
485
+			// check that Post ID matches critical page ID in config
486
+			if (
487
+				isset($critical_page['post']->ID)
488
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
489
+			) {
490
+				//update Config with post ID
491
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
492
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
493
+					$msg = __(
494
+						'The Event Espresso critical page configuration settings could not be updated.',
495
+						'event_espresso'
496
+					);
497
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
498
+				}
499
+			}
500
+			$critical_page_problem =
501
+				! isset($critical_page['post']->post_status)
502
+				|| $critical_page['post']->post_status !== 'publish'
503
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
504
+					? true
505
+					: $critical_page_problem;
506
+		}
507
+		if ($critical_page_problem) {
508
+			$msg = sprintf(
509
+				__(
510
+					'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
511
+					'event_espresso'
512
+				),
513
+				'<a href="'
514
+				. admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
515
+				. '">'
516
+				. __('Event Espresso Critical Pages Settings', 'event_espresso')
517
+				. '</a>'
518
+			);
519
+			EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
520
+		}
521
+		if (EE_Error::has_notices()) {
522
+			EE_Error::get_notices(false, true, true);
523
+		}
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * Returns the first post which uses the specified shortcode
530
+	 *
531
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
532
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
533
+	 *                             "[ESPRESSO_THANK_YOU"
534
+	 *                             (we don't search for the closing shortcode bracket because they might have added
535
+	 *                             parameter to the shortcode
536
+	 * @return WP_Post or NULl
537
+	 */
538
+	public static function get_page_by_ee_shortcode($ee_shortcode)
539
+	{
540
+		global $wpdb;
541
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
542
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
543
+		if ($post_id) {
544
+			return get_post($post_id);
545
+		} else {
546
+			return null;
547
+		}
548
+	}
549
+
550
+
551
+	/**
552
+	 *    This function generates a post for critical espresso pages
553
+	 *
554
+	 * @access public
555
+	 * @static
556
+	 * @param array $critical_page
557
+	 * @return array
558
+	 */
559
+	public static function create_critical_page($critical_page)
560
+	{
561
+
562
+		$post_args = array(
563
+			'post_title'     => $critical_page['name'],
564
+			'post_status'    => 'publish',
565
+			'post_type'      => 'page',
566
+			'comment_status' => 'closed',
567
+			'post_content'   => '[' . $critical_page['code'] . ']',
568
+		);
569
+
570
+		$post_id = wp_insert_post($post_args);
571
+		if (! $post_id) {
572
+			$msg = sprintf(
573
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
574
+				$critical_page['name']
575
+			);
576
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
577
+			return $critical_page;
578
+		}
579
+		// get newly created post's details
580
+		if (! $critical_page['post'] = get_post($post_id)) {
581
+			$msg = sprintf(
582
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
583
+				$critical_page['name']
584
+			);
585
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
586
+		}
587
+
588
+		return $critical_page;
589
+
590
+	}
591
+
592
+
593
+
594
+
595
+	/**
596
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
597
+	 * The role being used to check is filterable.
598
+	 *
599
+	 * @since  4.6.0
600
+	 * @global WPDB $wpdb
601
+	 * @return mixed null|int WP_user ID or NULL
602
+	 */
603
+	public static function get_default_creator_id()
604
+	{
605
+		global $wpdb;
606
+		if ( ! empty(self::$_default_creator_id)) {
607
+			return self::$_default_creator_id;
608
+		}/**/
609
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
610
+		//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.
611
+		$pre_filtered_id = apply_filters(
612
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
613
+			false,
614
+			$role_to_check
615
+		);
616
+		if ($pre_filtered_id !== false) {
617
+			return (int)$pre_filtered_id;
618
+		}
619
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
620
+		$query = $wpdb->prepare(
621
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
622
+			'%' . $role_to_check . '%'
623
+		);
624
+		$user_id = $wpdb->get_var($query);
625
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
626
+		if ($user_id && (int)$user_id) {
627
+			self::$_default_creator_id = (int)$user_id;
628
+			return self::$_default_creator_id;
629
+		} else {
630
+			return null;
631
+		}
632
+	}
633
+
634
+
635
+
636
+	/**
637
+	 * used by EE and EE addons during plugin activation to create tables.
638
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
639
+	 * but includes extra logic regarding activations.
640
+	 *
641
+	 * @access public
642
+	 * @static
643
+	 * @param string  $table_name              without the $wpdb->prefix
644
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
645
+	 *                                         table query)
646
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
647
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
648
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
649
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
650
+	 *                                         you just want to verify the table exists and matches this definition
651
+	 *                                         (and if it HAS data in it you want to leave it be)
652
+	 * @return void
653
+	 * @throws EE_Error if there are database errors
654
+	 */
655
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
656
+	{
657
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
658
+			return;
659
+		}
660
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
661
+		if ( ! function_exists('dbDelta')) {
662
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
663
+		}
664
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
665
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
666
+		// do we need to first delete an existing version of this table ?
667
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
668
+			// ok, delete the table... but ONLY if it's empty
669
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
670
+			// table is NOT empty, are you SURE you want to delete this table ???
671
+			if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
672
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
673
+			} else if ( ! $deleted_safely) {
674
+				// so we should be more cautious rather than just dropping tables so easily
675
+				error_log(
676
+					sprintf(
677
+						__(
678
+							'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
679
+							'event_espresso'
680
+						),
681
+						$wp_table_name,
682
+						'<br/>',
683
+						'espresso_db_update'
684
+					)
685
+				);
686
+			}
687
+		}
688
+		$engine = str_replace('ENGINE=', '', $engine);
689
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
690
+	}
691
+
692
+
693
+
694
+	/**
695
+	 *    add_column_if_it_doesn't_exist
696
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
697
+	 *
698
+	 * @access     public
699
+	 * @static
700
+	 * @deprecated instead use TableManager::addColumn()
701
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
702
+	 * @param string $column_name
703
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
704
+	 *                            'VARCHAR(10)'
705
+	 * @return bool|int
706
+	 */
707
+	public static function add_column_if_it_doesnt_exist(
708
+		$table_name,
709
+		$column_name,
710
+		$column_info = 'INT UNSIGNED NOT NULL'
711
+	) {
712
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
713
+	}
714
+
715
+
716
+	/**
717
+	 * get_fields_on_table
718
+	 * Gets all the fields on the database table.
719
+	 *
720
+	 * @access     public
721
+	 * @deprecated instead use TableManager::getTableColumns()
722
+	 * @static
723
+	 * @param string $table_name , without prefixed $wpdb->prefix
724
+	 * @return array of database column names
725
+	 */
726
+	public static function get_fields_on_table($table_name = null)
727
+	{
728
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
729
+	}
730
+
731
+
732
+	/**
733
+	 * db_table_is_empty
734
+	 *
735
+	 * @access     public\
736
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
737
+	 * @static
738
+	 * @param string $table_name
739
+	 * @return bool
740
+	 */
741
+	public static function db_table_is_empty($table_name)
742
+	{
743
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
744
+	}
745
+
746
+
747
+	/**
748
+	 * delete_db_table_if_empty
749
+	 *
750
+	 * @access public
751
+	 * @static
752
+	 * @param string $table_name
753
+	 * @return bool | int
754
+	 */
755
+	public static function delete_db_table_if_empty($table_name)
756
+	{
757
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
758
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
759
+		}
760
+		return false;
761
+	}
762
+
763
+
764
+	/**
765
+	 * delete_unused_db_table
766
+	 *
767
+	 * @access     public
768
+	 * @static
769
+	 * @deprecated instead use TableManager::dropTable()
770
+	 * @param string $table_name
771
+	 * @return bool | int
772
+	 */
773
+	public static function delete_unused_db_table($table_name)
774
+	{
775
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
776
+	}
777
+
778
+
779
+	/**
780
+	 * drop_index
781
+	 *
782
+	 * @access     public
783
+	 * @static
784
+	 * @deprecated instead use TableManager::dropIndex()
785
+	 * @param string $table_name
786
+	 * @param string $index_name
787
+	 * @return bool | int
788
+	 */
789
+	public static function drop_index($table_name, $index_name)
790
+	{
791
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
792
+	}
793
+
794
+
795
+
796
+	/**
797
+	 * create_database_tables
798
+	 *
799
+	 * @access public
800
+	 * @static
801
+	 * @throws EE_Error
802
+	 * @return boolean success (whether database is setup properly or not)
803
+	 */
804
+	public static function create_database_tables()
805
+	{
806
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
807
+		//find the migration script that sets the database to be compatible with the code
808
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
809
+		if ($dms_name) {
810
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
811
+			$current_data_migration_script->set_migrating(false);
812
+			$current_data_migration_script->schema_changes_before_migration();
813
+			$current_data_migration_script->schema_changes_after_migration();
814
+			if ($current_data_migration_script->get_errors()) {
815
+				if (WP_DEBUG) {
816
+					foreach ($current_data_migration_script->get_errors() as $error) {
817
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
818
+					}
819
+				} else {
820
+					EE_Error::add_error(
821
+						__(
822
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
823 823
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
824
-                            'event_espresso'
825
-                        )
826
-                    );
827
-                }
828
-                return false;
829
-            }
830
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
831
-        } else {
832
-            EE_Error::add_error(
833
-                __(
834
-                    'Could not determine most up-to-date data migration script from which to pull database schema
824
+							'event_espresso'
825
+						)
826
+					);
827
+				}
828
+				return false;
829
+			}
830
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
831
+		} else {
832
+			EE_Error::add_error(
833
+				__(
834
+					'Could not determine most up-to-date data migration script from which to pull database schema
835 835
                      structure. So database is probably not setup properly',
836
-                    'event_espresso'
837
-                ),
838
-                __FILE__,
839
-                __FUNCTION__,
840
-                __LINE__
841
-            );
842
-            return false;
843
-        }
844
-        return true;
845
-    }
846
-
847
-
848
-
849
-    /**
850
-     * initialize_system_questions
851
-     *
852
-     * @access public
853
-     * @static
854
-     * @return void
855
-     */
856
-    public static function initialize_system_questions()
857
-    {
858
-        // QUESTION GROUPS
859
-        global $wpdb;
860
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
861
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
862
-        // what we have
863
-        $question_groups = $wpdb->get_col($SQL);
864
-        // check the response
865
-        $question_groups = is_array($question_groups) ? $question_groups : array();
866
-        // what we should have
867
-        $QSG_systems = array(1, 2);
868
-        // loop thru what we should have and compare to what we have
869
-        foreach ($QSG_systems as $QSG_system) {
870
-            // reset values array
871
-            $QSG_values = array();
872
-            // 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)
873
-            if (! in_array("$QSG_system", $question_groups)) {
874
-                // add it
875
-                switch ($QSG_system) {
876
-                    case 1:
877
-                        $QSG_values = array(
878
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
879
-                            'QSG_identifier'      => 'personal-information-' . time(),
880
-                            'QSG_desc'            => '',
881
-                            'QSG_order'           => 1,
882
-                            'QSG_show_group_name' => 1,
883
-                            'QSG_show_group_desc' => 1,
884
-                            'QSG_system'          => EEM_Question_Group::system_personal,
885
-                            'QSG_deleted'         => 0,
886
-                        );
887
-                        break;
888
-                    case 2:
889
-                        $QSG_values = array(
890
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
891
-                            'QSG_identifier'      => 'address-information-' . time(),
892
-                            'QSG_desc'            => '',
893
-                            'QSG_order'           => 2,
894
-                            'QSG_show_group_name' => 1,
895
-                            'QSG_show_group_desc' => 1,
896
-                            'QSG_system'          => EEM_Question_Group::system_address,
897
-                            'QSG_deleted'         => 0,
898
-                        );
899
-                        break;
900
-                }
901
-                // make sure we have some values before inserting them
902
-                if (! empty($QSG_values)) {
903
-                    // insert system question
904
-                    $wpdb->insert(
905
-                        $table_name,
906
-                        $QSG_values,
907
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
908
-                    );
909
-                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
910
-                }
911
-            }
912
-        }
913
-        // QUESTIONS
914
-        global $wpdb;
915
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
916
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
917
-        // what we have
918
-        $questions = $wpdb->get_col($SQL);
919
-        // what we should have
920
-        $QST_systems = array(
921
-            'fname',
922
-            'lname',
923
-            'email',
924
-            'address',
925
-            'address2',
926
-            'city',
927
-            'country',
928
-            'state',
929
-            'zip',
930
-            'phone',
931
-        );
932
-        $order_for_group_1 = 1;
933
-        $order_for_group_2 = 1;
934
-        // loop thru what we should have and compare to what we have
935
-        foreach ($QST_systems as $QST_system) {
936
-            // reset values array
937
-            $QST_values = array();
938
-            // if we don't have what we should have
939
-            if (! in_array($QST_system, $questions)) {
940
-                // add it
941
-                switch ($QST_system) {
942
-                    case 'fname':
943
-                        $QST_values = array(
944
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
945
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
946
-                            'QST_system'        => 'fname',
947
-                            'QST_type'          => 'TEXT',
948
-                            'QST_required'      => 1,
949
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
950
-                            'QST_order'         => 1,
951
-                            'QST_admin_only'    => 0,
952
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
953
-                            'QST_wp_user'       => self::get_default_creator_id(),
954
-                            'QST_deleted'       => 0,
955
-                        );
956
-                        break;
957
-                    case 'lname':
958
-                        $QST_values = array(
959
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
960
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
961
-                            'QST_system'        => 'lname',
962
-                            'QST_type'          => 'TEXT',
963
-                            'QST_required'      => 1,
964
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
965
-                            'QST_order'         => 2,
966
-                            'QST_admin_only'    => 0,
967
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
968
-                            'QST_wp_user'       => self::get_default_creator_id(),
969
-                            'QST_deleted'       => 0,
970
-                        );
971
-                        break;
972
-                    case 'email':
973
-                        $QST_values = array(
974
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
975
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
976
-                            'QST_system'        => 'email',
977
-                            'QST_type'          => 'EMAIL',
978
-                            'QST_required'      => 1,
979
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
980
-                            'QST_order'         => 3,
981
-                            'QST_admin_only'    => 0,
982
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
983
-                            'QST_wp_user'       => self::get_default_creator_id(),
984
-                            'QST_deleted'       => 0,
985
-                        );
986
-                        break;
987
-                    case 'address':
988
-                        $QST_values = array(
989
-                            'QST_display_text'  => __('Address', 'event_espresso'),
990
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
991
-                            'QST_system'        => 'address',
992
-                            'QST_type'          => 'TEXT',
993
-                            'QST_required'      => 0,
994
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
995
-                            'QST_order'         => 4,
996
-                            'QST_admin_only'    => 0,
997
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
998
-                            'QST_wp_user'       => self::get_default_creator_id(),
999
-                            'QST_deleted'       => 0,
1000
-                        );
1001
-                        break;
1002
-                    case 'address2':
1003
-                        $QST_values = array(
1004
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
1005
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1006
-                            'QST_system'        => 'address2',
1007
-                            'QST_type'          => 'TEXT',
1008
-                            'QST_required'      => 0,
1009
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1010
-                            'QST_order'         => 5,
1011
-                            'QST_admin_only'    => 0,
1012
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1013
-                            'QST_wp_user'       => self::get_default_creator_id(),
1014
-                            'QST_deleted'       => 0,
1015
-                        );
1016
-                        break;
1017
-                    case 'city':
1018
-                        $QST_values = array(
1019
-                            'QST_display_text'  => __('City', 'event_espresso'),
1020
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1021
-                            'QST_system'        => 'city',
1022
-                            'QST_type'          => 'TEXT',
1023
-                            'QST_required'      => 0,
1024
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1025
-                            'QST_order'         => 6,
1026
-                            'QST_admin_only'    => 0,
1027
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1028
-                            'QST_wp_user'       => self::get_default_creator_id(),
1029
-                            'QST_deleted'       => 0,
1030
-                        );
1031
-                        break;
1032
-                    case 'country':
1033
-                        $QST_values = array(
1034
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1035
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1036
-                            'QST_system'        => 'country',
1037
-                            'QST_type'          => 'COUNTRY',
1038
-                            'QST_required'      => 0,
1039
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1040
-                            'QST_order'         => 7,
1041
-                            'QST_admin_only'    => 0,
1042
-                            'QST_wp_user'       => self::get_default_creator_id(),
1043
-                            'QST_deleted'       => 0,
1044
-                        );
1045
-                        break;
1046
-                    case 'state':
1047
-                        $QST_values = array(
1048
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1049
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1050
-                            'QST_system'        => 'state',
1051
-                            'QST_type'          => 'STATE',
1052
-                            'QST_required'      => 0,
1053
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1054
-                            'QST_order'         => 8,
1055
-                            'QST_admin_only'    => 0,
1056
-                            'QST_wp_user'       => self::get_default_creator_id(),
1057
-                            'QST_deleted'       => 0,
1058
-                        );
1059
-                        break;
1060
-                    case 'zip':
1061
-                        $QST_values = array(
1062
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1063
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1064
-                            'QST_system'        => 'zip',
1065
-                            'QST_type'          => 'TEXT',
1066
-                            'QST_required'      => 0,
1067
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1068
-                            'QST_order'         => 9,
1069
-                            'QST_admin_only'    => 0,
1070
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1071
-                            'QST_wp_user'       => self::get_default_creator_id(),
1072
-                            'QST_deleted'       => 0,
1073
-                        );
1074
-                        break;
1075
-                    case 'phone':
1076
-                        $QST_values = array(
1077
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1078
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1079
-                            'QST_system'        => 'phone',
1080
-                            'QST_type'          => 'TEXT',
1081
-                            'QST_required'      => 0,
1082
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1083
-                            'QST_order'         => 10,
1084
-                            'QST_admin_only'    => 0,
1085
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1086
-                            'QST_wp_user'       => self::get_default_creator_id(),
1087
-                            'QST_deleted'       => 0,
1088
-                        );
1089
-                        break;
1090
-                }
1091
-                if (! empty($QST_values)) {
1092
-                    // insert system question
1093
-                    $wpdb->insert(
1094
-                        $table_name,
1095
-                        $QST_values,
1096
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1097
-                    );
1098
-                    $QST_ID = $wpdb->insert_id;
1099
-                    // QUESTION GROUP QUESTIONS
1100
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1101
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1102
-                    } else {
1103
-                        $system_question_we_want = EEM_Question_Group::system_address;
1104
-                    }
1105
-                    if (isset($QSG_IDs[$system_question_we_want])) {
1106
-                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1107
-                    } else {
1108
-                        $id_col = EEM_Question_Group::instance()
1109
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1110
-                        if (is_array($id_col)) {
1111
-                            $QSG_ID = reset($id_col);
1112
-                        } else {
1113
-                            //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
1114
-                            EE_Log::instance()->log(
1115
-                                __FILE__,
1116
-                                __FUNCTION__,
1117
-                                sprintf(
1118
-                                    __(
1119
-                                        'Could not associate question %1$s to a question group because no system question
836
+					'event_espresso'
837
+				),
838
+				__FILE__,
839
+				__FUNCTION__,
840
+				__LINE__
841
+			);
842
+			return false;
843
+		}
844
+		return true;
845
+	}
846
+
847
+
848
+
849
+	/**
850
+	 * initialize_system_questions
851
+	 *
852
+	 * @access public
853
+	 * @static
854
+	 * @return void
855
+	 */
856
+	public static function initialize_system_questions()
857
+	{
858
+		// QUESTION GROUPS
859
+		global $wpdb;
860
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
861
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
862
+		// what we have
863
+		$question_groups = $wpdb->get_col($SQL);
864
+		// check the response
865
+		$question_groups = is_array($question_groups) ? $question_groups : array();
866
+		// what we should have
867
+		$QSG_systems = array(1, 2);
868
+		// loop thru what we should have and compare to what we have
869
+		foreach ($QSG_systems as $QSG_system) {
870
+			// reset values array
871
+			$QSG_values = array();
872
+			// 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)
873
+			if (! in_array("$QSG_system", $question_groups)) {
874
+				// add it
875
+				switch ($QSG_system) {
876
+					case 1:
877
+						$QSG_values = array(
878
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
879
+							'QSG_identifier'      => 'personal-information-' . time(),
880
+							'QSG_desc'            => '',
881
+							'QSG_order'           => 1,
882
+							'QSG_show_group_name' => 1,
883
+							'QSG_show_group_desc' => 1,
884
+							'QSG_system'          => EEM_Question_Group::system_personal,
885
+							'QSG_deleted'         => 0,
886
+						);
887
+						break;
888
+					case 2:
889
+						$QSG_values = array(
890
+							'QSG_name'            => __('Address Information', 'event_espresso'),
891
+							'QSG_identifier'      => 'address-information-' . time(),
892
+							'QSG_desc'            => '',
893
+							'QSG_order'           => 2,
894
+							'QSG_show_group_name' => 1,
895
+							'QSG_show_group_desc' => 1,
896
+							'QSG_system'          => EEM_Question_Group::system_address,
897
+							'QSG_deleted'         => 0,
898
+						);
899
+						break;
900
+				}
901
+				// make sure we have some values before inserting them
902
+				if (! empty($QSG_values)) {
903
+					// insert system question
904
+					$wpdb->insert(
905
+						$table_name,
906
+						$QSG_values,
907
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
908
+					);
909
+					$QSG_IDs[$QSG_system] = $wpdb->insert_id;
910
+				}
911
+			}
912
+		}
913
+		// QUESTIONS
914
+		global $wpdb;
915
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
916
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
917
+		// what we have
918
+		$questions = $wpdb->get_col($SQL);
919
+		// what we should have
920
+		$QST_systems = array(
921
+			'fname',
922
+			'lname',
923
+			'email',
924
+			'address',
925
+			'address2',
926
+			'city',
927
+			'country',
928
+			'state',
929
+			'zip',
930
+			'phone',
931
+		);
932
+		$order_for_group_1 = 1;
933
+		$order_for_group_2 = 1;
934
+		// loop thru what we should have and compare to what we have
935
+		foreach ($QST_systems as $QST_system) {
936
+			// reset values array
937
+			$QST_values = array();
938
+			// if we don't have what we should have
939
+			if (! in_array($QST_system, $questions)) {
940
+				// add it
941
+				switch ($QST_system) {
942
+					case 'fname':
943
+						$QST_values = array(
944
+							'QST_display_text'  => __('First Name', 'event_espresso'),
945
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
946
+							'QST_system'        => 'fname',
947
+							'QST_type'          => 'TEXT',
948
+							'QST_required'      => 1,
949
+							'QST_required_text' => __('This field is required', 'event_espresso'),
950
+							'QST_order'         => 1,
951
+							'QST_admin_only'    => 0,
952
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
953
+							'QST_wp_user'       => self::get_default_creator_id(),
954
+							'QST_deleted'       => 0,
955
+						);
956
+						break;
957
+					case 'lname':
958
+						$QST_values = array(
959
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
960
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
961
+							'QST_system'        => 'lname',
962
+							'QST_type'          => 'TEXT',
963
+							'QST_required'      => 1,
964
+							'QST_required_text' => __('This field is required', 'event_espresso'),
965
+							'QST_order'         => 2,
966
+							'QST_admin_only'    => 0,
967
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
968
+							'QST_wp_user'       => self::get_default_creator_id(),
969
+							'QST_deleted'       => 0,
970
+						);
971
+						break;
972
+					case 'email':
973
+						$QST_values = array(
974
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
975
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
976
+							'QST_system'        => 'email',
977
+							'QST_type'          => 'EMAIL',
978
+							'QST_required'      => 1,
979
+							'QST_required_text' => __('This field is required', 'event_espresso'),
980
+							'QST_order'         => 3,
981
+							'QST_admin_only'    => 0,
982
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
983
+							'QST_wp_user'       => self::get_default_creator_id(),
984
+							'QST_deleted'       => 0,
985
+						);
986
+						break;
987
+					case 'address':
988
+						$QST_values = array(
989
+							'QST_display_text'  => __('Address', 'event_espresso'),
990
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
991
+							'QST_system'        => 'address',
992
+							'QST_type'          => 'TEXT',
993
+							'QST_required'      => 0,
994
+							'QST_required_text' => __('This field is required', 'event_espresso'),
995
+							'QST_order'         => 4,
996
+							'QST_admin_only'    => 0,
997
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
998
+							'QST_wp_user'       => self::get_default_creator_id(),
999
+							'QST_deleted'       => 0,
1000
+						);
1001
+						break;
1002
+					case 'address2':
1003
+						$QST_values = array(
1004
+							'QST_display_text'  => __('Address2', 'event_espresso'),
1005
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1006
+							'QST_system'        => 'address2',
1007
+							'QST_type'          => 'TEXT',
1008
+							'QST_required'      => 0,
1009
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1010
+							'QST_order'         => 5,
1011
+							'QST_admin_only'    => 0,
1012
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1013
+							'QST_wp_user'       => self::get_default_creator_id(),
1014
+							'QST_deleted'       => 0,
1015
+						);
1016
+						break;
1017
+					case 'city':
1018
+						$QST_values = array(
1019
+							'QST_display_text'  => __('City', 'event_espresso'),
1020
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1021
+							'QST_system'        => 'city',
1022
+							'QST_type'          => 'TEXT',
1023
+							'QST_required'      => 0,
1024
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1025
+							'QST_order'         => 6,
1026
+							'QST_admin_only'    => 0,
1027
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1028
+							'QST_wp_user'       => self::get_default_creator_id(),
1029
+							'QST_deleted'       => 0,
1030
+						);
1031
+						break;
1032
+					case 'country':
1033
+						$QST_values = array(
1034
+							'QST_display_text'  => __('Country', 'event_espresso'),
1035
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1036
+							'QST_system'        => 'country',
1037
+							'QST_type'          => 'COUNTRY',
1038
+							'QST_required'      => 0,
1039
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1040
+							'QST_order'         => 7,
1041
+							'QST_admin_only'    => 0,
1042
+							'QST_wp_user'       => self::get_default_creator_id(),
1043
+							'QST_deleted'       => 0,
1044
+						);
1045
+						break;
1046
+					case 'state':
1047
+						$QST_values = array(
1048
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1049
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1050
+							'QST_system'        => 'state',
1051
+							'QST_type'          => 'STATE',
1052
+							'QST_required'      => 0,
1053
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1054
+							'QST_order'         => 8,
1055
+							'QST_admin_only'    => 0,
1056
+							'QST_wp_user'       => self::get_default_creator_id(),
1057
+							'QST_deleted'       => 0,
1058
+						);
1059
+						break;
1060
+					case 'zip':
1061
+						$QST_values = array(
1062
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1063
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1064
+							'QST_system'        => 'zip',
1065
+							'QST_type'          => 'TEXT',
1066
+							'QST_required'      => 0,
1067
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1068
+							'QST_order'         => 9,
1069
+							'QST_admin_only'    => 0,
1070
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1071
+							'QST_wp_user'       => self::get_default_creator_id(),
1072
+							'QST_deleted'       => 0,
1073
+						);
1074
+						break;
1075
+					case 'phone':
1076
+						$QST_values = array(
1077
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1078
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1079
+							'QST_system'        => 'phone',
1080
+							'QST_type'          => 'TEXT',
1081
+							'QST_required'      => 0,
1082
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1083
+							'QST_order'         => 10,
1084
+							'QST_admin_only'    => 0,
1085
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1086
+							'QST_wp_user'       => self::get_default_creator_id(),
1087
+							'QST_deleted'       => 0,
1088
+						);
1089
+						break;
1090
+				}
1091
+				if (! empty($QST_values)) {
1092
+					// insert system question
1093
+					$wpdb->insert(
1094
+						$table_name,
1095
+						$QST_values,
1096
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1097
+					);
1098
+					$QST_ID = $wpdb->insert_id;
1099
+					// QUESTION GROUP QUESTIONS
1100
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1101
+						$system_question_we_want = EEM_Question_Group::system_personal;
1102
+					} else {
1103
+						$system_question_we_want = EEM_Question_Group::system_address;
1104
+					}
1105
+					if (isset($QSG_IDs[$system_question_we_want])) {
1106
+						$QSG_ID = $QSG_IDs[$system_question_we_want];
1107
+					} else {
1108
+						$id_col = EEM_Question_Group::instance()
1109
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1110
+						if (is_array($id_col)) {
1111
+							$QSG_ID = reset($id_col);
1112
+						} else {
1113
+							//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
1114
+							EE_Log::instance()->log(
1115
+								__FILE__,
1116
+								__FUNCTION__,
1117
+								sprintf(
1118
+									__(
1119
+										'Could not associate question %1$s to a question group because no system question
1120 1120
                                          group existed',
1121
-                                        'event_espresso'
1122
-                                    ),
1123
-                                    $QST_ID),
1124
-                                'error');
1125
-                            continue;
1126
-                        }
1127
-                    }
1128
-                    // add system questions to groups
1129
-                    $wpdb->insert(
1130
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1131
-                        array(
1132
-                            'QSG_ID'    => $QSG_ID,
1133
-                            'QST_ID'    => $QST_ID,
1134
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1135
-                        ),
1136
-                        array('%d', '%d', '%d')
1137
-                    );
1138
-                }
1139
-            }
1140
-        }
1141
-    }
1142
-
1143
-
1144
-    /**
1145
-     * Makes sure the default payment method (Invoice) is active.
1146
-     * This used to be done automatically as part of constructing the old gateways config
1147
-     *
1148
-     * @throws \EE_Error
1149
-     */
1150
-    public static function insert_default_payment_methods()
1151
-    {
1152
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1153
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1154
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1155
-        } else {
1156
-            EEM_Payment_Method::instance()->verify_button_urls();
1157
-        }
1158
-    }
1159
-
1160
-    /**
1161
-     * insert_default_status_codes
1162
-     *
1163
-     * @access public
1164
-     * @static
1165
-     * @return void
1166
-     */
1167
-    public static function insert_default_status_codes()
1168
-    {
1169
-
1170
-        global $wpdb;
1171
-
1172
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1173
-
1174
-            $table_name = EEM_Status::instance()->table();
1175
-
1176
-            $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', 'MDO', 'MEX' );";
1177
-            $wpdb->query($SQL);
1178
-
1179
-            $SQL = "INSERT INTO $table_name
1121
+										'event_espresso'
1122
+									),
1123
+									$QST_ID),
1124
+								'error');
1125
+							continue;
1126
+						}
1127
+					}
1128
+					// add system questions to groups
1129
+					$wpdb->insert(
1130
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1131
+						array(
1132
+							'QSG_ID'    => $QSG_ID,
1133
+							'QST_ID'    => $QST_ID,
1134
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1135
+						),
1136
+						array('%d', '%d', '%d')
1137
+					);
1138
+				}
1139
+			}
1140
+		}
1141
+	}
1142
+
1143
+
1144
+	/**
1145
+	 * Makes sure the default payment method (Invoice) is active.
1146
+	 * This used to be done automatically as part of constructing the old gateways config
1147
+	 *
1148
+	 * @throws \EE_Error
1149
+	 */
1150
+	public static function insert_default_payment_methods()
1151
+	{
1152
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1153
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1154
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1155
+		} else {
1156
+			EEM_Payment_Method::instance()->verify_button_urls();
1157
+		}
1158
+	}
1159
+
1160
+	/**
1161
+	 * insert_default_status_codes
1162
+	 *
1163
+	 * @access public
1164
+	 * @static
1165
+	 * @return void
1166
+	 */
1167
+	public static function insert_default_status_codes()
1168
+	{
1169
+
1170
+		global $wpdb;
1171
+
1172
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1173
+
1174
+			$table_name = EEM_Status::instance()->table();
1175
+
1176
+			$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', 'MDO', 'MEX' );";
1177
+			$wpdb->query($SQL);
1178
+
1179
+			$SQL = "INSERT INTO $table_name
1180 1180
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1181 1181
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1182 1182
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1216,521 +1216,521 @@  discard block
 block discarded – undo
1216 1216
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1217 1217
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1218 1218
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1219
-            $wpdb->query($SQL);
1220
-
1221
-        }
1222
-
1223
-    }
1224
-
1225
-
1226
-    /**
1227
-     * create_upload_directories
1228
-     * Creates folders in the uploads directory to facilitate addons and templates
1229
-     *
1230
-     * @access public
1231
-     * @static
1232
-     * @return boolean success of verifying upload directories exist
1233
-     */
1234
-    public static function create_upload_directories()
1235
-    {
1236
-        // Create the required folders
1237
-        $folders = array(
1238
-            EVENT_ESPRESSO_TEMPLATE_DIR,
1239
-            EVENT_ESPRESSO_GATEWAY_DIR,
1240
-            EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1241
-            EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1242
-            EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1243
-        );
1244
-        foreach ($folders as $folder) {
1245
-            try {
1246
-                EEH_File::ensure_folder_exists_and_is_writable($folder);
1247
-                @ chmod($folder, 0755);
1248
-            } catch (EE_Error $e) {
1249
-                EE_Error::add_error(
1250
-                    sprintf(
1251
-                        __('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1252
-                        $folder,
1253
-                        '<br />' . $e->getMessage()
1254
-                    ),
1255
-                    __FILE__, __FUNCTION__, __LINE__
1256
-                );
1257
-                //indicate we'll need to fix this later
1258
-                update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1259
-                return false;
1260
-            }
1261
-        }
1262
-        //just add the .htaccess file to the logs directory to begin with. Even if logging
1263
-        //is disabled, there might be activation errors recorded in there
1264
-        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1265
-        //remember EE's folders are all good
1266
-        delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1267
-        return true;
1268
-    }
1269
-
1270
-    /**
1271
-     * Whether the upload directories need to be fixed or not.
1272
-     * If EE is installed but filesystem access isn't initially available,
1273
-     * we need to get the user's filesystem credentials and THEN create them,
1274
-     * so there might be period of time when EE is installed but its
1275
-     * upload directories aren't available. This indicates such a state
1276
-     *
1277
-     * @return boolean
1278
-     */
1279
-    public static function upload_directories_incomplete()
1280
-    {
1281
-        return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * generate_default_message_templates
1287
-     *
1288
-     * @static
1289
-     * @throws EE_Error
1290
-     * @return bool     true means new templates were created.
1291
-     *                  false means no templates were created.
1292
-     *                  This is NOT an error flag. To check for errors you will want
1293
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1294
-     */
1295
-    public static function generate_default_message_templates()
1296
-    {
1297
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1298
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1299
-        /*
1219
+			$wpdb->query($SQL);
1220
+
1221
+		}
1222
+
1223
+	}
1224
+
1225
+
1226
+	/**
1227
+	 * create_upload_directories
1228
+	 * Creates folders in the uploads directory to facilitate addons and templates
1229
+	 *
1230
+	 * @access public
1231
+	 * @static
1232
+	 * @return boolean success of verifying upload directories exist
1233
+	 */
1234
+	public static function create_upload_directories()
1235
+	{
1236
+		// Create the required folders
1237
+		$folders = array(
1238
+			EVENT_ESPRESSO_TEMPLATE_DIR,
1239
+			EVENT_ESPRESSO_GATEWAY_DIR,
1240
+			EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1241
+			EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1242
+			EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1243
+		);
1244
+		foreach ($folders as $folder) {
1245
+			try {
1246
+				EEH_File::ensure_folder_exists_and_is_writable($folder);
1247
+				@ chmod($folder, 0755);
1248
+			} catch (EE_Error $e) {
1249
+				EE_Error::add_error(
1250
+					sprintf(
1251
+						__('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1252
+						$folder,
1253
+						'<br />' . $e->getMessage()
1254
+					),
1255
+					__FILE__, __FUNCTION__, __LINE__
1256
+				);
1257
+				//indicate we'll need to fix this later
1258
+				update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1259
+				return false;
1260
+			}
1261
+		}
1262
+		//just add the .htaccess file to the logs directory to begin with. Even if logging
1263
+		//is disabled, there might be activation errors recorded in there
1264
+		EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1265
+		//remember EE's folders are all good
1266
+		delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1267
+		return true;
1268
+	}
1269
+
1270
+	/**
1271
+	 * Whether the upload directories need to be fixed or not.
1272
+	 * If EE is installed but filesystem access isn't initially available,
1273
+	 * we need to get the user's filesystem credentials and THEN create them,
1274
+	 * so there might be period of time when EE is installed but its
1275
+	 * upload directories aren't available. This indicates such a state
1276
+	 *
1277
+	 * @return boolean
1278
+	 */
1279
+	public static function upload_directories_incomplete()
1280
+	{
1281
+		return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * generate_default_message_templates
1287
+	 *
1288
+	 * @static
1289
+	 * @throws EE_Error
1290
+	 * @return bool     true means new templates were created.
1291
+	 *                  false means no templates were created.
1292
+	 *                  This is NOT an error flag. To check for errors you will want
1293
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1294
+	 */
1295
+	public static function generate_default_message_templates()
1296
+	{
1297
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1298
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1299
+		/*
1300 1300
          * This first method is taking care of ensuring any default messengers
1301 1301
          * that should be made active and have templates generated are done.
1302 1302
          */
1303
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1304
-            $message_resource_manager
1305
-        );
1306
-        /**
1307
-         * This method is verifying there are no NEW default message types
1308
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1309
-         */
1310
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1311
-            $message_resource_manager
1312
-        );
1313
-        //after all is done, let's persist these changes to the db.
1314
-        $message_resource_manager->update_has_activated_messengers_option();
1315
-        $message_resource_manager->update_active_messengers_option();
1316
-        // will return true if either of these are true.  Otherwise will return false.
1317
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1318
-    }
1319
-
1320
-
1321
-
1322
-    /**
1323
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1324
-     * @return array|bool
1325
-     * @throws \EE_Error
1326
-     */
1327
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1328
-        EE_Message_Resource_Manager $message_resource_manager
1329
-    ) {
1330
-        /** @type EE_messenger[] $active_messengers */
1331
-        $active_messengers = $message_resource_manager->active_messengers();
1332
-        $installed_message_types = $message_resource_manager->installed_message_types();
1333
-        $templates_created = false;
1334
-        foreach ($active_messengers as $active_messenger) {
1335
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1336
-            $default_message_type_names_to_activate = array();
1337
-            // looping through each default message type reported by the messenger
1338
-            // and setup the actual message types to activate.
1339
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1340
-                // if already active or has already been activated before we skip
1341
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1342
-                // we also skip if the message type is not installed.
1343
-                if (
1344
-                    $message_resource_manager->has_message_type_been_activated_for_messenger(
1345
-                        $default_message_type_name_for_messenger,
1346
-                        $active_messenger->name
1347
-                    )
1348
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1349
-                        $active_messenger->name,
1350
-                        $default_message_type_name_for_messenger
1351
-                    )
1352
-                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1353
-                ) {
1354
-                    continue;
1355
-                }
1356
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1357
-            }
1358
-            //let's activate!
1359
-            $message_resource_manager->ensure_message_types_are_active(
1360
-                $default_message_type_names_to_activate,
1361
-                $active_messenger->name,
1362
-                false
1363
-            );
1364
-            //activate the templates for these message types
1365
-            if ( ! empty($default_message_type_names_to_activate)) {
1366
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1367
-                    $active_messenger->name,
1368
-                    $default_message_type_names_for_messenger,
1369
-                    '',
1370
-                    true
1371
-                );
1372
-            }
1373
-        }
1374
-        return $templates_created;
1375
-    }
1376
-
1377
-
1378
-
1379
-    /**
1380
-     * This will activate and generate default messengers and default message types for those messengers.
1381
-     *
1382
-     * @param EE_message_Resource_Manager $message_resource_manager
1383
-     * @return array|bool  True means there were default messengers and message type templates generated.
1384
-     *                     False means that there were no templates generated
1385
-     *                     (which could simply mean there are no default message types for a messenger).
1386
-     * @throws EE_Error
1387
-     */
1388
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1389
-        EE_Message_Resource_Manager $message_resource_manager
1390
-    ) {
1391
-        /** @type EE_messenger[] $messengers_to_generate */
1392
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1393
-        $installed_message_types = $message_resource_manager->installed_message_types();
1394
-        $templates_generated = false;
1395
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1396
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1397
-            //verify the default message types match an installed message type.
1398
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1399
-                if (
1400
-                    ! isset($installed_message_types[$name])
1401
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1402
-                        $name,
1403
-                        $messenger_to_generate->name
1404
-                    )
1405
-                ) {
1406
-                    unset($default_message_type_names_for_messenger[$key]);
1407
-                }
1408
-            }
1409
-            // in previous iterations, the active_messengers option in the db
1410
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1411
-            // This comment is left here just in case we discover that we _do_ need to update before
1412
-            // passing off to create templates (after the refactor is done).
1413
-            // @todo remove this comment when determined not necessary.
1414
-            $message_resource_manager->activate_messenger(
1415
-                $messenger_to_generate->name,
1416
-                $default_message_type_names_for_messenger,
1417
-                false
1418
-            );
1419
-            //create any templates needing created (or will reactivate templates already generated as necessary).
1420
-            if ( ! empty($default_message_type_names_for_messenger)) {
1421
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1422
-                    $messenger_to_generate->name,
1423
-                    $default_message_type_names_for_messenger,
1424
-                    '',
1425
-                    true
1426
-                );
1427
-            }
1428
-        }
1429
-        return $templates_generated;
1430
-    }
1431
-
1432
-
1433
-    /**
1434
-     * This returns the default messengers to generate templates for on activation of EE.
1435
-     * It considers:
1436
-     * - whether a messenger is already active in the db.
1437
-     * - whether a messenger has been made active at any time in the past.
1438
-     *
1439
-     * @static
1440
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1441
-     * @return EE_messenger[]
1442
-     */
1443
-    protected static function _get_default_messengers_to_generate_on_activation(
1444
-        EE_Message_Resource_Manager $message_resource_manager
1445
-    ) {
1446
-        $active_messengers    = $message_resource_manager->active_messengers();
1447
-        $installed_messengers = $message_resource_manager->installed_messengers();
1448
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1449
-
1450
-        $messengers_to_generate = array();
1451
-        foreach ($installed_messengers as $installed_messenger) {
1452
-            //if installed messenger is a messenger that should be activated on install
1453
-            //and is not already active
1454
-            //and has never been activated
1455
-            if (
1456
-                ! $installed_messenger->activate_on_install
1457
-                || isset($active_messengers[$installed_messenger->name])
1458
-                || isset($has_activated[$installed_messenger->name])
1459
-            ) {
1460
-                continue;
1461
-            }
1462
-            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1463
-        }
1464
-        return $messengers_to_generate;
1465
-    }
1466
-
1467
-
1468
-    /**
1469
-     * This simply validates active message types to ensure they actually match installed
1470
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1471
-     * rows are set inactive.
1472
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1473
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1474
-     * are still handled in here.
1475
-     *
1476
-     * @since 4.3.1
1477
-     * @return void
1478
-     */
1479
-    public static function validate_messages_system()
1480
-    {
1481
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1482
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1483
-        $message_resource_manager->validate_active_message_types_are_installed();
1484
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * create_no_ticket_prices_array
1490
-     *
1491
-     * @access public
1492
-     * @static
1493
-     * @return void
1494
-     */
1495
-    public static function create_no_ticket_prices_array()
1496
-    {
1497
-        // this creates an array for tracking events that have no active ticket prices created
1498
-        // this allows us to warn admins of the situation so that it can be corrected
1499
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1500
-        if (! $espresso_no_ticket_prices) {
1501
-            add_option('ee_no_ticket_prices', array(), '', false);
1502
-        }
1503
-    }
1504
-
1505
-
1506
-    /**
1507
-     * plugin_deactivation
1508
-     *
1509
-     * @access public
1510
-     * @static
1511
-     * @return void
1512
-     */
1513
-    public static function plugin_deactivation()
1514
-    {
1515
-    }
1516
-
1517
-
1518
-    /**
1519
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1520
-     * (like post meta or term relations)
1521
-     *
1522
-     * @global wpdb $wpdb
1523
-     * @throws \EE_Error
1524
-     */
1525
-    public static function delete_all_espresso_cpt_data()
1526
-    {
1527
-        global $wpdb;
1528
-        //get all the CPT post_types
1529
-        $ee_post_types = array();
1530
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1531
-            if (method_exists($model_name, 'instance')) {
1532
-                $model_obj = call_user_func(array($model_name, 'instance'));
1533
-                if ($model_obj instanceof EEM_CPT_Base) {
1534
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1535
-                }
1536
-            }
1537
-        }
1538
-        //get all our CPTs
1539
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1540
-        $cpt_ids = $wpdb->get_col($query);
1541
-        //delete each post meta and term relations too
1542
-        foreach ($cpt_ids as $post_id) {
1543
-            wp_delete_post($post_id, true);
1544
-        }
1545
-    }
1546
-
1547
-    /**
1548
-     * Deletes all EE custom tables
1549
-     *
1550
-     * @return array
1551
-     */
1552
-    public static function drop_espresso_tables()
1553
-    {
1554
-        $tables = array();
1555
-        // load registry
1556
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1557
-            if (method_exists($model_name, 'instance')) {
1558
-                $model_obj = call_user_func(array($model_name, 'instance'));
1559
-                if ($model_obj instanceof EEM_Base) {
1560
-                    foreach ($model_obj->get_tables() as $table) {
1561
-                        if (strpos($table->get_table_name(), 'esp_')
1562
-                            &&
1563
-                            (
1564
-                                is_main_site()//main site? nuke them all
1565
-                                || ! $table->is_global()//not main site,but not global either. nuke it
1566
-                            )
1567
-                        ) {
1568
-                            $tables[$table->get_table_name()] = $table->get_table_name();
1569
-                        }
1570
-                    }
1571
-                }
1572
-            }
1573
-        }
1574
-
1575
-        //there are some tables whose models were removed.
1576
-        //they should be removed when removing all EE core's data
1577
-        $tables_without_models = array(
1578
-            'esp_promotion',
1579
-            'esp_promotion_applied',
1580
-            'esp_promotion_object',
1581
-            'esp_promotion_rule',
1582
-            'esp_rule',
1583
-        );
1584
-        foreach ($tables_without_models as $table) {
1585
-            $tables[$table] = $table;
1586
-        }
1587
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1588
-    }
1589
-
1590
-
1591
-
1592
-    /**
1593
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1594
-     * each table name provided has a wpdb prefix attached, and that it exists.
1595
-     * Returns the list actually deleted
1596
-     *
1597
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1598
-     * @global WPDB $wpdb
1599
-     * @param array $table_names
1600
-     * @return array of table names which we deleted
1601
-     */
1602
-    public static function drop_tables($table_names)
1603
-    {
1604
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1605
-    }
1606
-
1607
-
1608
-
1609
-    /**
1610
-     * plugin_uninstall
1611
-     *
1612
-     * @access public
1613
-     * @static
1614
-     * @param bool $remove_all
1615
-     * @return void
1616
-     */
1617
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1618
-    {
1619
-        global $wpdb;
1620
-        self::drop_espresso_tables();
1621
-        $wp_options_to_delete = array(
1622
-            'ee_no_ticket_prices'                => true,
1623
-            'ee_active_messengers'               => true,
1624
-            'ee_has_activated_messenger'         => true,
1625
-            'ee_flush_rewrite_rules'             => true,
1626
-            'ee_config'                          => false,
1627
-            'ee_data_migration_current_db_state' => true,
1628
-            'ee_data_migration_mapping_'         => false,
1629
-            'ee_data_migration_script_'          => false,
1630
-            'ee_data_migrations'                 => true,
1631
-            'ee_dms_map'                         => false,
1632
-            'ee_notices'                         => true,
1633
-            'lang_file_check_'                   => false,
1634
-            'ee_maintenance_mode'                => true,
1635
-            'ee_ueip_optin'                      => true,
1636
-            'ee_ueip_has_notified'               => true,
1637
-            'ee_plugin_activation_errors'        => true,
1638
-            'ee_id_mapping_from'                 => false,
1639
-            'espresso_persistent_admin_notices'  => true,
1640
-            'ee_encryption_key'                  => true,
1641
-            'pue_force_upgrade_'                 => false,
1642
-            'pue_json_error_'                    => false,
1643
-            'pue_install_key_'                   => false,
1644
-            'pue_verification_error_'            => false,
1645
-            'pu_dismissed_upgrade_'              => false,
1646
-            'external_updates-'                  => false,
1647
-            'ee_extra_data'                      => true,
1648
-            'ee_ssn_'                            => false,
1649
-            'ee_rss_'                            => false,
1650
-            'ee_rte_n_tx_'                       => false,
1651
-            'ee_pers_admin_notices'              => true,
1652
-            'ee_job_parameters_'                 => false,
1653
-            'ee_upload_directories_incomplete'   => true,
1654
-            'ee_verified_db_collations'          => true,
1655
-        );
1656
-        if (is_main_site()) {
1657
-            $wp_options_to_delete['ee_network_config'] = true;
1658
-        }
1659
-        $undeleted_options = array();
1660
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1661
-            if ($no_wildcard) {
1662
-                if ( ! delete_option($option_name)) {
1663
-                    $undeleted_options[] = $option_name;
1664
-                }
1665
-            } else {
1666
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1667
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1668
-                    if ( ! delete_option($option_name_from_wildcard)) {
1669
-                        $undeleted_options[] = $option_name_from_wildcard;
1670
-                    }
1671
-                }
1672
-            }
1673
-        }
1674
-        //also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1675
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1676
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1677
-            $db_update_sans_ee4 = array();
1678
-            foreach ($espresso_db_update as $version => $times_activated) {
1679
-                if ((string)$version[0] === '3') {//if its NON EE4
1680
-                    $db_update_sans_ee4[$version] = $times_activated;
1681
-                }
1682
-            }
1683
-            update_option('espresso_db_update', $db_update_sans_ee4);
1684
-        }
1685
-        $errors = '';
1686
-        if ( ! empty($undeleted_options)) {
1687
-            $errors .= sprintf(
1688
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1689
-                '<br/>',
1690
-                implode(',<br/>', $undeleted_options)
1691
-            );
1692
-        }
1693
-        if ( ! empty($errors)) {
1694
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1695
-        }
1696
-    }
1697
-
1698
-    /**
1699
-     * Gets the mysql error code from the last used query by wpdb
1700
-     *
1701
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1702
-     */
1703
-    public static function last_wpdb_error_code()
1704
-    {
1705
-        global $wpdb;
1706
-        if ($wpdb->use_mysqli) {
1707
-            return mysqli_errno($wpdb->dbh);
1708
-        } else {
1709
-            return mysql_errno($wpdb->dbh);
1710
-        }
1711
-    }
1712
-
1713
-    /**
1714
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1715
-     *
1716
-     * @global wpdb  $wpdb
1717
-     * @deprecated instead use TableAnalysis::tableExists()
1718
-     * @param string $table_name with or without $wpdb->prefix
1719
-     * @return boolean
1720
-     */
1721
-    public static function table_exists($table_name)
1722
-    {
1723
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1724
-    }
1725
-
1726
-    /**
1727
-     * Resets the cache on EEH_Activation
1728
-     */
1729
-    public static function reset()
1730
-    {
1731
-        self::$_default_creator_id                             = null;
1732
-        self::$_initialized_db_content_already_in_this_request = false;
1733
-    }
1303
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1304
+			$message_resource_manager
1305
+		);
1306
+		/**
1307
+		 * This method is verifying there are no NEW default message types
1308
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1309
+		 */
1310
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1311
+			$message_resource_manager
1312
+		);
1313
+		//after all is done, let's persist these changes to the db.
1314
+		$message_resource_manager->update_has_activated_messengers_option();
1315
+		$message_resource_manager->update_active_messengers_option();
1316
+		// will return true if either of these are true.  Otherwise will return false.
1317
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1318
+	}
1319
+
1320
+
1321
+
1322
+	/**
1323
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1324
+	 * @return array|bool
1325
+	 * @throws \EE_Error
1326
+	 */
1327
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1328
+		EE_Message_Resource_Manager $message_resource_manager
1329
+	) {
1330
+		/** @type EE_messenger[] $active_messengers */
1331
+		$active_messengers = $message_resource_manager->active_messengers();
1332
+		$installed_message_types = $message_resource_manager->installed_message_types();
1333
+		$templates_created = false;
1334
+		foreach ($active_messengers as $active_messenger) {
1335
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1336
+			$default_message_type_names_to_activate = array();
1337
+			// looping through each default message type reported by the messenger
1338
+			// and setup the actual message types to activate.
1339
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1340
+				// if already active or has already been activated before we skip
1341
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1342
+				// we also skip if the message type is not installed.
1343
+				if (
1344
+					$message_resource_manager->has_message_type_been_activated_for_messenger(
1345
+						$default_message_type_name_for_messenger,
1346
+						$active_messenger->name
1347
+					)
1348
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1349
+						$active_messenger->name,
1350
+						$default_message_type_name_for_messenger
1351
+					)
1352
+					|| ! isset($installed_message_types[$default_message_type_name_for_messenger])
1353
+				) {
1354
+					continue;
1355
+				}
1356
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1357
+			}
1358
+			//let's activate!
1359
+			$message_resource_manager->ensure_message_types_are_active(
1360
+				$default_message_type_names_to_activate,
1361
+				$active_messenger->name,
1362
+				false
1363
+			);
1364
+			//activate the templates for these message types
1365
+			if ( ! empty($default_message_type_names_to_activate)) {
1366
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1367
+					$active_messenger->name,
1368
+					$default_message_type_names_for_messenger,
1369
+					'',
1370
+					true
1371
+				);
1372
+			}
1373
+		}
1374
+		return $templates_created;
1375
+	}
1376
+
1377
+
1378
+
1379
+	/**
1380
+	 * This will activate and generate default messengers and default message types for those messengers.
1381
+	 *
1382
+	 * @param EE_message_Resource_Manager $message_resource_manager
1383
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1384
+	 *                     False means that there were no templates generated
1385
+	 *                     (which could simply mean there are no default message types for a messenger).
1386
+	 * @throws EE_Error
1387
+	 */
1388
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1389
+		EE_Message_Resource_Manager $message_resource_manager
1390
+	) {
1391
+		/** @type EE_messenger[] $messengers_to_generate */
1392
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1393
+		$installed_message_types = $message_resource_manager->installed_message_types();
1394
+		$templates_generated = false;
1395
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1396
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1397
+			//verify the default message types match an installed message type.
1398
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1399
+				if (
1400
+					! isset($installed_message_types[$name])
1401
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1402
+						$name,
1403
+						$messenger_to_generate->name
1404
+					)
1405
+				) {
1406
+					unset($default_message_type_names_for_messenger[$key]);
1407
+				}
1408
+			}
1409
+			// in previous iterations, the active_messengers option in the db
1410
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1411
+			// This comment is left here just in case we discover that we _do_ need to update before
1412
+			// passing off to create templates (after the refactor is done).
1413
+			// @todo remove this comment when determined not necessary.
1414
+			$message_resource_manager->activate_messenger(
1415
+				$messenger_to_generate->name,
1416
+				$default_message_type_names_for_messenger,
1417
+				false
1418
+			);
1419
+			//create any templates needing created (or will reactivate templates already generated as necessary).
1420
+			if ( ! empty($default_message_type_names_for_messenger)) {
1421
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1422
+					$messenger_to_generate->name,
1423
+					$default_message_type_names_for_messenger,
1424
+					'',
1425
+					true
1426
+				);
1427
+			}
1428
+		}
1429
+		return $templates_generated;
1430
+	}
1431
+
1432
+
1433
+	/**
1434
+	 * This returns the default messengers to generate templates for on activation of EE.
1435
+	 * It considers:
1436
+	 * - whether a messenger is already active in the db.
1437
+	 * - whether a messenger has been made active at any time in the past.
1438
+	 *
1439
+	 * @static
1440
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1441
+	 * @return EE_messenger[]
1442
+	 */
1443
+	protected static function _get_default_messengers_to_generate_on_activation(
1444
+		EE_Message_Resource_Manager $message_resource_manager
1445
+	) {
1446
+		$active_messengers    = $message_resource_manager->active_messengers();
1447
+		$installed_messengers = $message_resource_manager->installed_messengers();
1448
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1449
+
1450
+		$messengers_to_generate = array();
1451
+		foreach ($installed_messengers as $installed_messenger) {
1452
+			//if installed messenger is a messenger that should be activated on install
1453
+			//and is not already active
1454
+			//and has never been activated
1455
+			if (
1456
+				! $installed_messenger->activate_on_install
1457
+				|| isset($active_messengers[$installed_messenger->name])
1458
+				|| isset($has_activated[$installed_messenger->name])
1459
+			) {
1460
+				continue;
1461
+			}
1462
+			$messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1463
+		}
1464
+		return $messengers_to_generate;
1465
+	}
1466
+
1467
+
1468
+	/**
1469
+	 * This simply validates active message types to ensure they actually match installed
1470
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1471
+	 * rows are set inactive.
1472
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1473
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1474
+	 * are still handled in here.
1475
+	 *
1476
+	 * @since 4.3.1
1477
+	 * @return void
1478
+	 */
1479
+	public static function validate_messages_system()
1480
+	{
1481
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1482
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1483
+		$message_resource_manager->validate_active_message_types_are_installed();
1484
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * create_no_ticket_prices_array
1490
+	 *
1491
+	 * @access public
1492
+	 * @static
1493
+	 * @return void
1494
+	 */
1495
+	public static function create_no_ticket_prices_array()
1496
+	{
1497
+		// this creates an array for tracking events that have no active ticket prices created
1498
+		// this allows us to warn admins of the situation so that it can be corrected
1499
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1500
+		if (! $espresso_no_ticket_prices) {
1501
+			add_option('ee_no_ticket_prices', array(), '', false);
1502
+		}
1503
+	}
1504
+
1505
+
1506
+	/**
1507
+	 * plugin_deactivation
1508
+	 *
1509
+	 * @access public
1510
+	 * @static
1511
+	 * @return void
1512
+	 */
1513
+	public static function plugin_deactivation()
1514
+	{
1515
+	}
1516
+
1517
+
1518
+	/**
1519
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1520
+	 * (like post meta or term relations)
1521
+	 *
1522
+	 * @global wpdb $wpdb
1523
+	 * @throws \EE_Error
1524
+	 */
1525
+	public static function delete_all_espresso_cpt_data()
1526
+	{
1527
+		global $wpdb;
1528
+		//get all the CPT post_types
1529
+		$ee_post_types = array();
1530
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1531
+			if (method_exists($model_name, 'instance')) {
1532
+				$model_obj = call_user_func(array($model_name, 'instance'));
1533
+				if ($model_obj instanceof EEM_CPT_Base) {
1534
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1535
+				}
1536
+			}
1537
+		}
1538
+		//get all our CPTs
1539
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1540
+		$cpt_ids = $wpdb->get_col($query);
1541
+		//delete each post meta and term relations too
1542
+		foreach ($cpt_ids as $post_id) {
1543
+			wp_delete_post($post_id, true);
1544
+		}
1545
+	}
1546
+
1547
+	/**
1548
+	 * Deletes all EE custom tables
1549
+	 *
1550
+	 * @return array
1551
+	 */
1552
+	public static function drop_espresso_tables()
1553
+	{
1554
+		$tables = array();
1555
+		// load registry
1556
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1557
+			if (method_exists($model_name, 'instance')) {
1558
+				$model_obj = call_user_func(array($model_name, 'instance'));
1559
+				if ($model_obj instanceof EEM_Base) {
1560
+					foreach ($model_obj->get_tables() as $table) {
1561
+						if (strpos($table->get_table_name(), 'esp_')
1562
+							&&
1563
+							(
1564
+								is_main_site()//main site? nuke them all
1565
+								|| ! $table->is_global()//not main site,but not global either. nuke it
1566
+							)
1567
+						) {
1568
+							$tables[$table->get_table_name()] = $table->get_table_name();
1569
+						}
1570
+					}
1571
+				}
1572
+			}
1573
+		}
1574
+
1575
+		//there are some tables whose models were removed.
1576
+		//they should be removed when removing all EE core's data
1577
+		$tables_without_models = array(
1578
+			'esp_promotion',
1579
+			'esp_promotion_applied',
1580
+			'esp_promotion_object',
1581
+			'esp_promotion_rule',
1582
+			'esp_rule',
1583
+		);
1584
+		foreach ($tables_without_models as $table) {
1585
+			$tables[$table] = $table;
1586
+		}
1587
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1588
+	}
1589
+
1590
+
1591
+
1592
+	/**
1593
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1594
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1595
+	 * Returns the list actually deleted
1596
+	 *
1597
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1598
+	 * @global WPDB $wpdb
1599
+	 * @param array $table_names
1600
+	 * @return array of table names which we deleted
1601
+	 */
1602
+	public static function drop_tables($table_names)
1603
+	{
1604
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1605
+	}
1606
+
1607
+
1608
+
1609
+	/**
1610
+	 * plugin_uninstall
1611
+	 *
1612
+	 * @access public
1613
+	 * @static
1614
+	 * @param bool $remove_all
1615
+	 * @return void
1616
+	 */
1617
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1618
+	{
1619
+		global $wpdb;
1620
+		self::drop_espresso_tables();
1621
+		$wp_options_to_delete = array(
1622
+			'ee_no_ticket_prices'                => true,
1623
+			'ee_active_messengers'               => true,
1624
+			'ee_has_activated_messenger'         => true,
1625
+			'ee_flush_rewrite_rules'             => true,
1626
+			'ee_config'                          => false,
1627
+			'ee_data_migration_current_db_state' => true,
1628
+			'ee_data_migration_mapping_'         => false,
1629
+			'ee_data_migration_script_'          => false,
1630
+			'ee_data_migrations'                 => true,
1631
+			'ee_dms_map'                         => false,
1632
+			'ee_notices'                         => true,
1633
+			'lang_file_check_'                   => false,
1634
+			'ee_maintenance_mode'                => true,
1635
+			'ee_ueip_optin'                      => true,
1636
+			'ee_ueip_has_notified'               => true,
1637
+			'ee_plugin_activation_errors'        => true,
1638
+			'ee_id_mapping_from'                 => false,
1639
+			'espresso_persistent_admin_notices'  => true,
1640
+			'ee_encryption_key'                  => true,
1641
+			'pue_force_upgrade_'                 => false,
1642
+			'pue_json_error_'                    => false,
1643
+			'pue_install_key_'                   => false,
1644
+			'pue_verification_error_'            => false,
1645
+			'pu_dismissed_upgrade_'              => false,
1646
+			'external_updates-'                  => false,
1647
+			'ee_extra_data'                      => true,
1648
+			'ee_ssn_'                            => false,
1649
+			'ee_rss_'                            => false,
1650
+			'ee_rte_n_tx_'                       => false,
1651
+			'ee_pers_admin_notices'              => true,
1652
+			'ee_job_parameters_'                 => false,
1653
+			'ee_upload_directories_incomplete'   => true,
1654
+			'ee_verified_db_collations'          => true,
1655
+		);
1656
+		if (is_main_site()) {
1657
+			$wp_options_to_delete['ee_network_config'] = true;
1658
+		}
1659
+		$undeleted_options = array();
1660
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1661
+			if ($no_wildcard) {
1662
+				if ( ! delete_option($option_name)) {
1663
+					$undeleted_options[] = $option_name;
1664
+				}
1665
+			} else {
1666
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1667
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1668
+					if ( ! delete_option($option_name_from_wildcard)) {
1669
+						$undeleted_options[] = $option_name_from_wildcard;
1670
+					}
1671
+				}
1672
+			}
1673
+		}
1674
+		//also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1675
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1676
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1677
+			$db_update_sans_ee4 = array();
1678
+			foreach ($espresso_db_update as $version => $times_activated) {
1679
+				if ((string)$version[0] === '3') {//if its NON EE4
1680
+					$db_update_sans_ee4[$version] = $times_activated;
1681
+				}
1682
+			}
1683
+			update_option('espresso_db_update', $db_update_sans_ee4);
1684
+		}
1685
+		$errors = '';
1686
+		if ( ! empty($undeleted_options)) {
1687
+			$errors .= sprintf(
1688
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1689
+				'<br/>',
1690
+				implode(',<br/>', $undeleted_options)
1691
+			);
1692
+		}
1693
+		if ( ! empty($errors)) {
1694
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1695
+		}
1696
+	}
1697
+
1698
+	/**
1699
+	 * Gets the mysql error code from the last used query by wpdb
1700
+	 *
1701
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1702
+	 */
1703
+	public static function last_wpdb_error_code()
1704
+	{
1705
+		global $wpdb;
1706
+		if ($wpdb->use_mysqli) {
1707
+			return mysqli_errno($wpdb->dbh);
1708
+		} else {
1709
+			return mysql_errno($wpdb->dbh);
1710
+		}
1711
+	}
1712
+
1713
+	/**
1714
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1715
+	 *
1716
+	 * @global wpdb  $wpdb
1717
+	 * @deprecated instead use TableAnalysis::tableExists()
1718
+	 * @param string $table_name with or without $wpdb->prefix
1719
+	 * @return boolean
1720
+	 */
1721
+	public static function table_exists($table_name)
1722
+	{
1723
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1724
+	}
1725
+
1726
+	/**
1727
+	 * Resets the cache on EEH_Activation
1728
+	 */
1729
+	public static function reset()
1730
+	{
1731
+		self::$_default_creator_id                             = null;
1732
+		self::$_initialized_db_content_already_in_this_request = false;
1733
+	}
1734 1734
 }
1735 1735
 // End of file EEH_Activation.helper.php
1736 1736
 // Location: /helpers/EEH_Activation.core.php
Please login to merge, or discard this patch.
caffeinated/brewing_regular.php 2 patches
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.
Indentation   +269 added lines, -269 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\services\database\TableAnalysis;
5 5
 
6 6
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 /**
10 10
  * the purpose of this file is to simply contain any action/filter hook callbacks etc for specific aspects of EE
@@ -29,277 +29,277 @@  discard block
 block discarded – undo
29 29
 class EE_Brewing_Regular extends EE_BASE implements InterminableInterface
30 30
 {
31 31
 
32
-    /**
33
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
34
-     */
35
-    protected $_table_analysis;
36
-
37
-
38
-
39
-    /**
40
-     * EE_Brewing_Regular constructor.
41
-     */
42
-    public function __construct(TableAnalysis $table_analysis)
43
-    {
44
-        $this->_table_analysis = $table_analysis;
45
-        if (defined('EE_CAFF_PATH')) {
46
-            // activation
47
-            add_action('AHEE__EEH_Activation__initialize_db_content', array($this, 'initialize_caf_db_content'));
48
-            // load caff init
49
-            add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'caffeinated_init'));
50
-            // remove the "powered by" credit link from receipts and invoices
51
-            add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
52
-            // add caffeinated modules
53
-            add_filter(
54
-                'FHEE__EE_Config__register_modules__modules_to_register',
55
-                array($this, 'caffeinated_modules_to_register')
56
-            );
57
-            // load caff scripts
58
-            add_action('wp_enqueue_scripts', array($this, 'enqueue_caffeinated_scripts'), 10);
59
-            add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
60
-            add_filter(
61
-                'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
62
-                array($this, 'caf_payment_methods')
63
-            );
64
-            // caffeinated constructed
65
-            do_action('AHEE__EE_Brewing_Regular__construct__complete');
66
-            //seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
67
-            add_filter('FHEE__ee_show_affiliate_links', '__return_false');
68
-        }
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
75
-     *
76
-     * @param array $paths original helper paths array
77
-     * @return array             new array of paths
78
-     */
79
-    public function caf_helper_paths($paths)
80
-    {
81
-        $paths[] = EE_CAF_CORE . 'helpers' . DS;
82
-        return $paths;
83
-    }
84
-
85
-
86
-
87
-    /**
88
-     * Upon brand-new activation, if this is a new activation of CAF, we want to add
89
-     * some global prices that will show off EE4's capabilities. However, if they're upgrading
90
-     * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
91
-     * This action should only be called when EE 4.x.0.P is initially activated.
92
-     * Right now the only CAF content are these global prices. If there's more in the future, then
93
-     * we should probably create a caf file to contain it all instead just a function like this.
94
-     * Right now, we ASSUME the only price types in the system are default ones
95
-     *
96
-     * @global wpdb $wpdb
97
-     */
98
-    public function initialize_caf_db_content()
99
-    {
100
-        global $wpdb;
101
-        //use same method of getting creator id as the version introducing the change
102
-        $default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
103
-        $price_type_table = $wpdb->prefix . "esp_price_type";
104
-        $price_table = $wpdb->prefix . "esp_price";
105
-        if ($this->_get_table_analysis()->tableExists($price_type_table)) {
106
-            $SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
107
-            $tax_price_type_count = $wpdb->get_var($SQL);
108
-            if ($tax_price_type_count <= 1) {
109
-                $wpdb->insert(
110
-                    $price_type_table,
111
-                    array(
112
-                        'PRT_name'       => __("Regional Tax", "event_espresso"),
113
-                        'PBT_ID'         => 4,
114
-                        'PRT_is_percent' => true,
115
-                        'PRT_order'      => 60,
116
-                        'PRT_deleted'    => false,
117
-                        'PRT_wp_user'    => $default_creator_id,
118
-                    ),
119
-                    array(
120
-                        '%s',//PRT_name
121
-                        '%d',//PBT_id
122
-                        '%d',//PRT_is_percent
123
-                        '%d',//PRT_order
124
-                        '%d',//PRT_deleted
125
-                        '%d', //PRT_wp_user
126
-                    )
127
-                );
128
-                //federal tax
129
-                $result = $wpdb->insert(
130
-                    $price_type_table,
131
-                    array(
132
-                        'PRT_name'       => __("Federal Tax", "event_espresso"),
133
-                        'PBT_ID'         => 4,
134
-                        'PRT_is_percent' => true,
135
-                        'PRT_order'      => 70,
136
-                        'PRT_deleted'    => false,
137
-                        'PRT_wp_user'    => $default_creator_id,
138
-                    ),
139
-                    array(
140
-                        '%s',//PRT_name
141
-                        '%d',//PBT_id
142
-                        '%d',//PRT_is_percent
143
-                        '%d',//PRT_order
144
-                        '%d',//PRT_deleted
145
-                        '%d' //PRT_wp_user
146
-                    )
147
-                );
148
-                if ($result) {
149
-                    $wpdb->insert(
150
-                        $price_table,
151
-                        array(
152
-                            'PRT_ID'         => $wpdb->insert_id,
153
-                            'PRC_amount'     => 15.00,
154
-                            'PRC_name'       => __("Sales Tax", "event_espresso"),
155
-                            'PRC_desc'       => '',
156
-                            'PRC_is_default' => true,
157
-                            'PRC_overrides'  => null,
158
-                            'PRC_deleted'    => false,
159
-                            'PRC_order'      => 50,
160
-                            'PRC_parent'     => null,
161
-                            'PRC_wp_user'    => $default_creator_id,
162
-                        ),
163
-                        array(
164
-                            '%d',//PRT_id
165
-                            '%f',//PRC_amount
166
-                            '%s',//PRC_name
167
-                            '%s',//PRC_desc
168
-                            '%d',//PRC_is_default
169
-                            '%d',//PRC_overrides
170
-                            '%d',//PRC_deleted
171
-                            '%d',//PRC_order
172
-                            '%d',//PRC_parent
173
-                            '%d' //PRC_wp_user
174
-                        )
175
-                    );
176
-                }
177
-            }
178
-        }
179
-    }
180
-
181
-
182
-
183
-    /**
184
-     *    caffeinated_modules_to_register
185
-     *
186
-     * @access public
187
-     * @param array $modules_to_register
188
-     * @return array
189
-     */
190
-    public function caffeinated_modules_to_register($modules_to_register = array())
191
-    {
192
-        if (is_readable(EE_CAFF_PATH . 'modules')) {
193
-            $caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
194
-            if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
195
-                $modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
196
-            }
197
-        }
198
-        return $modules_to_register;
199
-    }
200
-
201
-
202
-
203
-    public function caffeinated_init()
204
-    {
205
-        // EE_Register_CPTs hooks
206
-        add_filter('FHEE__EE_Register_CPTs__get_taxonomies__taxonomies', array($this, 'filter_taxonomies'), 10);
207
-        add_filter('FHEE__EE_Register_CPTs__get_CPTs__cpts', array($this, 'filter_cpts'), 10);
208
-        add_filter('FHEE__EE_Admin__get_extra_nav_menu_pages_items', array($this, 'nav_metabox_items'), 10);
209
-        EE_Registry::instance()->load_file(EE_CAFF_PATH, 'EE_Caf_Messages', 'class', array(), false);
210
-        // caffeinated_init__complete hook
211
-        do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
212
-    }
213
-
214
-
215
-
216
-    public function enqueue_caffeinated_scripts()
217
-    {
218
-        // sound of crickets...
219
-    }
220
-
221
-
222
-
223
-    /**
224
-     * callbacks below here
225
-     *
226
-     * @param array $taxonomy_array
227
-     * @return array
228
-     */
229
-    public function filter_taxonomies(array $taxonomy_array)
230
-    {
231
-        $taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
232
-        return $taxonomy_array;
233
-    }
234
-
235
-
236
-
237
-    /**
238
-     * @param array $cpt_array
239
-     * @return mixed
240
-     */
241
-    public function filter_cpts(array $cpt_array)
242
-    {
243
-        $cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
244
-        return $cpt_array;
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * @param array $menuitems
251
-     * @return array
252
-     */
253
-    public function nav_metabox_items(array $menuitems)
254
-    {
255
-        $menuitems[] = array(
256
-            'title'       => __('Venue List', 'event_espresso'),
257
-            'url'         => get_post_type_archive_link('espresso_venues'),
258
-            'description' => __('Archive page for all venues.', 'event_espresso'),
259
-        );
260
-        return $menuitems;
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     * Adds the payment methods in {event-espresso-core}/caffeinated/payment_methods
267
-     *
268
-     * @param array $payment_method_paths
269
-     * @return array values are folder paths to payment method folders
270
-     */
271
-    public function caf_payment_methods($payment_method_paths)
272
-    {
273
-        $caf_payment_methods_paths = glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
274
-        $payment_method_paths = array_merge($payment_method_paths, $caf_payment_methods_paths);
275
-        return $payment_method_paths;
276
-    }
277
-
278
-
279
-
280
-    /**
281
-     * Gets the injected table analyzer, or throws an exception
282
-     *
283
-     * @return TableAnalysis
284
-     * @throws \EE_Error
285
-     */
286
-    protected function _get_table_analysis()
287
-    {
288
-        if ($this->_table_analysis instanceof TableAnalysis) {
289
-            return $this->_table_analysis;
290
-        } else {
291
-            throw new \EE_Error(
292
-                sprintf(
293
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
294
-                    get_class($this)
295
-                )
296
-            );
297
-        }
298
-    }
32
+	/**
33
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
34
+	 */
35
+	protected $_table_analysis;
36
+
37
+
38
+
39
+	/**
40
+	 * EE_Brewing_Regular constructor.
41
+	 */
42
+	public function __construct(TableAnalysis $table_analysis)
43
+	{
44
+		$this->_table_analysis = $table_analysis;
45
+		if (defined('EE_CAFF_PATH')) {
46
+			// activation
47
+			add_action('AHEE__EEH_Activation__initialize_db_content', array($this, 'initialize_caf_db_content'));
48
+			// load caff init
49
+			add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'caffeinated_init'));
50
+			// remove the "powered by" credit link from receipts and invoices
51
+			add_filter('FHEE_EE_Html_messenger__add_powered_by_credit_link_to_receipt_and_invoice', '__return_false');
52
+			// add caffeinated modules
53
+			add_filter(
54
+				'FHEE__EE_Config__register_modules__modules_to_register',
55
+				array($this, 'caffeinated_modules_to_register')
56
+			);
57
+			// load caff scripts
58
+			add_action('wp_enqueue_scripts', array($this, 'enqueue_caffeinated_scripts'), 10);
59
+			add_filter('FHEE__EE_Registry__load_helper__helper_paths', array($this, 'caf_helper_paths'), 10);
60
+			add_filter(
61
+				'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
62
+				array($this, 'caf_payment_methods')
63
+			);
64
+			// caffeinated constructed
65
+			do_action('AHEE__EE_Brewing_Regular__construct__complete');
66
+			//seeing how this is caf, which isn't put on WordPress.org, we can have affiliate links without a disclaimer
67
+			add_filter('FHEE__ee_show_affiliate_links', '__return_false');
68
+		}
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * callback for the FHEE__EE_Registry__load_helper__helper_paths filter to add the caffeinated paths
75
+	 *
76
+	 * @param array $paths original helper paths array
77
+	 * @return array             new array of paths
78
+	 */
79
+	public function caf_helper_paths($paths)
80
+	{
81
+		$paths[] = EE_CAF_CORE . 'helpers' . DS;
82
+		return $paths;
83
+	}
84
+
85
+
86
+
87
+	/**
88
+	 * Upon brand-new activation, if this is a new activation of CAF, we want to add
89
+	 * some global prices that will show off EE4's capabilities. However, if they're upgrading
90
+	 * from 3.1, or simply EE4.x decaf, we assume they don't want us to suddenly introduce these extra prices.
91
+	 * This action should only be called when EE 4.x.0.P is initially activated.
92
+	 * Right now the only CAF content are these global prices. If there's more in the future, then
93
+	 * we should probably create a caf file to contain it all instead just a function like this.
94
+	 * Right now, we ASSUME the only price types in the system are default ones
95
+	 *
96
+	 * @global wpdb $wpdb
97
+	 */
98
+	public function initialize_caf_db_content()
99
+	{
100
+		global $wpdb;
101
+		//use same method of getting creator id as the version introducing the change
102
+		$default_creator_id = apply_filters('FHEE__EE_DMS_Core_4_5_0__get_default_creator_id', get_current_user_id());
103
+		$price_type_table = $wpdb->prefix . "esp_price_type";
104
+		$price_table = $wpdb->prefix . "esp_price";
105
+		if ($this->_get_table_analysis()->tableExists($price_type_table)) {
106
+			$SQL = 'SELECT COUNT(PRT_ID) FROM ' . $price_type_table . ' WHERE PBT_ID=4';//include trashed price types
107
+			$tax_price_type_count = $wpdb->get_var($SQL);
108
+			if ($tax_price_type_count <= 1) {
109
+				$wpdb->insert(
110
+					$price_type_table,
111
+					array(
112
+						'PRT_name'       => __("Regional Tax", "event_espresso"),
113
+						'PBT_ID'         => 4,
114
+						'PRT_is_percent' => true,
115
+						'PRT_order'      => 60,
116
+						'PRT_deleted'    => false,
117
+						'PRT_wp_user'    => $default_creator_id,
118
+					),
119
+					array(
120
+						'%s',//PRT_name
121
+						'%d',//PBT_id
122
+						'%d',//PRT_is_percent
123
+						'%d',//PRT_order
124
+						'%d',//PRT_deleted
125
+						'%d', //PRT_wp_user
126
+					)
127
+				);
128
+				//federal tax
129
+				$result = $wpdb->insert(
130
+					$price_type_table,
131
+					array(
132
+						'PRT_name'       => __("Federal Tax", "event_espresso"),
133
+						'PBT_ID'         => 4,
134
+						'PRT_is_percent' => true,
135
+						'PRT_order'      => 70,
136
+						'PRT_deleted'    => false,
137
+						'PRT_wp_user'    => $default_creator_id,
138
+					),
139
+					array(
140
+						'%s',//PRT_name
141
+						'%d',//PBT_id
142
+						'%d',//PRT_is_percent
143
+						'%d',//PRT_order
144
+						'%d',//PRT_deleted
145
+						'%d' //PRT_wp_user
146
+					)
147
+				);
148
+				if ($result) {
149
+					$wpdb->insert(
150
+						$price_table,
151
+						array(
152
+							'PRT_ID'         => $wpdb->insert_id,
153
+							'PRC_amount'     => 15.00,
154
+							'PRC_name'       => __("Sales Tax", "event_espresso"),
155
+							'PRC_desc'       => '',
156
+							'PRC_is_default' => true,
157
+							'PRC_overrides'  => null,
158
+							'PRC_deleted'    => false,
159
+							'PRC_order'      => 50,
160
+							'PRC_parent'     => null,
161
+							'PRC_wp_user'    => $default_creator_id,
162
+						),
163
+						array(
164
+							'%d',//PRT_id
165
+							'%f',//PRC_amount
166
+							'%s',//PRC_name
167
+							'%s',//PRC_desc
168
+							'%d',//PRC_is_default
169
+							'%d',//PRC_overrides
170
+							'%d',//PRC_deleted
171
+							'%d',//PRC_order
172
+							'%d',//PRC_parent
173
+							'%d' //PRC_wp_user
174
+						)
175
+					);
176
+				}
177
+			}
178
+		}
179
+	}
180
+
181
+
182
+
183
+	/**
184
+	 *    caffeinated_modules_to_register
185
+	 *
186
+	 * @access public
187
+	 * @param array $modules_to_register
188
+	 * @return array
189
+	 */
190
+	public function caffeinated_modules_to_register($modules_to_register = array())
191
+	{
192
+		if (is_readable(EE_CAFF_PATH . 'modules')) {
193
+			$caffeinated_modules_to_register = glob(EE_CAFF_PATH . 'modules' . DS . '*', GLOB_ONLYDIR);
194
+			if (is_array($caffeinated_modules_to_register) && ! empty($caffeinated_modules_to_register)) {
195
+				$modules_to_register = array_merge($modules_to_register, $caffeinated_modules_to_register);
196
+			}
197
+		}
198
+		return $modules_to_register;
199
+	}
200
+
201
+
202
+
203
+	public function caffeinated_init()
204
+	{
205
+		// EE_Register_CPTs hooks
206
+		add_filter('FHEE__EE_Register_CPTs__get_taxonomies__taxonomies', array($this, 'filter_taxonomies'), 10);
207
+		add_filter('FHEE__EE_Register_CPTs__get_CPTs__cpts', array($this, 'filter_cpts'), 10);
208
+		add_filter('FHEE__EE_Admin__get_extra_nav_menu_pages_items', array($this, 'nav_metabox_items'), 10);
209
+		EE_Registry::instance()->load_file(EE_CAFF_PATH, 'EE_Caf_Messages', 'class', array(), false);
210
+		// caffeinated_init__complete hook
211
+		do_action('AHEE__EE_Brewing_Regular__caffeinated_init__complete');
212
+	}
213
+
214
+
215
+
216
+	public function enqueue_caffeinated_scripts()
217
+	{
218
+		// sound of crickets...
219
+	}
220
+
221
+
222
+
223
+	/**
224
+	 * callbacks below here
225
+	 *
226
+	 * @param array $taxonomy_array
227
+	 * @return array
228
+	 */
229
+	public function filter_taxonomies(array $taxonomy_array)
230
+	{
231
+		$taxonomy_array['espresso_venue_categories']['args']['show_in_nav_menus'] = true;
232
+		return $taxonomy_array;
233
+	}
234
+
235
+
236
+
237
+	/**
238
+	 * @param array $cpt_array
239
+	 * @return mixed
240
+	 */
241
+	public function filter_cpts(array $cpt_array)
242
+	{
243
+		$cpt_array['espresso_venues']['args']['show_in_nav_menus'] = true;
244
+		return $cpt_array;
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * @param array $menuitems
251
+	 * @return array
252
+	 */
253
+	public function nav_metabox_items(array $menuitems)
254
+	{
255
+		$menuitems[] = array(
256
+			'title'       => __('Venue List', 'event_espresso'),
257
+			'url'         => get_post_type_archive_link('espresso_venues'),
258
+			'description' => __('Archive page for all venues.', 'event_espresso'),
259
+		);
260
+		return $menuitems;
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 * Adds the payment methods in {event-espresso-core}/caffeinated/payment_methods
267
+	 *
268
+	 * @param array $payment_method_paths
269
+	 * @return array values are folder paths to payment method folders
270
+	 */
271
+	public function caf_payment_methods($payment_method_paths)
272
+	{
273
+		$caf_payment_methods_paths = glob(EE_CAF_PAYMENT_METHODS . '*', GLOB_ONLYDIR);
274
+		$payment_method_paths = array_merge($payment_method_paths, $caf_payment_methods_paths);
275
+		return $payment_method_paths;
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * Gets the injected table analyzer, or throws an exception
282
+	 *
283
+	 * @return TableAnalysis
284
+	 * @throws \EE_Error
285
+	 */
286
+	protected function _get_table_analysis()
287
+	{
288
+		if ($this->_table_analysis instanceof TableAnalysis) {
289
+			return $this->_table_analysis;
290
+		} else {
291
+			throw new \EE_Error(
292
+				sprintf(
293
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
294
+					get_class($this)
295
+				)
296
+			);
297
+		}
298
+	}
299 299
 }
300 300
 
301 301
 
302 302
 
303 303
 $brewing = new EE_Brewing_Regular(
304
-    EE_Registry::instance()->create('TableAnalysis', array(), true)
304
+	EE_Registry::instance()->create('TableAnalysis', array(), true)
305 305
 );
306 306
\ No newline at end of file
Please login to merge, or discard this patch.
core/request_stack/EE_Request.core.php 2 patches
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.
Indentation   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\interfaces\InterminableInterface;
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
 
@@ -18,231 +18,231 @@  discard block
 block discarded – undo
18 18
 class EE_Request implements InterminableInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @access private
23
-     * @var    array $_get $_GET parameters
24
-     */
25
-    private $_get = array();
26
-
27
-    /**
28
-     * @access private
29
-     * @var    array $_post $_POST parameters
30
-     */
31
-    private $_post = array();
32
-
33
-    /**
34
-     * @access private
35
-     * @var    array $_cookie $_COOKIE parameters
36
-     */
37
-    private $_cookie = array();
38
-
39
-    /**
40
-     * @access private
41
-     * @var    array $_params $_REQUEST parameters
42
-     */
43
-    private $_params = array();
44
-
45
-    /**
46
-     * whether current request is via AJAX
47
-     *
48
-     * @var    boolean
49
-     * @access public
50
-     */
51
-    public $ajax = false;
52
-
53
-    /**
54
-     * whether current request is via AJAX from the frontend of the site
55
-     *
56
-     * @var    boolean
57
-     * @access public
58
-     */
59
-    public $front_ajax = false;
60
-
61
-    /**
62
-     * IP address for request
63
-     *
64
-     * @var string $_ip_address
65
-     */
66
-    private $_ip_address = '';
67
-
68
-
69
-
70
-    /**
71
-     * class constructor
72
-     *
73
-     * @access    public
74
-     * @param array $get
75
-     * @param array $post
76
-     * @param array $cookie
77
-     */
78
-    public function __construct($get, $post, $cookie)
79
-    {
80
-        // grab request vars
81
-        $this->_get = (array)$get;
82
-        $this->_post = (array)$post;
83
-        $this->_cookie = (array)$cookie;
84
-        $this->_params = array_merge($this->_get, $this->_post);
85
-        // AJAX ???
86
-        $this->ajax = defined('DOING_AJAX') ? true : false;
87
-        $this->front_ajax = $this->is_set('ee_front_ajax') && (int)$this->get('ee_front_ajax') === 1;
88
-        // grab user IP
89
-        $this->_ip_address = $this->_visitor_ip();
90
-    }
91
-
92
-
93
-
94
-    /**
95
-     * @return array
96
-     */
97
-    public function get_params()
98
-    {
99
-        return $this->_get;
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     * @return array
106
-     */
107
-    public function post_params()
108
-    {
109
-        return $this->_post;
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * @return array
116
-     */
117
-    public function cookie_params()
118
-    {
119
-        return $this->_cookie;
120
-    }
121
-
122
-
123
-
124
-    /**
125
-     * returns contents of $_REQUEST
126
-     *
127
-     * @return array
128
-     */
129
-    public function params()
130
-    {
131
-        return $this->_params;
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     *    setter
138
-     *
139
-     * @access    public
140
-     * @param      $key
141
-     * @param      $value
142
-     * @param bool $override_ee
143
-     * @return    void
144
-     */
145
-    public function set($key, $value, $override_ee = false)
146
-    {
147
-        // don't allow "ee" to be overwritten unless explicitly instructed to do so
148
-        if (
149
-            $key !== 'ee'
150
-            || ($key === 'ee' && empty($this->_params['ee']))
151
-            || ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
152
-        ) {
153
-            $this->_params[$key] = $value;
154
-        }
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     *    getter
161
-     *
162
-     * @access    public
163
-     * @param      $key
164
-     * @param null $default
165
-     * @return    mixed
166
-     */
167
-    public function get($key, $default = null)
168
-    {
169
-        return isset($this->_params[$key]) ? $this->_params[$key] : $default;
170
-    }
171
-
172
-
173
-
174
-    /**
175
-     *    check if param exists
176
-     *
177
-     * @access    public
178
-     * @param $key
179
-     * @return    boolean
180
-     */
181
-    public function is_set($key)
182
-    {
183
-        return isset($this->_params[$key]) ? true : false;
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     *    remove param
190
-     *
191
-     * @access    public
192
-     * @param      $key
193
-     * @param bool $unset_from_global_too
194
-     */
195
-    public function un_set($key, $unset_from_global_too = false)
196
-    {
197
-        unset($this->_params[$key]);
198
-        if ($unset_from_global_too) {
199
-            unset($_REQUEST[$key]);
200
-        }
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * @return string
207
-     */
208
-    public function ip_address()
209
-    {
210
-        return $this->_ip_address;
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * _visitor_ip
217
-     *    attempt to get IP address of current visitor from server
218
-     * plz see: http://stackoverflow.com/a/2031935/1475279
219
-     *
220
-     * @access public
221
-     * @return string
222
-     */
223
-    private function _visitor_ip()
224
-    {
225
-        $visitor_ip = '0.0.0.0';
226
-        $server_keys = array(
227
-            'HTTP_CLIENT_IP',
228
-            'HTTP_X_FORWARDED_FOR',
229
-            'HTTP_X_FORWARDED',
230
-            'HTTP_X_CLUSTER_CLIENT_IP',
231
-            'HTTP_FORWARDED_FOR',
232
-            'HTTP_FORWARDED',
233
-            'REMOTE_ADDR',
234
-        );
235
-        foreach ($server_keys as $key) {
236
-            if (isset($_SERVER[$key])) {
237
-                foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
238
-                    if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
239
-                        $visitor_ip = $ip;
240
-                    }
241
-                }
242
-            }
243
-        }
244
-        return $visitor_ip;
245
-    }
21
+	/**
22
+	 * @access private
23
+	 * @var    array $_get $_GET parameters
24
+	 */
25
+	private $_get = array();
26
+
27
+	/**
28
+	 * @access private
29
+	 * @var    array $_post $_POST parameters
30
+	 */
31
+	private $_post = array();
32
+
33
+	/**
34
+	 * @access private
35
+	 * @var    array $_cookie $_COOKIE parameters
36
+	 */
37
+	private $_cookie = array();
38
+
39
+	/**
40
+	 * @access private
41
+	 * @var    array $_params $_REQUEST parameters
42
+	 */
43
+	private $_params = array();
44
+
45
+	/**
46
+	 * whether current request is via AJAX
47
+	 *
48
+	 * @var    boolean
49
+	 * @access public
50
+	 */
51
+	public $ajax = false;
52
+
53
+	/**
54
+	 * whether current request is via AJAX from the frontend of the site
55
+	 *
56
+	 * @var    boolean
57
+	 * @access public
58
+	 */
59
+	public $front_ajax = false;
60
+
61
+	/**
62
+	 * IP address for request
63
+	 *
64
+	 * @var string $_ip_address
65
+	 */
66
+	private $_ip_address = '';
67
+
68
+
69
+
70
+	/**
71
+	 * class constructor
72
+	 *
73
+	 * @access    public
74
+	 * @param array $get
75
+	 * @param array $post
76
+	 * @param array $cookie
77
+	 */
78
+	public function __construct($get, $post, $cookie)
79
+	{
80
+		// grab request vars
81
+		$this->_get = (array)$get;
82
+		$this->_post = (array)$post;
83
+		$this->_cookie = (array)$cookie;
84
+		$this->_params = array_merge($this->_get, $this->_post);
85
+		// AJAX ???
86
+		$this->ajax = defined('DOING_AJAX') ? true : false;
87
+		$this->front_ajax = $this->is_set('ee_front_ajax') && (int)$this->get('ee_front_ajax') === 1;
88
+		// grab user IP
89
+		$this->_ip_address = $this->_visitor_ip();
90
+	}
91
+
92
+
93
+
94
+	/**
95
+	 * @return array
96
+	 */
97
+	public function get_params()
98
+	{
99
+		return $this->_get;
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 * @return array
106
+	 */
107
+	public function post_params()
108
+	{
109
+		return $this->_post;
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * @return array
116
+	 */
117
+	public function cookie_params()
118
+	{
119
+		return $this->_cookie;
120
+	}
121
+
122
+
123
+
124
+	/**
125
+	 * returns contents of $_REQUEST
126
+	 *
127
+	 * @return array
128
+	 */
129
+	public function params()
130
+	{
131
+		return $this->_params;
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 *    setter
138
+	 *
139
+	 * @access    public
140
+	 * @param      $key
141
+	 * @param      $value
142
+	 * @param bool $override_ee
143
+	 * @return    void
144
+	 */
145
+	public function set($key, $value, $override_ee = false)
146
+	{
147
+		// don't allow "ee" to be overwritten unless explicitly instructed to do so
148
+		if (
149
+			$key !== 'ee'
150
+			|| ($key === 'ee' && empty($this->_params['ee']))
151
+			|| ($key === 'ee' && ! empty($this->_params['ee']) && $override_ee)
152
+		) {
153
+			$this->_params[$key] = $value;
154
+		}
155
+	}
156
+
157
+
158
+
159
+	/**
160
+	 *    getter
161
+	 *
162
+	 * @access    public
163
+	 * @param      $key
164
+	 * @param null $default
165
+	 * @return    mixed
166
+	 */
167
+	public function get($key, $default = null)
168
+	{
169
+		return isset($this->_params[$key]) ? $this->_params[$key] : $default;
170
+	}
171
+
172
+
173
+
174
+	/**
175
+	 *    check if param exists
176
+	 *
177
+	 * @access    public
178
+	 * @param $key
179
+	 * @return    boolean
180
+	 */
181
+	public function is_set($key)
182
+	{
183
+		return isset($this->_params[$key]) ? true : false;
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 *    remove param
190
+	 *
191
+	 * @access    public
192
+	 * @param      $key
193
+	 * @param bool $unset_from_global_too
194
+	 */
195
+	public function un_set($key, $unset_from_global_too = false)
196
+	{
197
+		unset($this->_params[$key]);
198
+		if ($unset_from_global_too) {
199
+			unset($_REQUEST[$key]);
200
+		}
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * @return string
207
+	 */
208
+	public function ip_address()
209
+	{
210
+		return $this->_ip_address;
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * _visitor_ip
217
+	 *    attempt to get IP address of current visitor from server
218
+	 * plz see: http://stackoverflow.com/a/2031935/1475279
219
+	 *
220
+	 * @access public
221
+	 * @return string
222
+	 */
223
+	private function _visitor_ip()
224
+	{
225
+		$visitor_ip = '0.0.0.0';
226
+		$server_keys = array(
227
+			'HTTP_CLIENT_IP',
228
+			'HTTP_X_FORWARDED_FOR',
229
+			'HTTP_X_FORWARDED',
230
+			'HTTP_X_CLUSTER_CLIENT_IP',
231
+			'HTTP_FORWARDED_FOR',
232
+			'HTTP_FORWARDED',
233
+			'REMOTE_ADDR',
234
+		);
235
+		foreach ($server_keys as $key) {
236
+			if (isset($_SERVER[$key])) {
237
+				foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
238
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
239
+						$visitor_ip = $ip;
240
+					}
241
+				}
242
+			}
243
+		}
244
+		return $visitor_ip;
245
+	}
246 246
 
247 247
 
248 248
 
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 2 patches
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.
Indentation   +745 added lines, -745 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\interfaces\ResettableInterface;
2 2
 
3 3
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 EE_Registry::instance()->load_class('Processor_Base');
7 7
 
@@ -18,748 +18,748 @@  discard block
 block discarded – undo
18 18
 class EE_Payment_Processor extends EE_Processor_Base implements ResettableInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @var EE_Payment_Processor $_instance
23
-     * @access    private
24
-     */
25
-    private static $_instance;
26
-
27
-
28
-
29
-    /**
30
-     * @singleton method used to instantiate class object
31
-     * @access    public
32
-     * @return EE_Payment_Processor instance
33
-     */
34
-    public static function instance()
35
-    {
36
-        // check if class object is instantiated
37
-        if ( ! self::$_instance instanceof EE_Payment_Processor) {
38
-            self::$_instance = new self();
39
-        }
40
-        return self::$_instance;
41
-    }
42
-
43
-
44
-
45
-    /**
46
-     * @return EE_Payment_Processor
47
-     */
48
-    public static function reset()
49
-    {
50
-        self::$_instance = null;
51
-        return self::instance();
52
-    }
53
-
54
-
55
-
56
-    /**
57
-     *private constructor to prevent direct creation
58
-     *
59
-     * @Constructor
60
-     * @access private
61
-     */
62
-    private function __construct()
63
-    {
64
-        do_action('AHEE__EE_Payment_Processor__construct');
65
-        add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
66
-    }
67
-
68
-
69
-
70
-    /**
71
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction
72
-     * appropriately. Saves the payment that is generated
73
-     *
74
-     * @param EE_Payment_Method    $payment_method
75
-     * @param EE_Transaction       $transaction
76
-     * @param float                $amount       if only part of the transaction is to be paid for, how much.
77
-     *                                           Leave null if payment is for the full amount owing
78
-     * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
79
-     *                                           Receive_form_submission() should have
80
-     *                                           already been called on the billing form
81
-     *                                           (ie, its inputs should have their normalized values set).
82
-     * @param string               $return_url   string used mostly by offsite gateways to specify
83
-     *                                           where to go AFTER the offsite gateway
84
-     * @param string               $method       like 'CART', indicates who the client who called this was
85
-     * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
86
-     * @param boolean              $update_txn   whether or not to call
87
-     *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
88
-     * @param string               $cancel_url   URL to return to if off-site payments are cancelled
89
-     * @return \EE_Payment
90
-     * @throws \EE_Error
91
-     */
92
-    public function process_payment(
93
-        EE_Payment_Method $payment_method,
94
-        EE_Transaction $transaction,
95
-        $amount = null,
96
-        $billing_form = null,
97
-        $return_url = null,
98
-        $method = 'CART',
99
-        $by_admin = false,
100
-        $update_txn = true,
101
-        $cancel_url = ''
102
-    ) {
103
-        if ((float)$amount < 0) {
104
-            throw new EE_Error(
105
-                sprintf(
106
-                    __(
107
-                        'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
108
-                        'event_espresso'
109
-                    ),
110
-                    $amount,
111
-                    $transaction->ID()
112
-                )
113
-            );
114
-        }
115
-        // verify payment method
116
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
117
-        // verify transaction
118
-        EEM_Transaction::instance()->ensure_is_obj($transaction);
119
-        $transaction->set_payment_method_ID($payment_method->ID());
120
-        // verify payment method type
121
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
122
-            $payment = $payment_method->type_obj()->process_payment(
123
-                $transaction,
124
-                min($amount, $transaction->remaining()),//make sure we don't overcharge
125
-                $billing_form,
126
-                $return_url,
127
-                add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
128
-                $method,
129
-                $by_admin
130
-            );
131
-            // check if payment method uses an off-site gateway
132
-            if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
133
-                // don't process payments for off-site gateways yet because no payment has occurred yet
134
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
135
-            }
136
-            return $payment;
137
-        } else {
138
-            EE_Error::add_error(
139
-                sprintf(
140
-                    __('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
141
-                    '<br/>',
142
-                    EE_Registry::instance()->CFG->organization->get_pretty('email')
143
-                ), __FILE__, __FUNCTION__, __LINE__
144
-            );
145
-            return null;
146
-        }
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @param EE_Transaction|int $transaction
153
-     * @param EE_Payment_Method  $payment_method
154
-     * @throws EE_Error
155
-     * @return string
156
-     */
157
-    public function get_ipn_url_for_payment_method($transaction, $payment_method)
158
-    {
159
-        /** @type \EE_Transaction $transaction */
160
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
161
-        $primary_reg = $transaction->primary_registration();
162
-        if ( ! $primary_reg instanceof EE_Registration) {
163
-            throw new EE_Error(
164
-                sprintf(
165
-                    __(
166
-                        "Cannot get IPN URL for transaction with ID %d because it has no primary registration",
167
-                        "event_espresso"
168
-                    ),
169
-                    $transaction->ID()
170
-                )
171
-            );
172
-        }
173
-        $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
174
-        $url = add_query_arg(
175
-            array(
176
-                'e_reg_url_link'    => $primary_reg->reg_url_link(),
177
-                'ee_payment_method' => $payment_method->slug(),
178
-            ),
179
-            EE_Registry::instance()->CFG->core->txn_page_url()
180
-        );
181
-        return $url;
182
-    }
183
-
184
-
185
-
186
-    /**
187
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
188
-     * we can easily find what registration the IPN is for and what payment method.
189
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
190
-     * If a payment is found for the IPN info, it is saved.
191
-     *
192
-     * @param array              $_req_data            eg $_REQUEST
193
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
194
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
195
-     * @param boolean            $update_txn           whether or not to call
196
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
197
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
198
-     *                                                 or is processed manually ( false like Mijireh )
199
-     * @throws EE_Error
200
-     * @throws Exception
201
-     * @return EE_Payment
202
-     */
203
-    public function process_ipn(
204
-        $_req_data,
205
-        $transaction = null,
206
-        $payment_method = null,
207
-        $update_txn = true,
208
-        $separate_IPN_request = true
209
-    ) {
210
-        EE_Registry::instance()->load_model('Change_Log');
211
-        $_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
212
-        EE_Processor_Base::set_IPN($separate_IPN_request);
213
-        $obj_for_log = null;
214
-        if ($transaction instanceof EE_Transaction) {
215
-            $obj_for_log = $transaction;
216
-            if ($payment_method instanceof EE_Payment_Method) {
217
-                $obj_for_log = EEM_Payment::instance()->get_one(
218
-                    array(
219
-                        array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
220
-                        'order_by' => array('PAY_timestamp' => 'desc'),
221
-                    )
222
-                );
223
-            }
224
-        } else if ($payment_method instanceof EE_Payment) {
225
-            $obj_for_log = $payment_method;
226
-        }
227
-        $log = EEM_Change_Log::instance()->log(
228
-            EEM_Change_Log::type_gateway,
229
-            array('IPN data received' => $_req_data),
230
-            $obj_for_log
231
-        );
232
-        try {
233
-            /**
234
-             * @var EE_Payment $payment
235
-             */
236
-            $payment = null;
237
-            if ($transaction && $payment_method) {
238
-                /** @type EE_Transaction $transaction */
239
-                $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
240
-                /** @type EE_Payment_Method $payment_method */
241
-                $payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
242
-                if ($payment_method->type_obj() instanceof EE_PMT_Base) {
243
-                    try {
244
-                        $payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
245
-                        $log->set_object($payment);
246
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
247
-                        EEM_Change_Log::instance()->log(
248
-                            EEM_Change_Log::type_gateway,
249
-                            array(
250
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
251
-                                'current_url' => EEH_URL::current_url(),
252
-                                'payment'     => $e->getPaymentProperties(),
253
-                                'IPN_data'    => $e->getIpnData(),
254
-                            ),
255
-                            $obj_for_log
256
-                        );
257
-                        return $e->getPayment();
258
-                    }
259
-                } else {
260
-                    // not a payment
261
-                    EE_Error::add_error(
262
-                        sprintf(
263
-                            __('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
264
-                            '<br/>',
265
-                            EE_Registry::instance()->CFG->organization->get_pretty('email')
266
-                        ),
267
-                        __FILE__, __FUNCTION__, __LINE__
268
-                    );
269
-                }
270
-            } else {
271
-                //that's actually pretty ok. The IPN just wasn't able
272
-                //to identify which transaction or payment method this was for
273
-                // give all active payment methods a chance to claim it
274
-                $active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
275
-                foreach ($active_payment_methods as $active_payment_method) {
276
-                    try {
277
-                        $payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
278
-                        $payment_method = $active_payment_method;
279
-                        EEM_Change_Log::instance()->log(
280
-                            EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
281
-                        );
282
-                        break;
283
-                    } catch (EventEspresso\core\exceptions\IpnException $e) {
284
-                        EEM_Change_Log::instance()->log(
285
-                            EEM_Change_Log::type_gateway,
286
-                            array(
287
-                                'message'     => 'IPN Exception: ' . $e->getMessage(),
288
-                                'current_url' => EEH_URL::current_url(),
289
-                                'payment'     => $e->getPaymentProperties(),
290
-                                'IPN_data'    => $e->getIpnData(),
291
-                            ),
292
-                            $obj_for_log
293
-                        );
294
-                        return $e->getPayment();
295
-                    } catch (EE_Error $e) {
296
-                        //that's fine- it apparently couldn't handle the IPN
297
-                    }
298
-                }
299
-            }
300
-            // 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
301
-            if ($payment instanceof EE_Payment) {
302
-                $payment->save();
303
-                //  update the TXN
304
-                $this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
305
-            } else {
306
-                //we couldn't find the payment for this IPN... let's try and log at least SOMETHING
307
-                if ($payment_method) {
308
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
309
-                } elseif ($transaction) {
310
-                    EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
311
-                }
312
-            }
313
-            return $payment;
314
-        } catch (EE_Error $e) {
315
-            do_action(
316
-                'AHEE__log', __FILE__, __FUNCTION__, sprintf(
317
-                    __('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
318
-                    print_r($transaction, true),
319
-                    print_r($_req_data, true),
320
-                    $e->getMessage()
321
-                )
322
-            );
323
-            throw $e;
324
-        }
325
-    }
326
-
327
-
328
-
329
-    /**
330
-     * Removes any non-printable illegal characters from the input,
331
-     * which might cause a raucous when trying to insert into the database
332
-     *
333
-     * @param  array $request_data
334
-     * @return array
335
-     */
336
-    protected function _remove_unusable_characters_from_array(array $request_data)
337
-    {
338
-        $return_data = array();
339
-        foreach ($request_data as $key => $value) {
340
-            $return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
341
-        }
342
-        return $return_data;
343
-    }
344
-
345
-
346
-
347
-    /**
348
-     * Removes any non-printable illegal characters from the input,
349
-     * which might cause a raucous when trying to insert into the database
350
-     *
351
-     * @param string $request_data
352
-     * @return string
353
-     */
354
-    protected function _remove_unusable_characters($request_data)
355
-    {
356
-        return preg_replace('/[^[:print:]]/', '', $request_data);
357
-    }
358
-
359
-
360
-
361
-    /**
362
-     * Should be called just before displaying the payment attempt results to the user,
363
-     * when the payment attempt has finished. Some payment methods may have special
364
-     * logic to perform here. For example, if process_payment() happens on a special request
365
-     * and then the user is redirected to a page that displays the payment's status, this
366
-     * should be called while loading the page that displays the payment's status. If the user is
367
-     * sent to an offsite payment provider, this should be called upon returning from that offsite payment
368
-     * provider.
369
-     *
370
-     * @param EE_Transaction|int $transaction
371
-     * @param bool               $update_txn whether or not to call
372
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
373
-     * @throws \EE_Error
374
-     * @return EE_Payment
375
-     * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
376
-     *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
377
-     */
378
-    public function finalize_payment_for($transaction, $update_txn = true)
379
-    {
380
-        /** @var $transaction EE_Transaction */
381
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
382
-        $last_payment_method = $transaction->payment_method();
383
-        if ($last_payment_method instanceof EE_Payment_Method) {
384
-            $payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
385
-            $this->update_txn_based_on_payment($transaction, $payment, $update_txn);
386
-            return $payment;
387
-        } else {
388
-            return null;
389
-        }
390
-    }
391
-
392
-
393
-
394
-    /**
395
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
396
-     *
397
-     * @param EE_Payment_Method $payment_method
398
-     * @param EE_Payment        $payment_to_refund
399
-     * @param array             $refund_info
400
-     * @return EE_Payment
401
-     * @throws \EE_Error
402
-     */
403
-    public function process_refund(
404
-        EE_Payment_Method $payment_method,
405
-        EE_Payment $payment_to_refund,
406
-        $refund_info = array()
407
-    ) {
408
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
409
-            $payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
410
-            $this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
411
-        }
412
-        return $payment_to_refund;
413
-    }
414
-
415
-
416
-
417
-    /**
418
-     * This should be called each time there may have been an update to a
419
-     * payment on a transaction (ie, we asked for a payment to process a
420
-     * payment for a transaction, or we told a payment method about an IPN, or
421
-     * we told a payment method to
422
-     * "finalize_payment_for" (a transaction), or we told a payment method to
423
-     * process a refund. This should handle firing the correct hooks to
424
-     * indicate
425
-     * what exactly happened and updating the transaction appropriately). This
426
-     * could be integrated directly into EE_Transaction upon save, but we want
427
-     * this logic to be separate from 'normal' plain-jane saving and updating
428
-     * of transactions and payments, and to be tied to payment processing.
429
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
430
-     * of previous code to decide whether or not to save (because the payment passed into
431
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
432
-     * in which case we only want that payment object for some temporary usage during this request,
433
-     * but we don't want it to be saved).
434
-     *
435
-     * @param EE_Transaction|int $transaction
436
-     * @param EE_Payment         $payment
437
-     * @param boolean            $update_txn
438
-     *                        whether or not to call
439
-     *                        EE_Transaction_Processor::
440
-     *                        update_transaction_and_registrations_after_checkout_or_payment()
441
-     *                        (you can save 1 DB query if you know you're going
442
-     *                        to save it later instead)
443
-     * @param bool               $IPN
444
-     *                        if processing IPNs or other similar payment
445
-     *                        related activities that occur in alternate
446
-     *                        requests than the main one that is processing the
447
-     *                        TXN, then set this to true to check whether the
448
-     *                        TXN is locked before updating
449
-     * @throws \EE_Error
450
-     */
451
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
452
-    {
453
-        $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
454
-        /** @type EE_Transaction $transaction */
455
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
456
-        // can we freely update the TXN at this moment?
457
-        if ($IPN && $transaction->is_locked()) {
458
-            // don't update the transaction at this exact moment
459
-            // because the TXN is active in another request
460
-            EE_Cron_Tasks::schedule_update_transaction_with_payment(
461
-                time(),
462
-                $transaction->ID(),
463
-                $payment->ID()
464
-            );
465
-        } else {
466
-            // verify payment and that it has been saved
467
-            if ($payment instanceof EE_Payment && $payment->ID()) {
468
-                if (
469
-                    $payment->payment_method() instanceof EE_Payment_Method
470
-                    && $payment->payment_method()->type_obj() instanceof EE_PMT_Base
471
-                ) {
472
-                    $payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
473
-                    // update TXN registrations with payment info
474
-                    $this->process_registration_payments($transaction, $payment);
475
-                }
476
-                $do_action = $payment->just_approved()
477
-                    ? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
478
-                    : $do_action;
479
-            } else {
480
-                // send out notifications
481
-                add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
482
-                $do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
483
-            }
484
-            if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
485
-                /** @type EE_Transaction_Payments $transaction_payments */
486
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
487
-                // set new value for total paid
488
-                $transaction_payments->calculate_total_payments_and_update_status($transaction);
489
-                // call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
490
-                if ($update_txn) {
491
-                    $this->_post_payment_processing($transaction, $payment, $IPN);
492
-                }
493
-            }
494
-            // granular hook for others to use.
495
-            do_action($do_action, $transaction, $payment);
496
-            do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
497
-            //global hook for others to use.
498
-            do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
499
-        }
500
-    }
501
-
502
-
503
-
504
-    /**
505
-     * update registrations REG_paid field after successful payment and link registrations with payment
506
-     *
507
-     * @param EE_Transaction    $transaction
508
-     * @param EE_Payment        $payment
509
-     * @param EE_Registration[] $registrations
510
-     * @throws \EE_Error
511
-     */
512
-    public function process_registration_payments(
513
-        EE_Transaction $transaction,
514
-        EE_Payment $payment,
515
-        $registrations = array()
516
-    ) {
517
-        // only process if payment was successful
518
-        if ($payment->status() !== EEM_Payment::status_id_approved) {
519
-            return;
520
-        }
521
-        //EEM_Registration::instance()->show_next_x_db_queries();
522
-        if (empty($registrations)) {
523
-            // find registrations with monies owing that can receive a payment
524
-            $registrations = $transaction->registrations(
525
-                array(
526
-                    array(
527
-                        // only these reg statuses can receive payments
528
-                        'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
529
-                        'REG_final_price'  => array('!=', 0),
530
-                        'REG_final_price*' => array('!=', 'REG_paid', true),
531
-                    ),
532
-                )
533
-            );
534
-        }
535
-        // still nothing ??!??
536
-        if (empty($registrations)) {
537
-            return;
538
-        }
539
-        // todo: break out the following logic into a separate strategy class
540
-        // todo: named something like "Sequential_Reg_Payment_Strategy"
541
-        // todo: which would apply payments using the capitalist "first come first paid" approach
542
-        // todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
543
-        // todo: which would be the socialist "everybody gets a piece of pie" approach,
544
-        // todo: which would be better for deposits, where you want a bit of the payment applied to each registration
545
-        $refund = $payment->is_a_refund();
546
-        // how much is available to apply to registrations?
547
-        $available_payment_amount = abs($payment->amount());
548
-        foreach ($registrations as $registration) {
549
-            if ($registration instanceof EE_Registration) {
550
-                // nothing left?
551
-                if ($available_payment_amount <= 0) {
552
-                    break;
553
-                }
554
-                if ($refund) {
555
-                    $available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
556
-                } else {
557
-                    $available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
558
-                }
559
-            }
560
-        }
561
-        if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
562
-            EE_Error::add_attention(
563
-                sprintf(
564
-                    __('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
565
-                        'event_espresso'),
566
-                    EEH_Template::format_currency($available_payment_amount),
567
-                    implode(', ', array_keys($registrations)),
568
-                    '<br/>',
569
-                    EEH_Template::format_currency($payment->amount())
570
-                ),
571
-                __FILE__, __FUNCTION__, __LINE__
572
-            );
573
-        }
574
-    }
575
-
576
-
577
-
578
-    /**
579
-     * update registration REG_paid field after successful payment and link registration with payment
580
-     *
581
-     * @param EE_Registration $registration
582
-     * @param EE_Payment      $payment
583
-     * @param float           $available_payment_amount
584
-     * @return float
585
-     * @throws \EE_Error
586
-     */
587
-    public function process_registration_payment(
588
-        EE_Registration $registration,
589
-        EE_Payment $payment,
590
-        $available_payment_amount = 0.00
591
-    ) {
592
-        $owing = $registration->final_price() - $registration->paid();
593
-        if ($owing > 0) {
594
-            // don't allow payment amount to exceed the available payment amount, OR the amount owing
595
-            $payment_amount = min($available_payment_amount, $owing);
596
-            // update $available_payment_amount
597
-            $available_payment_amount -= $payment_amount;
598
-            //calculate and set new REG_paid
599
-            $registration->set_paid($registration->paid() + $payment_amount);
600
-            // now save it
601
-            $this->_apply_registration_payment($registration, $payment, $payment_amount);
602
-        }
603
-        return $available_payment_amount;
604
-    }
605
-
606
-
607
-
608
-    /**
609
-     * update registration REG_paid field after successful payment and link registration with payment
610
-     *
611
-     * @param EE_Registration $registration
612
-     * @param EE_Payment      $payment
613
-     * @param float           $payment_amount
614
-     * @return void
615
-     * @throws \EE_Error
616
-     */
617
-    protected function _apply_registration_payment(
618
-        EE_Registration $registration,
619
-        EE_Payment $payment,
620
-        $payment_amount = 0.00
621
-    ) {
622
-        // find any existing reg payment records for this registration and payment
623
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
624
-            array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
625
-        );
626
-        // if existing registration payment exists
627
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
628
-            // then update that record
629
-            $existing_reg_payment->set_amount($payment_amount);
630
-            $existing_reg_payment->save();
631
-        } else {
632
-            // or add new relation between registration and payment and set amount
633
-            $registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
634
-            // make it stick
635
-            $registration->save();
636
-        }
637
-    }
638
-
639
-
640
-
641
-    /**
642
-     * update registration REG_paid field after refund and link registration with payment
643
-     *
644
-     * @param EE_Registration $registration
645
-     * @param EE_Payment      $payment
646
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
647
-     * @return float
648
-     * @throws \EE_Error
649
-     */
650
-    public function process_registration_refund(
651
-        EE_Registration $registration,
652
-        EE_Payment $payment,
653
-        $available_refund_amount = 0.00
654
-    ) {
655
-        //EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
656
-        if ($registration->paid() > 0) {
657
-            // ensure $available_refund_amount is NOT negative
658
-            $available_refund_amount = (float)abs($available_refund_amount);
659
-            // don't allow refund amount to exceed the available payment amount, OR the amount paid
660
-            $refund_amount = min($available_refund_amount, (float)$registration->paid());
661
-            // update $available_payment_amount
662
-            $available_refund_amount -= $refund_amount;
663
-            //calculate and set new REG_paid
664
-            $registration->set_paid($registration->paid() - $refund_amount);
665
-            // convert payment amount back to a negative value for storage in the db
666
-            $refund_amount = (float)abs($refund_amount) * -1;
667
-            // now save it
668
-            $this->_apply_registration_payment($registration, $payment, $refund_amount);
669
-        }
670
-        return $available_refund_amount;
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * Process payments and transaction after payment process completed.
677
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
678
-     * if this request happens to be processing an IPN,
679
-     * then we will also set the Payment Options Reg Step to completed,
680
-     * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
681
-     *
682
-     * @param EE_Transaction $transaction
683
-     * @param EE_Payment     $payment
684
-     * @param bool           $IPN
685
-     * @throws \EE_Error
686
-     */
687
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
688
-    {
689
-        /** @type EE_Transaction_Processor $transaction_processor */
690
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
691
-        // is the Payment Options Reg Step completed ?
692
-        $payment_options_step_completed = $transaction->reg_step_completed('payment_options');
693
-        // if the Payment Options Reg Step is completed...
694
-        $revisit = $payment_options_step_completed === true ? true : false;
695
-        // then this is kinda sorta a revisit with regards to payments at least
696
-        $transaction_processor->set_revisit($revisit);
697
-        // if this is an IPN, let's consider the Payment Options Reg Step completed if not already
698
-        if (
699
-            $IPN
700
-            && $payment_options_step_completed !== true
701
-            && ($payment->is_approved() || $payment->is_pending())
702
-        ) {
703
-            $payment_options_step_completed = $transaction->set_reg_step_completed(
704
-                'payment_options'
705
-            );
706
-        }
707
-        // maybe update status, but don't save transaction just yet
708
-        $transaction->update_status_based_on_total_paid(false);
709
-        // check if 'finalize_registration' step has been completed...
710
-        $finalized = $transaction->reg_step_completed('finalize_registration');
711
-        //  if this is an IPN and the final step has not been initiated
712
-        if ($IPN && $payment_options_step_completed && $finalized === false) {
713
-            // and if it hasn't already been set as being started...
714
-            $finalized = $transaction->set_reg_step_initiated('finalize_registration');
715
-        }
716
-        $transaction->save();
717
-        // because the above will return false if the final step was not fully completed, we need to check again...
718
-        if ($IPN && $finalized !== false) {
719
-            // and if we are all good to go, then send out notifications
720
-            add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
721
-            //ok, now process the transaction according to the payment
722
-            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
723
-        }
724
-        // DEBUG LOG
725
-        $payment_method = $payment->payment_method();
726
-        if ($payment_method instanceof EE_Payment_Method) {
727
-            $payment_method_type_obj = $payment_method->type_obj();
728
-            if ($payment_method_type_obj instanceof EE_PMT_Base) {
729
-                $gateway = $payment_method_type_obj->get_gateway();
730
-                if ($gateway instanceof EE_Gateway) {
731
-                    $gateway->log(
732
-                        array(
733
-                            'message'               => __('Post Payment Transaction Details', 'event_espresso'),
734
-                            'transaction'           => $transaction->model_field_array(),
735
-                            'finalized'             => $finalized,
736
-                            'IPN'                   => $IPN,
737
-                            'deliver_notifications' => has_filter(
738
-                                'FHEE__EED_Messages___maybe_registration__deliver_notifications'
739
-                            ),
740
-                        ),
741
-                        $payment
742
-                    );
743
-                }
744
-            }
745
-        }
746
-    }
747
-
748
-
749
-
750
-    /**
751
-     * Force posts to PayPal to use TLS v1.2. See:
752
-     * https://core.trac.wordpress.org/ticket/36320
753
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
754
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
755
-     * This will affect paypal standard, pro, express, and payflow.
756
-     */
757
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
758
-    {
759
-        if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
760
-            //Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
761
-            //instead of the constant because it might not be defined
762
-            curl_setopt($handle, CURLOPT_SSLVERSION, 1);
763
-        }
764
-    }
21
+	/**
22
+	 * @var EE_Payment_Processor $_instance
23
+	 * @access    private
24
+	 */
25
+	private static $_instance;
26
+
27
+
28
+
29
+	/**
30
+	 * @singleton method used to instantiate class object
31
+	 * @access    public
32
+	 * @return EE_Payment_Processor instance
33
+	 */
34
+	public static function instance()
35
+	{
36
+		// check if class object is instantiated
37
+		if ( ! self::$_instance instanceof EE_Payment_Processor) {
38
+			self::$_instance = new self();
39
+		}
40
+		return self::$_instance;
41
+	}
42
+
43
+
44
+
45
+	/**
46
+	 * @return EE_Payment_Processor
47
+	 */
48
+	public static function reset()
49
+	{
50
+		self::$_instance = null;
51
+		return self::instance();
52
+	}
53
+
54
+
55
+
56
+	/**
57
+	 *private constructor to prevent direct creation
58
+	 *
59
+	 * @Constructor
60
+	 * @access private
61
+	 */
62
+	private function __construct()
63
+	{
64
+		do_action('AHEE__EE_Payment_Processor__construct');
65
+		add_action('http_api_curl', array($this, '_curl_requests_to_paypal_use_tls'), 10, 3);
66
+	}
67
+
68
+
69
+
70
+	/**
71
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction
72
+	 * appropriately. Saves the payment that is generated
73
+	 *
74
+	 * @param EE_Payment_Method    $payment_method
75
+	 * @param EE_Transaction       $transaction
76
+	 * @param float                $amount       if only part of the transaction is to be paid for, how much.
77
+	 *                                           Leave null if payment is for the full amount owing
78
+	 * @param EE_Billing_Info_Form $billing_form (or probably null, if it's an offline or offsite payment method).
79
+	 *                                           Receive_form_submission() should have
80
+	 *                                           already been called on the billing form
81
+	 *                                           (ie, its inputs should have their normalized values set).
82
+	 * @param string               $return_url   string used mostly by offsite gateways to specify
83
+	 *                                           where to go AFTER the offsite gateway
84
+	 * @param string               $method       like 'CART', indicates who the client who called this was
85
+	 * @param bool                 $by_admin     TRUE if payment is being attempted from the admin
86
+	 * @param boolean              $update_txn   whether or not to call
87
+	 *                                           EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
88
+	 * @param string               $cancel_url   URL to return to if off-site payments are cancelled
89
+	 * @return \EE_Payment
90
+	 * @throws \EE_Error
91
+	 */
92
+	public function process_payment(
93
+		EE_Payment_Method $payment_method,
94
+		EE_Transaction $transaction,
95
+		$amount = null,
96
+		$billing_form = null,
97
+		$return_url = null,
98
+		$method = 'CART',
99
+		$by_admin = false,
100
+		$update_txn = true,
101
+		$cancel_url = ''
102
+	) {
103
+		if ((float)$amount < 0) {
104
+			throw new EE_Error(
105
+				sprintf(
106
+					__(
107
+						'Attempting to make a payment for a negative amount of %1$d for transaction %2$d. That should be a refund',
108
+						'event_espresso'
109
+					),
110
+					$amount,
111
+					$transaction->ID()
112
+				)
113
+			);
114
+		}
115
+		// verify payment method
116
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
117
+		// verify transaction
118
+		EEM_Transaction::instance()->ensure_is_obj($transaction);
119
+		$transaction->set_payment_method_ID($payment_method->ID());
120
+		// verify payment method type
121
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
122
+			$payment = $payment_method->type_obj()->process_payment(
123
+				$transaction,
124
+				min($amount, $transaction->remaining()),//make sure we don't overcharge
125
+				$billing_form,
126
+				$return_url,
127
+				add_query_arg(array('ee_cancel_payment' => true), $cancel_url),
128
+				$method,
129
+				$by_admin
130
+			);
131
+			// check if payment method uses an off-site gateway
132
+			if ($payment_method->type_obj()->payment_occurs() !== EE_PMT_Base::offsite) {
133
+				// don't process payments for off-site gateways yet because no payment has occurred yet
134
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
135
+			}
136
+			return $payment;
137
+		} else {
138
+			EE_Error::add_error(
139
+				sprintf(
140
+					__('A valid payment method could not be determined due to a technical issue.%sPlease try again or contact %s for assistance.', 'event_espresso'),
141
+					'<br/>',
142
+					EE_Registry::instance()->CFG->organization->get_pretty('email')
143
+				), __FILE__, __FUNCTION__, __LINE__
144
+			);
145
+			return null;
146
+		}
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @param EE_Transaction|int $transaction
153
+	 * @param EE_Payment_Method  $payment_method
154
+	 * @throws EE_Error
155
+	 * @return string
156
+	 */
157
+	public function get_ipn_url_for_payment_method($transaction, $payment_method)
158
+	{
159
+		/** @type \EE_Transaction $transaction */
160
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
161
+		$primary_reg = $transaction->primary_registration();
162
+		if ( ! $primary_reg instanceof EE_Registration) {
163
+			throw new EE_Error(
164
+				sprintf(
165
+					__(
166
+						"Cannot get IPN URL for transaction with ID %d because it has no primary registration",
167
+						"event_espresso"
168
+					),
169
+					$transaction->ID()
170
+				)
171
+			);
172
+		}
173
+		$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method, true);
174
+		$url = add_query_arg(
175
+			array(
176
+				'e_reg_url_link'    => $primary_reg->reg_url_link(),
177
+				'ee_payment_method' => $payment_method->slug(),
178
+			),
179
+			EE_Registry::instance()->CFG->core->txn_page_url()
180
+		);
181
+		return $url;
182
+	}
183
+
184
+
185
+
186
+	/**
187
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
188
+	 * we can easily find what registration the IPN is for and what payment method.
189
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
190
+	 * If a payment is found for the IPN info, it is saved.
191
+	 *
192
+	 * @param array              $_req_data            eg $_REQUEST
193
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
194
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
195
+	 * @param boolean            $update_txn           whether or not to call
196
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
197
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request ( true like PayPal )
198
+	 *                                                 or is processed manually ( false like Mijireh )
199
+	 * @throws EE_Error
200
+	 * @throws Exception
201
+	 * @return EE_Payment
202
+	 */
203
+	public function process_ipn(
204
+		$_req_data,
205
+		$transaction = null,
206
+		$payment_method = null,
207
+		$update_txn = true,
208
+		$separate_IPN_request = true
209
+	) {
210
+		EE_Registry::instance()->load_model('Change_Log');
211
+		$_req_data = $this->_remove_unusable_characters_from_array((array)$_req_data);
212
+		EE_Processor_Base::set_IPN($separate_IPN_request);
213
+		$obj_for_log = null;
214
+		if ($transaction instanceof EE_Transaction) {
215
+			$obj_for_log = $transaction;
216
+			if ($payment_method instanceof EE_Payment_Method) {
217
+				$obj_for_log = EEM_Payment::instance()->get_one(
218
+					array(
219
+						array('TXN_ID' => $transaction->ID(), 'PMD_ID' => $payment_method->ID()),
220
+						'order_by' => array('PAY_timestamp' => 'desc'),
221
+					)
222
+				);
223
+			}
224
+		} else if ($payment_method instanceof EE_Payment) {
225
+			$obj_for_log = $payment_method;
226
+		}
227
+		$log = EEM_Change_Log::instance()->log(
228
+			EEM_Change_Log::type_gateway,
229
+			array('IPN data received' => $_req_data),
230
+			$obj_for_log
231
+		);
232
+		try {
233
+			/**
234
+			 * @var EE_Payment $payment
235
+			 */
236
+			$payment = null;
237
+			if ($transaction && $payment_method) {
238
+				/** @type EE_Transaction $transaction */
239
+				$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
240
+				/** @type EE_Payment_Method $payment_method */
241
+				$payment_method = EEM_Payment_Method::instance()->ensure_is_obj($payment_method);
242
+				if ($payment_method->type_obj() instanceof EE_PMT_Base) {
243
+					try {
244
+						$payment = $payment_method->type_obj()->handle_ipn($_req_data, $transaction);
245
+						$log->set_object($payment);
246
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
247
+						EEM_Change_Log::instance()->log(
248
+							EEM_Change_Log::type_gateway,
249
+							array(
250
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
251
+								'current_url' => EEH_URL::current_url(),
252
+								'payment'     => $e->getPaymentProperties(),
253
+								'IPN_data'    => $e->getIpnData(),
254
+							),
255
+							$obj_for_log
256
+						);
257
+						return $e->getPayment();
258
+					}
259
+				} else {
260
+					// not a payment
261
+					EE_Error::add_error(
262
+						sprintf(
263
+							__('A valid payment method could not be determined due to a technical issue.%sPlease refresh your browser and try again or contact %s for assistance.', 'event_espresso'),
264
+							'<br/>',
265
+							EE_Registry::instance()->CFG->organization->get_pretty('email')
266
+						),
267
+						__FILE__, __FUNCTION__, __LINE__
268
+					);
269
+				}
270
+			} else {
271
+				//that's actually pretty ok. The IPN just wasn't able
272
+				//to identify which transaction or payment method this was for
273
+				// give all active payment methods a chance to claim it
274
+				$active_payment_methods = EEM_Payment_Method::instance()->get_all_active();
275
+				foreach ($active_payment_methods as $active_payment_method) {
276
+					try {
277
+						$payment = $active_payment_method->type_obj()->handle_unclaimed_ipn($_req_data);
278
+						$payment_method = $active_payment_method;
279
+						EEM_Change_Log::instance()->log(
280
+							EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment
281
+						);
282
+						break;
283
+					} catch (EventEspresso\core\exceptions\IpnException $e) {
284
+						EEM_Change_Log::instance()->log(
285
+							EEM_Change_Log::type_gateway,
286
+							array(
287
+								'message'     => 'IPN Exception: ' . $e->getMessage(),
288
+								'current_url' => EEH_URL::current_url(),
289
+								'payment'     => $e->getPaymentProperties(),
290
+								'IPN_data'    => $e->getIpnData(),
291
+							),
292
+							$obj_for_log
293
+						);
294
+						return $e->getPayment();
295
+					} catch (EE_Error $e) {
296
+						//that's fine- it apparently couldn't handle the IPN
297
+					}
298
+				}
299
+			}
300
+			// 			EEM_Payment_Log::instance()->log("got to 7",$transaction,$payment_method);
301
+			if ($payment instanceof EE_Payment) {
302
+				$payment->save();
303
+				//  update the TXN
304
+				$this->update_txn_based_on_payment($transaction, $payment, $update_txn, $separate_IPN_request);
305
+			} else {
306
+				//we couldn't find the payment for this IPN... let's try and log at least SOMETHING
307
+				if ($payment_method) {
308
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $payment_method);
309
+				} elseif ($transaction) {
310
+					EEM_Change_Log::instance()->log(EEM_Change_Log::type_gateway, array('IPN data' => $_req_data), $transaction);
311
+				}
312
+			}
313
+			return $payment;
314
+		} catch (EE_Error $e) {
315
+			do_action(
316
+				'AHEE__log', __FILE__, __FUNCTION__, sprintf(
317
+					__('Error occurred while receiving IPN. Transaction: %1$s, req data: %2$s. The error was "%3$s"', 'event_espresso'),
318
+					print_r($transaction, true),
319
+					print_r($_req_data, true),
320
+					$e->getMessage()
321
+				)
322
+			);
323
+			throw $e;
324
+		}
325
+	}
326
+
327
+
328
+
329
+	/**
330
+	 * Removes any non-printable illegal characters from the input,
331
+	 * which might cause a raucous when trying to insert into the database
332
+	 *
333
+	 * @param  array $request_data
334
+	 * @return array
335
+	 */
336
+	protected function _remove_unusable_characters_from_array(array $request_data)
337
+	{
338
+		$return_data = array();
339
+		foreach ($request_data as $key => $value) {
340
+			$return_data[$this->_remove_unusable_characters($key)] = $this->_remove_unusable_characters($value);
341
+		}
342
+		return $return_data;
343
+	}
344
+
345
+
346
+
347
+	/**
348
+	 * Removes any non-printable illegal characters from the input,
349
+	 * which might cause a raucous when trying to insert into the database
350
+	 *
351
+	 * @param string $request_data
352
+	 * @return string
353
+	 */
354
+	protected function _remove_unusable_characters($request_data)
355
+	{
356
+		return preg_replace('/[^[:print:]]/', '', $request_data);
357
+	}
358
+
359
+
360
+
361
+	/**
362
+	 * Should be called just before displaying the payment attempt results to the user,
363
+	 * when the payment attempt has finished. Some payment methods may have special
364
+	 * logic to perform here. For example, if process_payment() happens on a special request
365
+	 * and then the user is redirected to a page that displays the payment's status, this
366
+	 * should be called while loading the page that displays the payment's status. If the user is
367
+	 * sent to an offsite payment provider, this should be called upon returning from that offsite payment
368
+	 * provider.
369
+	 *
370
+	 * @param EE_Transaction|int $transaction
371
+	 * @param bool               $update_txn whether or not to call
372
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
373
+	 * @throws \EE_Error
374
+	 * @return EE_Payment
375
+	 * @deprecated 4.6.24 method is no longer used. Instead it is up to client code, like SPCO,
376
+	 *                                       to call handle_ipn() for offsite gateways that don't receive separate IPNs
377
+	 */
378
+	public function finalize_payment_for($transaction, $update_txn = true)
379
+	{
380
+		/** @var $transaction EE_Transaction */
381
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
382
+		$last_payment_method = $transaction->payment_method();
383
+		if ($last_payment_method instanceof EE_Payment_Method) {
384
+			$payment = $last_payment_method->type_obj()->finalize_payment_for($transaction);
385
+			$this->update_txn_based_on_payment($transaction, $payment, $update_txn);
386
+			return $payment;
387
+		} else {
388
+			return null;
389
+		}
390
+	}
391
+
392
+
393
+
394
+	/**
395
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
396
+	 *
397
+	 * @param EE_Payment_Method $payment_method
398
+	 * @param EE_Payment        $payment_to_refund
399
+	 * @param array             $refund_info
400
+	 * @return EE_Payment
401
+	 * @throws \EE_Error
402
+	 */
403
+	public function process_refund(
404
+		EE_Payment_Method $payment_method,
405
+		EE_Payment $payment_to_refund,
406
+		$refund_info = array()
407
+	) {
408
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj()->supports_sending_refunds()) {
409
+			$payment_method->type_obj()->process_refund($payment_to_refund, $refund_info);
410
+			$this->update_txn_based_on_payment($payment_to_refund->transaction(), $payment_to_refund);
411
+		}
412
+		return $payment_to_refund;
413
+	}
414
+
415
+
416
+
417
+	/**
418
+	 * This should be called each time there may have been an update to a
419
+	 * payment on a transaction (ie, we asked for a payment to process a
420
+	 * payment for a transaction, or we told a payment method about an IPN, or
421
+	 * we told a payment method to
422
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
423
+	 * process a refund. This should handle firing the correct hooks to
424
+	 * indicate
425
+	 * what exactly happened and updating the transaction appropriately). This
426
+	 * could be integrated directly into EE_Transaction upon save, but we want
427
+	 * this logic to be separate from 'normal' plain-jane saving and updating
428
+	 * of transactions and payments, and to be tied to payment processing.
429
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
430
+	 * of previous code to decide whether or not to save (because the payment passed into
431
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
432
+	 * in which case we only want that payment object for some temporary usage during this request,
433
+	 * but we don't want it to be saved).
434
+	 *
435
+	 * @param EE_Transaction|int $transaction
436
+	 * @param EE_Payment         $payment
437
+	 * @param boolean            $update_txn
438
+	 *                        whether or not to call
439
+	 *                        EE_Transaction_Processor::
440
+	 *                        update_transaction_and_registrations_after_checkout_or_payment()
441
+	 *                        (you can save 1 DB query if you know you're going
442
+	 *                        to save it later instead)
443
+	 * @param bool               $IPN
444
+	 *                        if processing IPNs or other similar payment
445
+	 *                        related activities that occur in alternate
446
+	 *                        requests than the main one that is processing the
447
+	 *                        TXN, then set this to true to check whether the
448
+	 *                        TXN is locked before updating
449
+	 * @throws \EE_Error
450
+	 */
451
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
452
+	{
453
+		$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__not_successful';
454
+		/** @type EE_Transaction $transaction */
455
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
456
+		// can we freely update the TXN at this moment?
457
+		if ($IPN && $transaction->is_locked()) {
458
+			// don't update the transaction at this exact moment
459
+			// because the TXN is active in another request
460
+			EE_Cron_Tasks::schedule_update_transaction_with_payment(
461
+				time(),
462
+				$transaction->ID(),
463
+				$payment->ID()
464
+			);
465
+		} else {
466
+			// verify payment and that it has been saved
467
+			if ($payment instanceof EE_Payment && $payment->ID()) {
468
+				if (
469
+					$payment->payment_method() instanceof EE_Payment_Method
470
+					&& $payment->payment_method()->type_obj() instanceof EE_PMT_Base
471
+				) {
472
+					$payment->payment_method()->type_obj()->update_txn_based_on_payment($payment);
473
+					// update TXN registrations with payment info
474
+					$this->process_registration_payments($transaction, $payment);
475
+				}
476
+				$do_action = $payment->just_approved()
477
+					? 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__successful'
478
+					: $do_action;
479
+			} else {
480
+				// send out notifications
481
+				add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
482
+				$do_action = 'AHEE__EE_Payment_Processor__update_txn_based_on_payment__no_payment_made';
483
+			}
484
+			if ($payment instanceof EE_Payment && $payment->status() !== EEM_Payment::status_id_failed) {
485
+				/** @type EE_Transaction_Payments $transaction_payments */
486
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
487
+				// set new value for total paid
488
+				$transaction_payments->calculate_total_payments_and_update_status($transaction);
489
+				// call EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment() ???
490
+				if ($update_txn) {
491
+					$this->_post_payment_processing($transaction, $payment, $IPN);
492
+				}
493
+			}
494
+			// granular hook for others to use.
495
+			do_action($do_action, $transaction, $payment);
496
+			do_action('AHEE_log', __CLASS__, __FUNCTION__, $do_action, '$do_action');
497
+			//global hook for others to use.
498
+			do_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', $transaction, $payment);
499
+		}
500
+	}
501
+
502
+
503
+
504
+	/**
505
+	 * update registrations REG_paid field after successful payment and link registrations with payment
506
+	 *
507
+	 * @param EE_Transaction    $transaction
508
+	 * @param EE_Payment        $payment
509
+	 * @param EE_Registration[] $registrations
510
+	 * @throws \EE_Error
511
+	 */
512
+	public function process_registration_payments(
513
+		EE_Transaction $transaction,
514
+		EE_Payment $payment,
515
+		$registrations = array()
516
+	) {
517
+		// only process if payment was successful
518
+		if ($payment->status() !== EEM_Payment::status_id_approved) {
519
+			return;
520
+		}
521
+		//EEM_Registration::instance()->show_next_x_db_queries();
522
+		if (empty($registrations)) {
523
+			// find registrations with monies owing that can receive a payment
524
+			$registrations = $transaction->registrations(
525
+				array(
526
+					array(
527
+						// only these reg statuses can receive payments
528
+						'STS_ID'           => array('IN', EEM_Registration::reg_statuses_that_allow_payment()),
529
+						'REG_final_price'  => array('!=', 0),
530
+						'REG_final_price*' => array('!=', 'REG_paid', true),
531
+					),
532
+				)
533
+			);
534
+		}
535
+		// still nothing ??!??
536
+		if (empty($registrations)) {
537
+			return;
538
+		}
539
+		// todo: break out the following logic into a separate strategy class
540
+		// todo: named something like "Sequential_Reg_Payment_Strategy"
541
+		// todo: which would apply payments using the capitalist "first come first paid" approach
542
+		// todo: then have another strategy class like "Distributed_Reg_Payment_Strategy"
543
+		// todo: which would be the socialist "everybody gets a piece of pie" approach,
544
+		// todo: which would be better for deposits, where you want a bit of the payment applied to each registration
545
+		$refund = $payment->is_a_refund();
546
+		// how much is available to apply to registrations?
547
+		$available_payment_amount = abs($payment->amount());
548
+		foreach ($registrations as $registration) {
549
+			if ($registration instanceof EE_Registration) {
550
+				// nothing left?
551
+				if ($available_payment_amount <= 0) {
552
+					break;
553
+				}
554
+				if ($refund) {
555
+					$available_payment_amount = $this->process_registration_refund($registration, $payment, $available_payment_amount);
556
+				} else {
557
+					$available_payment_amount = $this->process_registration_payment($registration, $payment, $available_payment_amount);
558
+				}
559
+			}
560
+		}
561
+		if ($available_payment_amount > 0 && apply_filters('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', false)) {
562
+			EE_Error::add_attention(
563
+				sprintf(
564
+					__('A remainder of %1$s exists after applying this payment to Registration(s) %2$s.%3$sPlease verify that the original payment amount of %4$s is correct. If so, you should edit this payment and select at least one additional registration in the "Registrations to Apply Payment to" section, so that the remainder of this payment can be applied to the additional registration(s).',
565
+						'event_espresso'),
566
+					EEH_Template::format_currency($available_payment_amount),
567
+					implode(', ', array_keys($registrations)),
568
+					'<br/>',
569
+					EEH_Template::format_currency($payment->amount())
570
+				),
571
+				__FILE__, __FUNCTION__, __LINE__
572
+			);
573
+		}
574
+	}
575
+
576
+
577
+
578
+	/**
579
+	 * update registration REG_paid field after successful payment and link registration with payment
580
+	 *
581
+	 * @param EE_Registration $registration
582
+	 * @param EE_Payment      $payment
583
+	 * @param float           $available_payment_amount
584
+	 * @return float
585
+	 * @throws \EE_Error
586
+	 */
587
+	public function process_registration_payment(
588
+		EE_Registration $registration,
589
+		EE_Payment $payment,
590
+		$available_payment_amount = 0.00
591
+	) {
592
+		$owing = $registration->final_price() - $registration->paid();
593
+		if ($owing > 0) {
594
+			// don't allow payment amount to exceed the available payment amount, OR the amount owing
595
+			$payment_amount = min($available_payment_amount, $owing);
596
+			// update $available_payment_amount
597
+			$available_payment_amount -= $payment_amount;
598
+			//calculate and set new REG_paid
599
+			$registration->set_paid($registration->paid() + $payment_amount);
600
+			// now save it
601
+			$this->_apply_registration_payment($registration, $payment, $payment_amount);
602
+		}
603
+		return $available_payment_amount;
604
+	}
605
+
606
+
607
+
608
+	/**
609
+	 * update registration REG_paid field after successful payment and link registration with payment
610
+	 *
611
+	 * @param EE_Registration $registration
612
+	 * @param EE_Payment      $payment
613
+	 * @param float           $payment_amount
614
+	 * @return void
615
+	 * @throws \EE_Error
616
+	 */
617
+	protected function _apply_registration_payment(
618
+		EE_Registration $registration,
619
+		EE_Payment $payment,
620
+		$payment_amount = 0.00
621
+	) {
622
+		// find any existing reg payment records for this registration and payment
623
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
624
+			array(array('REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()))
625
+		);
626
+		// if existing registration payment exists
627
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
628
+			// then update that record
629
+			$existing_reg_payment->set_amount($payment_amount);
630
+			$existing_reg_payment->save();
631
+		} else {
632
+			// or add new relation between registration and payment and set amount
633
+			$registration->_add_relation_to($payment, 'Payment', array('RPY_amount' => $payment_amount));
634
+			// make it stick
635
+			$registration->save();
636
+		}
637
+	}
638
+
639
+
640
+
641
+	/**
642
+	 * update registration REG_paid field after refund and link registration with payment
643
+	 *
644
+	 * @param EE_Registration $registration
645
+	 * @param EE_Payment      $payment
646
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
647
+	 * @return float
648
+	 * @throws \EE_Error
649
+	 */
650
+	public function process_registration_refund(
651
+		EE_Registration $registration,
652
+		EE_Payment $payment,
653
+		$available_refund_amount = 0.00
654
+	) {
655
+		//EEH_Debug_Tools::printr( $payment->amount(), '$payment->amount()', __FILE__, __LINE__ );
656
+		if ($registration->paid() > 0) {
657
+			// ensure $available_refund_amount is NOT negative
658
+			$available_refund_amount = (float)abs($available_refund_amount);
659
+			// don't allow refund amount to exceed the available payment amount, OR the amount paid
660
+			$refund_amount = min($available_refund_amount, (float)$registration->paid());
661
+			// update $available_payment_amount
662
+			$available_refund_amount -= $refund_amount;
663
+			//calculate and set new REG_paid
664
+			$registration->set_paid($registration->paid() - $refund_amount);
665
+			// convert payment amount back to a negative value for storage in the db
666
+			$refund_amount = (float)abs($refund_amount) * -1;
667
+			// now save it
668
+			$this->_apply_registration_payment($registration, $payment, $refund_amount);
669
+		}
670
+		return $available_refund_amount;
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * Process payments and transaction after payment process completed.
677
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
678
+	 * if this request happens to be processing an IPN,
679
+	 * then we will also set the Payment Options Reg Step to completed,
680
+	 * and attempt to completely finalize the TXN if all of the other Reg Steps are completed as well.
681
+	 *
682
+	 * @param EE_Transaction $transaction
683
+	 * @param EE_Payment     $payment
684
+	 * @param bool           $IPN
685
+	 * @throws \EE_Error
686
+	 */
687
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
688
+	{
689
+		/** @type EE_Transaction_Processor $transaction_processor */
690
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
691
+		// is the Payment Options Reg Step completed ?
692
+		$payment_options_step_completed = $transaction->reg_step_completed('payment_options');
693
+		// if the Payment Options Reg Step is completed...
694
+		$revisit = $payment_options_step_completed === true ? true : false;
695
+		// then this is kinda sorta a revisit with regards to payments at least
696
+		$transaction_processor->set_revisit($revisit);
697
+		// if this is an IPN, let's consider the Payment Options Reg Step completed if not already
698
+		if (
699
+			$IPN
700
+			&& $payment_options_step_completed !== true
701
+			&& ($payment->is_approved() || $payment->is_pending())
702
+		) {
703
+			$payment_options_step_completed = $transaction->set_reg_step_completed(
704
+				'payment_options'
705
+			);
706
+		}
707
+		// maybe update status, but don't save transaction just yet
708
+		$transaction->update_status_based_on_total_paid(false);
709
+		// check if 'finalize_registration' step has been completed...
710
+		$finalized = $transaction->reg_step_completed('finalize_registration');
711
+		//  if this is an IPN and the final step has not been initiated
712
+		if ($IPN && $payment_options_step_completed && $finalized === false) {
713
+			// and if it hasn't already been set as being started...
714
+			$finalized = $transaction->set_reg_step_initiated('finalize_registration');
715
+		}
716
+		$transaction->save();
717
+		// because the above will return false if the final step was not fully completed, we need to check again...
718
+		if ($IPN && $finalized !== false) {
719
+			// and if we are all good to go, then send out notifications
720
+			add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
721
+			//ok, now process the transaction according to the payment
722
+			$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($transaction, $payment);
723
+		}
724
+		// DEBUG LOG
725
+		$payment_method = $payment->payment_method();
726
+		if ($payment_method instanceof EE_Payment_Method) {
727
+			$payment_method_type_obj = $payment_method->type_obj();
728
+			if ($payment_method_type_obj instanceof EE_PMT_Base) {
729
+				$gateway = $payment_method_type_obj->get_gateway();
730
+				if ($gateway instanceof EE_Gateway) {
731
+					$gateway->log(
732
+						array(
733
+							'message'               => __('Post Payment Transaction Details', 'event_espresso'),
734
+							'transaction'           => $transaction->model_field_array(),
735
+							'finalized'             => $finalized,
736
+							'IPN'                   => $IPN,
737
+							'deliver_notifications' => has_filter(
738
+								'FHEE__EED_Messages___maybe_registration__deliver_notifications'
739
+							),
740
+						),
741
+						$payment
742
+					);
743
+				}
744
+			}
745
+		}
746
+	}
747
+
748
+
749
+
750
+	/**
751
+	 * Force posts to PayPal to use TLS v1.2. See:
752
+	 * https://core.trac.wordpress.org/ticket/36320
753
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
754
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
755
+	 * This will affect paypal standard, pro, express, and payflow.
756
+	 */
757
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
758
+	{
759
+		if (strstr($url, 'https://') && strstr($url, '.paypal.com')) {
760
+			//Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
761
+			//instead of the constant because it might not be defined
762
+			curl_setopt($handle, CURLOPT_SSLVERSION, 1);
763
+		}
764
+	}
765 765
 }
Please login to merge, or discard this patch.
core/middleware/EE_Recommended_Versions.core.php 2 patches
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.
Indentation   +139 added lines, -139 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,150 +18,150 @@  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 recommended PHP version
43
-        if ( ! $this->_minimum_php_version_recommended()) {
44
-            $this->_display_minimum_recommended_php_version_notice();
45
-        }
46
-        $this->_response = $this->process_request_stack($this->_request, $this->_response);
47
-        //$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
48
-        return $this->_response;
49
-    }
50
-
51
-
52
-    /**
53
-     * Helper method to assess installed wp version against given values.
54
-     * By default this compares the required minimum version of WP for EE against the installed version of WP
55
-     *
56
-     * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked against)
57
-     * so consider that when sending in your values.
58
-     *
59
-     * @param string $version_to_check
60
-     * @param string $operator
61
-     * @return bool
62
-     */
63
-    public static function check_wp_version($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
64
-    {
65
-        global $wp_version;
66
-        return version_compare(
67
-            //first account for wp_version being pre-release (like RC, beta etc which are usually in the format like
68
-            //4.7-RC3-39519
69
-            strpos($wp_version, '-') > 0 ? substr($wp_version, 0, strpos($wp_version, '-')) : $wp_version,
70
-            $version_to_check,
71
-            $operator
72
-        );
73
-    }
74
-
75
-
76
-
77
-    /**
78
-     *    _minimum_wp_version_required
79
-     *
80
-     * @access private
81
-     * @return boolean
82
-     */
83
-    private function _minimum_wp_version_required()
84
-    {
85
-        return self::check_wp_version();
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     *    _check_php_version
92
-     *
93
-     * @access private
94
-     * @param string $min_version
95
-     * @return boolean
96
-     */
97
-    private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
98
-    {
99
-        return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     *    _minimum_php_version_recommended
106
-     *
107
-     * @access private
108
-     * @return boolean
109
-     */
110
-    private function _minimum_php_version_recommended()
111
-    {
112
-        return $this->_check_php_version(EE_MIN_PHP_VER_RECOMMENDED);
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     *    minimum_wp_version_error
119
-     *
120
-     * @return void
121
-     */
122
-    public function minimum_wp_version_error()
123
-    {
124
-        global $wp_version;
125
-        ?>
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 recommended PHP version
43
+		if ( ! $this->_minimum_php_version_recommended()) {
44
+			$this->_display_minimum_recommended_php_version_notice();
45
+		}
46
+		$this->_response = $this->process_request_stack($this->_request, $this->_response);
47
+		//$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
48
+		return $this->_response;
49
+	}
50
+
51
+
52
+	/**
53
+	 * Helper method to assess installed wp version against given values.
54
+	 * By default this compares the required minimum version of WP for EE against the installed version of WP
55
+	 *
56
+	 * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked against)
57
+	 * so consider that when sending in your values.
58
+	 *
59
+	 * @param string $version_to_check
60
+	 * @param string $operator
61
+	 * @return bool
62
+	 */
63
+	public static function check_wp_version($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
64
+	{
65
+		global $wp_version;
66
+		return version_compare(
67
+			//first account for wp_version being pre-release (like RC, beta etc which are usually in the format like
68
+			//4.7-RC3-39519
69
+			strpos($wp_version, '-') > 0 ? substr($wp_version, 0, strpos($wp_version, '-')) : $wp_version,
70
+			$version_to_check,
71
+			$operator
72
+		);
73
+	}
74
+
75
+
76
+
77
+	/**
78
+	 *    _minimum_wp_version_required
79
+	 *
80
+	 * @access private
81
+	 * @return boolean
82
+	 */
83
+	private function _minimum_wp_version_required()
84
+	{
85
+		return self::check_wp_version();
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 *    _check_php_version
92
+	 *
93
+	 * @access private
94
+	 * @param string $min_version
95
+	 * @return boolean
96
+	 */
97
+	private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
98
+	{
99
+		return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 *    _minimum_php_version_recommended
106
+	 *
107
+	 * @access private
108
+	 * @return boolean
109
+	 */
110
+	private function _minimum_php_version_recommended()
111
+	{
112
+		return $this->_check_php_version(EE_MIN_PHP_VER_RECOMMENDED);
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 *    minimum_wp_version_error
119
+	 *
120
+	 * @return void
121
+	 */
122
+	public function minimum_wp_version_error()
123
+	{
124
+		global $wp_version;
125
+		?>
126 126
         <div class="error">
127 127
             <p>
128 128
                 <?php
129
-                printf(
130
-                        __('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.',
131
-                                'event_espresso'),
132
-                        EE_MIN_WP_VER_REQUIRED,
133
-                        $wp_version,
134
-                        '<br/>',
135
-                        '<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
136
-                );
137
-                ?>
129
+				printf(
130
+						__('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.',
131
+								'event_espresso'),
132
+						EE_MIN_WP_VER_REQUIRED,
133
+						$wp_version,
134
+						'<br/>',
135
+						'<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
136
+				);
137
+				?>
138 138
             </p>
139 139
         </div>
140 140
         <?php
141
-    }
142
-
143
-
144
-
145
-    /**
146
-     *    _display_minimum_recommended_php_version_notice
147
-     *
148
-     * @access private
149
-     * @return void
150
-     */
151
-    private function _display_minimum_recommended_php_version_notice()
152
-    {
153
-        EE_Error::add_persistent_admin_notice(
154
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
155
-                sprintf(
156
-                        __('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.',
157
-                                'event_espresso'),
158
-                        EE_MIN_PHP_VER_RECOMMENDED,
159
-                        PHP_VERSION,
160
-                        '<br/>',
161
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
162
-                )
163
-        );
164
-    }
141
+	}
142
+
143
+
144
+
145
+	/**
146
+	 *    _display_minimum_recommended_php_version_notice
147
+	 *
148
+	 * @access private
149
+	 * @return void
150
+	 */
151
+	private function _display_minimum_recommended_php_version_notice()
152
+	{
153
+		EE_Error::add_persistent_admin_notice(
154
+				'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
155
+				sprintf(
156
+						__('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.',
157
+								'event_espresso'),
158
+						EE_MIN_PHP_VER_RECOMMENDED,
159
+						PHP_VERSION,
160
+						'<br/>',
161
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
162
+				)
163
+		);
164
+	}
165 165
 
166 166
 
167 167
 }
Please login to merge, or discard this patch.
admin_pages/messages/templates/ee_msg_messages_help_tab.template.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,3 +1,3 @@
 block discarded – undo
1 1
 <h2><?php esc_html_e('What is the Event Espresso Messages System?', 'event_espresso'); ?></h2>
2
-<p><?php printf( esc_html__('The Event Espresso Messages system is a powerful framework that Event Espresso uses to prepare %1$smessages%2$s for different types of use (message types) and delivered by different %1$smessengers%2$s.', 'event_espresso'), '<strong>', '</strong>' ); ?></p>
2
+<p><?php printf(esc_html__('The Event Espresso Messages system is a powerful framework that Event Espresso uses to prepare %1$smessages%2$s for different types of use (message types) and delivered by different %1$smessengers%2$s.', 'event_espresso'), '<strong>', '</strong>'); ?></p>
3 3
 <p><?php esc_html_e('We\'ve intentionally created this framework so that we have as much flexibility as possible for future ideas that we think of (or customers think of) for the kinds of messages that get sent out related to your events.', 'event_espresso'); ?></p>
4 4
\ No newline at end of file
Please login to merge, or discard this patch.