Completed
Branch FET/editor-dates-tickets-refac... (c72528)
by
unknown
46:50 queued 36:04
created
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.
Indentation   +392 added lines, -392 removed lines patch added patch discarded remove patch
@@ -17,396 +17,396 @@
 block discarded – undo
17 17
 class EE_Cart implements ResettableInterface
18 18
 {
19 19
 
20
-    /**
21
-     * instance of the EE_Cart object
22
-     *
23
-     * @access    private
24
-     * @var EE_Cart $_instance
25
-     */
26
-    private static $_instance;
27
-
28
-    /**
29
-     * instance of the EE_Session object
30
-     *
31
-     * @access    protected
32
-     * @var EE_Session $_session
33
-     */
34
-    protected $_session;
35
-
36
-    /**
37
-     * The total Line item which comprises all the children line-item subtotals,
38
-     * which in turn each have their line items.
39
-     * Typically, the line item structure will look like:
40
-     * grand total
41
-     * -tickets-sub-total
42
-     * --ticket1
43
-     * --ticket2
44
-     * --...
45
-     * -taxes-sub-total
46
-     * --tax1
47
-     * --tax2
48
-     *
49
-     * @var EE_Line_Item
50
-     */
51
-    private $_grand_total;
52
-
53
-
54
-    /**
55
-     * @singleton method used to instantiate class object
56
-     * @access    public
57
-     * @param EE_Line_Item $grand_total
58
-     * @param EE_Session   $session
59
-     * @return \EE_Cart
60
-     * @throws \EE_Error
61
-     */
62
-    public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
63
-    {
64
-        if ($grand_total instanceof EE_Line_Item && $grand_total->is_total()) {
65
-            self::$_instance = new self($grand_total, $session);
66
-        }
67
-        // or maybe retrieve an existing one ?
68
-        if (! self::$_instance instanceof EE_Cart) {
69
-            // try getting the cart out of the session
70
-            $saved_cart = $session instanceof EE_Session ? $session->cart() : null;
71
-            self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
72
-            unset($saved_cart);
73
-        }
74
-        // verify that cart is ok and grand total line item exists
75
-        if (! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
76
-            self::$_instance = new self($grand_total, $session);
77
-        }
78
-        self::$_instance->get_grand_total();
79
-        // once everything is all said and done, save the cart to the EE_Session
80
-        add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
81
-        return self::$_instance;
82
-    }
83
-
84
-
85
-    /**
86
-     * private constructor to prevent direct creation
87
-     *
88
-     * @Constructor
89
-     * @access private
90
-     * @param EE_Line_Item $grand_total
91
-     * @param EE_Session   $session
92
-     */
93
-    private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
94
-    {
95
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
96
-        $this->set_session($session);
97
-        if ($grand_total instanceof EE_Line_Item && $grand_total->is_total()) {
98
-            $this->set_grand_total_line_item($grand_total);
99
-        }
100
-    }
101
-
102
-
103
-    /**
104
-     * Resets the cart completely (whereas empty_cart
105
-     *
106
-     * @param EE_Line_Item $grand_total
107
-     * @param EE_Session   $session
108
-     * @return EE_Cart
109
-     * @throws \EE_Error
110
-     */
111
-    public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
112
-    {
113
-        remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
114
-        if ($session instanceof EE_Session) {
115
-            $session->reset_cart();
116
-        }
117
-        self::$_instance = null;
118
-        return self::instance($grand_total, $session);
119
-    }
120
-
121
-
122
-    /**
123
-     * @return \EE_Session
124
-     */
125
-    public function session()
126
-    {
127
-        if (! $this->_session instanceof EE_Session) {
128
-            $this->set_session();
129
-        }
130
-        return $this->_session;
131
-    }
132
-
133
-
134
-    /**
135
-     * @param EE_Session $session
136
-     */
137
-    public function set_session(EE_Session $session = null)
138
-    {
139
-        $this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
140
-    }
141
-
142
-
143
-    /**
144
-     * Sets the cart to match the line item. Especially handy for loading an old cart where you
145
-     *  know the grand total line item on it
146
-     *
147
-     * @param EE_Line_Item $line_item
148
-     */
149
-    public function set_grand_total_line_item(EE_Line_Item $line_item)
150
-    {
151
-        $this->_grand_total = $line_item;
152
-    }
153
-
154
-
155
-    /**
156
-     * get_cart_from_reg_url_link
157
-     *
158
-     * @access public
159
-     * @param EE_Transaction $transaction
160
-     * @param EE_Session     $session
161
-     * @return \EE_Cart
162
-     * @throws \EE_Error
163
-     */
164
-    public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
165
-    {
166
-        $grand_total = $transaction->total_line_item();
167
-        $grand_total->get_items();
168
-        $grand_total->tax_descendants();
169
-        return EE_Cart::instance($grand_total, $session);
170
-    }
171
-
172
-
173
-    /**
174
-     * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
175
-     *
176
-     * @return EE_Line_Item
177
-     * @throws \EE_Error
178
-     */
179
-    private function _create_grand_total()
180
-    {
181
-        $this->_grand_total = EEH_Line_Item::create_total_line_item();
182
-        return $this->_grand_total;
183
-    }
184
-
185
-
186
-    /**
187
-     * Gets all the line items of object type Ticket
188
-     *
189
-     * @access public
190
-     * @return \EE_Line_Item[]
191
-     */
192
-    public function get_tickets()
193
-    {
194
-        if ($this->_grand_total === null) {
195
-            return array();
196
-        }
197
-        return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
198
-    }
199
-
200
-
201
-    /**
202
-     * returns the total quantity of tickets in the cart
203
-     *
204
-     * @access public
205
-     * @return int
206
-     * @throws \EE_Error
207
-     */
208
-    public function all_ticket_quantity_count()
209
-    {
210
-        $tickets = $this->get_tickets();
211
-        if (empty($tickets)) {
212
-            return 0;
213
-        }
214
-        $count = 0;
215
-        foreach ($tickets as $ticket) {
216
-            $count += $ticket->get('LIN_quantity');
217
-        }
218
-        return $count;
219
-    }
220
-
221
-
222
-    /**
223
-     * Gets all the tax line items
224
-     *
225
-     * @return \EE_Line_Item[]
226
-     * @throws \EE_Error
227
-     */
228
-    public function get_taxes()
229
-    {
230
-        return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
231
-    }
232
-
233
-
234
-    /**
235
-     * Gets the total line item (which is a parent of all other line items) on this cart
236
-     *
237
-     * @return EE_Line_Item
238
-     * @throws \EE_Error
239
-     */
240
-    public function get_grand_total()
241
-    {
242
-        return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
243
-    }
244
-
245
-
246
-    /**
247
-     * @process items for adding to cart
248
-     * @access  public
249
-     * @param EE_Ticket $ticket
250
-     * @param int       $qty
251
-     * @return TRUE on success, FALSE on fail
252
-     * @throws \EE_Error
253
-     */
254
-    public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
255
-    {
256
-        EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
257
-        return $this->save_cart() ? true : false;
258
-    }
259
-
260
-
261
-    /**
262
-     * get_cart_total_before_tax
263
-     *
264
-     * @access public
265
-     * @return float
266
-     * @throws \EE_Error
267
-     */
268
-    public function get_cart_total_before_tax()
269
-    {
270
-        return $this->get_grand_total()->recalculate_pre_tax_total();
271
-    }
272
-
273
-
274
-    /**
275
-     * gets the total amount of tax paid for items in this cart
276
-     *
277
-     * @access public
278
-     * @return float
279
-     * @throws \EE_Error
280
-     */
281
-    public function get_applied_taxes()
282
-    {
283
-        return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
284
-    }
285
-
286
-
287
-    /**
288
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
289
-     *
290
-     * @access public
291
-     * @return float
292
-     * @throws \EE_Error
293
-     */
294
-    public function get_cart_grand_total()
295
-    {
296
-        EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
297
-        return $this->get_grand_total()->total();
298
-    }
299
-
300
-
301
-    /**
302
-     * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
303
-     *
304
-     * @access public
305
-     * @return float
306
-     * @throws \EE_Error
307
-     */
308
-    public function recalculate_all_cart_totals()
309
-    {
310
-        $pre_tax_total = $this->get_cart_total_before_tax();
311
-        $taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
312
-        $this->_grand_total->set_total($pre_tax_total + $taxes_total);
313
-        $this->_grand_total->save_this_and_descendants_to_txn();
314
-        return $this->get_grand_total()->total();
315
-    }
316
-
317
-
318
-    /**
319
-     * deletes an item from the cart
320
-     *
321
-     * @access public
322
-     * @param array|bool|string $line_item_codes
323
-     * @return int on success, FALSE on fail
324
-     * @throws \EE_Error
325
-     */
326
-    public function delete_items($line_item_codes = false)
327
-    {
328
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
329
-        return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
330
-    }
331
-
332
-
333
-    /**
334
-     * @remove ALL items from cart and zero ALL totals
335
-     * @access public
336
-     * @return bool
337
-     * @throws \EE_Error
338
-     */
339
-    public function empty_cart()
340
-    {
341
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
342
-        $this->_grand_total = $this->_create_grand_total();
343
-        return $this->save_cart(true);
344
-    }
345
-
346
-
347
-    /**
348
-     * @remove ALL items from cart and delete total as well
349
-     * @access public
350
-     * @return bool
351
-     * @throws \EE_Error
352
-     */
353
-    public function delete_cart()
354
-    {
355
-        if ($this->_grand_total instanceof EE_Line_Item) {
356
-            $deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
357
-            if ($deleted) {
358
-                $deleted += $this->_grand_total->delete();
359
-                $this->_grand_total = null;
360
-                return true;
361
-            }
362
-        }
363
-        return false;
364
-    }
365
-
366
-
367
-    /**
368
-     * @save   cart to session
369
-     * @access public
370
-     * @param bool $apply_taxes
371
-     * @return TRUE on success, FALSE on fail
372
-     * @throws \EE_Error
373
-     */
374
-    public function save_cart($apply_taxes = true)
375
-    {
376
-        if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
377
-            EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
378
-            // make sure we don't cache the transaction because it can get stale
379
-            if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
380
-                && $this->_grand_total->get_one_from_cache('Transaction')->ID()
381
-            ) {
382
-                $this->_grand_total->clear_cache('Transaction', null, true);
383
-            }
384
-        }
385
-        if ($this->session() instanceof EE_Session) {
386
-            return $this->session()->set_cart($this);
387
-        } else {
388
-            return false;
389
-        }
390
-    }
391
-
392
-
393
-    public function __wakeup()
394
-    {
395
-        if (! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
396
-            // $this->_grand_total is actually just an ID, so use it to get the object from the db
397
-            $this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
398
-        }
399
-    }
400
-
401
-
402
-    /**
403
-     * @return array
404
-     */
405
-    public function __sleep()
406
-    {
407
-        if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
408
-            $this->_grand_total = $this->_grand_total->ID();
409
-        }
410
-        return array('_grand_total');
411
-    }
20
+	/**
21
+	 * instance of the EE_Cart object
22
+	 *
23
+	 * @access    private
24
+	 * @var EE_Cart $_instance
25
+	 */
26
+	private static $_instance;
27
+
28
+	/**
29
+	 * instance of the EE_Session object
30
+	 *
31
+	 * @access    protected
32
+	 * @var EE_Session $_session
33
+	 */
34
+	protected $_session;
35
+
36
+	/**
37
+	 * The total Line item which comprises all the children line-item subtotals,
38
+	 * which in turn each have their line items.
39
+	 * Typically, the line item structure will look like:
40
+	 * grand total
41
+	 * -tickets-sub-total
42
+	 * --ticket1
43
+	 * --ticket2
44
+	 * --...
45
+	 * -taxes-sub-total
46
+	 * --tax1
47
+	 * --tax2
48
+	 *
49
+	 * @var EE_Line_Item
50
+	 */
51
+	private $_grand_total;
52
+
53
+
54
+	/**
55
+	 * @singleton method used to instantiate class object
56
+	 * @access    public
57
+	 * @param EE_Line_Item $grand_total
58
+	 * @param EE_Session   $session
59
+	 * @return \EE_Cart
60
+	 * @throws \EE_Error
61
+	 */
62
+	public static function instance(EE_Line_Item $grand_total = null, EE_Session $session = null)
63
+	{
64
+		if ($grand_total instanceof EE_Line_Item && $grand_total->is_total()) {
65
+			self::$_instance = new self($grand_total, $session);
66
+		}
67
+		// or maybe retrieve an existing one ?
68
+		if (! self::$_instance instanceof EE_Cart) {
69
+			// try getting the cart out of the session
70
+			$saved_cart = $session instanceof EE_Session ? $session->cart() : null;
71
+			self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
72
+			unset($saved_cart);
73
+		}
74
+		// verify that cart is ok and grand total line item exists
75
+		if (! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
76
+			self::$_instance = new self($grand_total, $session);
77
+		}
78
+		self::$_instance->get_grand_total();
79
+		// once everything is all said and done, save the cart to the EE_Session
80
+		add_action('shutdown', array(self::$_instance, 'save_cart'), 90);
81
+		return self::$_instance;
82
+	}
83
+
84
+
85
+	/**
86
+	 * private constructor to prevent direct creation
87
+	 *
88
+	 * @Constructor
89
+	 * @access private
90
+	 * @param EE_Line_Item $grand_total
91
+	 * @param EE_Session   $session
92
+	 */
93
+	private function __construct(EE_Line_Item $grand_total = null, EE_Session $session = null)
94
+	{
95
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
96
+		$this->set_session($session);
97
+		if ($grand_total instanceof EE_Line_Item && $grand_total->is_total()) {
98
+			$this->set_grand_total_line_item($grand_total);
99
+		}
100
+	}
101
+
102
+
103
+	/**
104
+	 * Resets the cart completely (whereas empty_cart
105
+	 *
106
+	 * @param EE_Line_Item $grand_total
107
+	 * @param EE_Session   $session
108
+	 * @return EE_Cart
109
+	 * @throws \EE_Error
110
+	 */
111
+	public static function reset(EE_Line_Item $grand_total = null, EE_Session $session = null)
112
+	{
113
+		remove_action('shutdown', array(self::$_instance, 'save_cart'), 90);
114
+		if ($session instanceof EE_Session) {
115
+			$session->reset_cart();
116
+		}
117
+		self::$_instance = null;
118
+		return self::instance($grand_total, $session);
119
+	}
120
+
121
+
122
+	/**
123
+	 * @return \EE_Session
124
+	 */
125
+	public function session()
126
+	{
127
+		if (! $this->_session instanceof EE_Session) {
128
+			$this->set_session();
129
+		}
130
+		return $this->_session;
131
+	}
132
+
133
+
134
+	/**
135
+	 * @param EE_Session $session
136
+	 */
137
+	public function set_session(EE_Session $session = null)
138
+	{
139
+		$this->_session = $session instanceof EE_Session ? $session : EE_Registry::instance()->load_core('Session');
140
+	}
141
+
142
+
143
+	/**
144
+	 * Sets the cart to match the line item. Especially handy for loading an old cart where you
145
+	 *  know the grand total line item on it
146
+	 *
147
+	 * @param EE_Line_Item $line_item
148
+	 */
149
+	public function set_grand_total_line_item(EE_Line_Item $line_item)
150
+	{
151
+		$this->_grand_total = $line_item;
152
+	}
153
+
154
+
155
+	/**
156
+	 * get_cart_from_reg_url_link
157
+	 *
158
+	 * @access public
159
+	 * @param EE_Transaction $transaction
160
+	 * @param EE_Session     $session
161
+	 * @return \EE_Cart
162
+	 * @throws \EE_Error
163
+	 */
164
+	public static function get_cart_from_txn(EE_Transaction $transaction, EE_Session $session = null)
165
+	{
166
+		$grand_total = $transaction->total_line_item();
167
+		$grand_total->get_items();
168
+		$grand_total->tax_descendants();
169
+		return EE_Cart::instance($grand_total, $session);
170
+	}
171
+
172
+
173
+	/**
174
+	 * Creates the total line item, and ensures it has its 'tickets' and 'taxes' sub-items
175
+	 *
176
+	 * @return EE_Line_Item
177
+	 * @throws \EE_Error
178
+	 */
179
+	private function _create_grand_total()
180
+	{
181
+		$this->_grand_total = EEH_Line_Item::create_total_line_item();
182
+		return $this->_grand_total;
183
+	}
184
+
185
+
186
+	/**
187
+	 * Gets all the line items of object type Ticket
188
+	 *
189
+	 * @access public
190
+	 * @return \EE_Line_Item[]
191
+	 */
192
+	public function get_tickets()
193
+	{
194
+		if ($this->_grand_total === null) {
195
+			return array();
196
+		}
197
+		return EEH_Line_Item::get_ticket_line_items($this->_grand_total);
198
+	}
199
+
200
+
201
+	/**
202
+	 * returns the total quantity of tickets in the cart
203
+	 *
204
+	 * @access public
205
+	 * @return int
206
+	 * @throws \EE_Error
207
+	 */
208
+	public function all_ticket_quantity_count()
209
+	{
210
+		$tickets = $this->get_tickets();
211
+		if (empty($tickets)) {
212
+			return 0;
213
+		}
214
+		$count = 0;
215
+		foreach ($tickets as $ticket) {
216
+			$count += $ticket->get('LIN_quantity');
217
+		}
218
+		return $count;
219
+	}
220
+
221
+
222
+	/**
223
+	 * Gets all the tax line items
224
+	 *
225
+	 * @return \EE_Line_Item[]
226
+	 * @throws \EE_Error
227
+	 */
228
+	public function get_taxes()
229
+	{
230
+		return EEH_Line_Item::get_taxes_subtotal($this->_grand_total)->children();
231
+	}
232
+
233
+
234
+	/**
235
+	 * Gets the total line item (which is a parent of all other line items) on this cart
236
+	 *
237
+	 * @return EE_Line_Item
238
+	 * @throws \EE_Error
239
+	 */
240
+	public function get_grand_total()
241
+	{
242
+		return $this->_grand_total instanceof EE_Line_Item ? $this->_grand_total : $this->_create_grand_total();
243
+	}
244
+
245
+
246
+	/**
247
+	 * @process items for adding to cart
248
+	 * @access  public
249
+	 * @param EE_Ticket $ticket
250
+	 * @param int       $qty
251
+	 * @return TRUE on success, FALSE on fail
252
+	 * @throws \EE_Error
253
+	 */
254
+	public function add_ticket_to_cart(EE_Ticket $ticket, $qty = 1)
255
+	{
256
+		EEH_Line_Item::add_ticket_purchase($this->get_grand_total(), $ticket, $qty);
257
+		return $this->save_cart() ? true : false;
258
+	}
259
+
260
+
261
+	/**
262
+	 * get_cart_total_before_tax
263
+	 *
264
+	 * @access public
265
+	 * @return float
266
+	 * @throws \EE_Error
267
+	 */
268
+	public function get_cart_total_before_tax()
269
+	{
270
+		return $this->get_grand_total()->recalculate_pre_tax_total();
271
+	}
272
+
273
+
274
+	/**
275
+	 * gets the total amount of tax paid for items in this cart
276
+	 *
277
+	 * @access public
278
+	 * @return float
279
+	 * @throws \EE_Error
280
+	 */
281
+	public function get_applied_taxes()
282
+	{
283
+		return EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
284
+	}
285
+
286
+
287
+	/**
288
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
289
+	 *
290
+	 * @access public
291
+	 * @return float
292
+	 * @throws \EE_Error
293
+	 */
294
+	public function get_cart_grand_total()
295
+	{
296
+		EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
297
+		return $this->get_grand_total()->total();
298
+	}
299
+
300
+
301
+	/**
302
+	 * Gets the total amount to be paid for the items in the cart, including taxes and other modifiers
303
+	 *
304
+	 * @access public
305
+	 * @return float
306
+	 * @throws \EE_Error
307
+	 */
308
+	public function recalculate_all_cart_totals()
309
+	{
310
+		$pre_tax_total = $this->get_cart_total_before_tax();
311
+		$taxes_total = EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
312
+		$this->_grand_total->set_total($pre_tax_total + $taxes_total);
313
+		$this->_grand_total->save_this_and_descendants_to_txn();
314
+		return $this->get_grand_total()->total();
315
+	}
316
+
317
+
318
+	/**
319
+	 * deletes an item from the cart
320
+	 *
321
+	 * @access public
322
+	 * @param array|bool|string $line_item_codes
323
+	 * @return int on success, FALSE on fail
324
+	 * @throws \EE_Error
325
+	 */
326
+	public function delete_items($line_item_codes = false)
327
+	{
328
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
329
+		return EEH_Line_Item::delete_items($this->get_grand_total(), $line_item_codes);
330
+	}
331
+
332
+
333
+	/**
334
+	 * @remove ALL items from cart and zero ALL totals
335
+	 * @access public
336
+	 * @return bool
337
+	 * @throws \EE_Error
338
+	 */
339
+	public function empty_cart()
340
+	{
341
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
342
+		$this->_grand_total = $this->_create_grand_total();
343
+		return $this->save_cart(true);
344
+	}
345
+
346
+
347
+	/**
348
+	 * @remove ALL items from cart and delete total as well
349
+	 * @access public
350
+	 * @return bool
351
+	 * @throws \EE_Error
352
+	 */
353
+	public function delete_cart()
354
+	{
355
+		if ($this->_grand_total instanceof EE_Line_Item) {
356
+			$deleted = EEH_Line_Item::delete_all_child_items($this->_grand_total);
357
+			if ($deleted) {
358
+				$deleted += $this->_grand_total->delete();
359
+				$this->_grand_total = null;
360
+				return true;
361
+			}
362
+		}
363
+		return false;
364
+	}
365
+
366
+
367
+	/**
368
+	 * @save   cart to session
369
+	 * @access public
370
+	 * @param bool $apply_taxes
371
+	 * @return TRUE on success, FALSE on fail
372
+	 * @throws \EE_Error
373
+	 */
374
+	public function save_cart($apply_taxes = true)
375
+	{
376
+		if ($apply_taxes && $this->_grand_total instanceof EE_Line_Item) {
377
+			EEH_Line_Item::ensure_taxes_applied($this->_grand_total);
378
+			// make sure we don't cache the transaction because it can get stale
379
+			if ($this->_grand_total->get_one_from_cache('Transaction') instanceof EE_Transaction
380
+				&& $this->_grand_total->get_one_from_cache('Transaction')->ID()
381
+			) {
382
+				$this->_grand_total->clear_cache('Transaction', null, true);
383
+			}
384
+		}
385
+		if ($this->session() instanceof EE_Session) {
386
+			return $this->session()->set_cart($this);
387
+		} else {
388
+			return false;
389
+		}
390
+	}
391
+
392
+
393
+	public function __wakeup()
394
+	{
395
+		if (! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
396
+			// $this->_grand_total is actually just an ID, so use it to get the object from the db
397
+			$this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
398
+		}
399
+	}
400
+
401
+
402
+	/**
403
+	 * @return array
404
+	 */
405
+	public function __sleep()
406
+	{
407
+		if ($this->_grand_total instanceof EE_Line_Item && $this->_grand_total->ID()) {
408
+			$this->_grand_total = $this->_grand_total->ID();
409
+		}
410
+		return array('_grand_total');
411
+	}
412 412
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -65,14 +65,14 @@  discard block
 block discarded – undo
65 65
             self::$_instance = new self($grand_total, $session);
66 66
         }
67 67
         // or maybe retrieve an existing one ?
68
-        if (! self::$_instance instanceof EE_Cart) {
68
+        if ( ! self::$_instance instanceof EE_Cart) {
69 69
             // try getting the cart out of the session
70 70
             $saved_cart = $session instanceof EE_Session ? $session->cart() : null;
71 71
             self::$_instance = $saved_cart instanceof EE_Cart ? $saved_cart : new self($grand_total, $session);
72 72
             unset($saved_cart);
73 73
         }
74 74
         // verify that cart is ok and grand total line item exists
75
-        if (! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
75
+        if ( ! self::$_instance instanceof EE_Cart || ! self::$_instance->_grand_total instanceof EE_Line_Item) {
76 76
             self::$_instance = new self($grand_total, $session);
77 77
         }
78 78
         self::$_instance->get_grand_total();
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
      */
125 125
     public function session()
126 126
     {
127
-        if (! $this->_session instanceof EE_Session) {
127
+        if ( ! $this->_session instanceof EE_Session) {
128 128
             $this->set_session();
129 129
         }
130 130
         return $this->_session;
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
 
393 393
     public function __wakeup()
394 394
     {
395
-        if (! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
395
+        if ( ! $this->_grand_total instanceof EE_Line_Item && absint($this->_grand_total) !== 0) {
396 396
             // $this->_grand_total is actually just an ID, so use it to get the object from the db
397 397
             $this->_grand_total = EEM_Line_Item::instance()->get_one_by_ID($this->_grand_total);
398 398
         }
Please login to merge, or discard this patch.
core/helpers/EEH_Activation.helper.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
      *
614 614
      * @since  4.6.0
615 615
      * @global WPDB $wpdb
616
-     * @return mixed null|int WP_user ID or NULL
616
+     * @return integer|null null|int WP_user ID or NULL
617 617
      */
618 618
     public static function get_default_creator_id()
619 619
     {
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
      * @static
775 775
      * @deprecated instead use TableManager::dropTable()
776 776
      * @param string $table_name
777
-     * @return bool | int
777
+     * @return integer | int
778 778
      */
779 779
     public static function delete_unused_db_table($table_name)
780 780
     {
@@ -791,7 +791,7 @@  discard block
 block discarded – undo
791 791
      * @deprecated instead use TableManager::dropIndex()
792 792
      * @param string $table_name
793 793
      * @param string $index_name
794
-     * @return bool | int
794
+     * @return integer | int
795 795
      */
796 796
     public static function drop_index($table_name, $index_name)
797 797
     {
Please login to merge, or discard this patch.
Indentation   +1576 added lines, -1576 removed lines patch added patch discarded remove patch
@@ -15,232 +15,232 @@  discard block
 block discarded – undo
15 15
 class EEH_Activation implements ResettableInterface
16 16
 {
17 17
 
18
-    /**
19
-     * constant used to indicate a cron task is no longer in use
20
-     */
21
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
22
-
23
-    /**
24
-     * WP_User->ID
25
-     *
26
-     * @var int
27
-     */
28
-    private static $_default_creator_id;
29
-
30
-    /**
31
-     * indicates whether or not we've already verified core's default data during this request,
32
-     * because after migrations are done, any addons activated while in maintenance mode
33
-     * will want to setup their own default data, and they might hook into core's default data
34
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
35
-     * This prevents doing that for EVERY single addon.
36
-     *
37
-     * @var boolean
38
-     */
39
-    protected static $_initialized_db_content_already_in_this_request = false;
40
-
41
-    /**
42
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
43
-     */
44
-    private static $table_analysis;
45
-
46
-    /**
47
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
48
-     */
49
-    private static $table_manager;
50
-
51
-
52
-    /**
53
-     * @return \EventEspresso\core\services\database\TableAnalysis
54
-     */
55
-    public static function getTableAnalysis()
56
-    {
57
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
58
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
59
-        }
60
-        return self::$table_analysis;
61
-    }
62
-
63
-
64
-    /**
65
-     * @return \EventEspresso\core\services\database\TableManager
66
-     */
67
-    public static function getTableManager()
68
-    {
69
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
70
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
71
-        }
72
-        return self::$table_manager;
73
-    }
74
-
75
-
76
-    /**
77
-     *    _ensure_table_name_has_prefix
78
-     *
79
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
80
-     * @access     public
81
-     * @static
82
-     * @param $table_name
83
-     * @return string
84
-     */
85
-    public static function ensure_table_name_has_prefix($table_name)
86
-    {
87
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88
-    }
89
-
90
-
91
-    /**
92
-     *    system_initialization
93
-     *    ensures the EE configuration settings are loaded with at least default options set
94
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
95
-     *
96
-     * @access public
97
-     * @static
98
-     * @return void
99
-     */
100
-    public static function system_initialization()
101
-    {
102
-        EEH_Activation::reset_and_update_config();
103
-        // which is fired BEFORE activation of plugin anyways
104
-        EEH_Activation::verify_default_pages_exist();
105
-    }
106
-
107
-
108
-    /**
109
-     * Sets the database schema and creates folders. This should
110
-     * be called on plugin activation and reactivation
111
-     *
112
-     * @return boolean success, whether the database and folders are setup properly
113
-     * @throws \EE_Error
114
-     */
115
-    public static function initialize_db_and_folders()
116
-    {
117
-        return EEH_Activation::create_database_tables();
118
-    }
119
-
120
-
121
-    /**
122
-     * assuming we have an up-to-date database schema, this will populate it
123
-     * with default and initial data. This should be called
124
-     * upon activation of a new plugin, reactivation, and at the end
125
-     * of running migration scripts
126
-     *
127
-     * @throws \EE_Error
128
-     */
129
-    public static function initialize_db_content()
130
-    {
131
-        // let's avoid doing all this logic repeatedly, especially when addons are requesting it
132
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
133
-            return;
134
-        }
135
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
136
-
137
-        EEH_Activation::initialize_system_questions();
138
-        EEH_Activation::insert_default_status_codes();
139
-        EEH_Activation::generate_default_message_templates();
140
-        EEH_Activation::create_no_ticket_prices_array();
141
-
142
-        EEH_Activation::validate_messages_system();
143
-        EEH_Activation::insert_default_payment_methods();
144
-        // in case we've
145
-        EEH_Activation::remove_cron_tasks();
146
-        EEH_Activation::create_cron_tasks();
147
-        // remove all TXN locks since that is being done via extra meta now
148
-        delete_option('ee_locked_transactions');
149
-        // also, check for CAF default db content
150
-        do_action('AHEE__EEH_Activation__initialize_db_content');
151
-        // also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
152
-        // which users really won't care about on initial activation
153
-        EE_Error::overwrite_success();
154
-    }
155
-
156
-
157
-    /**
158
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
159
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
160
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
161
-     * (null)
162
-     *
163
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
164
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
165
-     * @return array
166
-     * @throws \EE_Error
167
-     */
168
-    public static function get_cron_tasks($which_to_include)
169
-    {
170
-        $cron_tasks = apply_filters(
171
-            'FHEE__EEH_Activation__get_cron_tasks',
172
-            array(
173
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
174
-            //              'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
175
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
176
-                // 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
177
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
178
-            )
179
-        );
180
-        if ($which_to_include === 'old') {
181
-            $cron_tasks = array_filter(
182
-                $cron_tasks,
183
-                function ($value) {
184
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
185
-                }
186
-            );
187
-        } elseif ($which_to_include === 'current') {
188
-            $cron_tasks = array_filter($cron_tasks);
189
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
190
-            throw new EE_Error(
191
-                sprintf(
192
-                    __(
193
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
194
-                        'event_espresso'
195
-                    ),
196
-                    $which_to_include
197
-                )
198
-            );
199
-        }
200
-        return $cron_tasks;
201
-    }
202
-
203
-
204
-    /**
205
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
206
-     *
207
-     * @throws \EE_Error
208
-     */
209
-    public static function create_cron_tasks()
210
-    {
211
-
212
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
213
-            if (! wp_next_scheduled($hook_name)) {
214
-                /**
215
-                 * This allows client code to define the initial start timestamp for this schedule.
216
-                 */
217
-                if (is_array($frequency)
218
-                    && count($frequency) === 2
219
-                    && isset($frequency[0], $frequency[1])
220
-                ) {
221
-                    $start_timestamp = $frequency[0];
222
-                    $frequency = $frequency[1];
223
-                } else {
224
-                    $start_timestamp = time();
225
-                }
226
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
227
-            }
228
-        }
229
-    }
230
-
231
-
232
-    /**
233
-     * Remove the currently-existing and now-removed cron tasks.
234
-     *
235
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
236
-     * @throws \EE_Error
237
-     */
238
-    public static function remove_cron_tasks($remove_all = true)
239
-    {
240
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
241
-        $crons                = _get_cron_array();
242
-        $crons                = is_array($crons) ? $crons : array();
243
-        /* reminder of what $crons look like:
18
+	/**
19
+	 * constant used to indicate a cron task is no longer in use
20
+	 */
21
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
22
+
23
+	/**
24
+	 * WP_User->ID
25
+	 *
26
+	 * @var int
27
+	 */
28
+	private static $_default_creator_id;
29
+
30
+	/**
31
+	 * indicates whether or not we've already verified core's default data during this request,
32
+	 * because after migrations are done, any addons activated while in maintenance mode
33
+	 * will want to setup their own default data, and they might hook into core's default data
34
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
35
+	 * This prevents doing that for EVERY single addon.
36
+	 *
37
+	 * @var boolean
38
+	 */
39
+	protected static $_initialized_db_content_already_in_this_request = false;
40
+
41
+	/**
42
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
43
+	 */
44
+	private static $table_analysis;
45
+
46
+	/**
47
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
48
+	 */
49
+	private static $table_manager;
50
+
51
+
52
+	/**
53
+	 * @return \EventEspresso\core\services\database\TableAnalysis
54
+	 */
55
+	public static function getTableAnalysis()
56
+	{
57
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
58
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
59
+		}
60
+		return self::$table_analysis;
61
+	}
62
+
63
+
64
+	/**
65
+	 * @return \EventEspresso\core\services\database\TableManager
66
+	 */
67
+	public static function getTableManager()
68
+	{
69
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
70
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
71
+		}
72
+		return self::$table_manager;
73
+	}
74
+
75
+
76
+	/**
77
+	 *    _ensure_table_name_has_prefix
78
+	 *
79
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
80
+	 * @access     public
81
+	 * @static
82
+	 * @param $table_name
83
+	 * @return string
84
+	 */
85
+	public static function ensure_table_name_has_prefix($table_name)
86
+	{
87
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88
+	}
89
+
90
+
91
+	/**
92
+	 *    system_initialization
93
+	 *    ensures the EE configuration settings are loaded with at least default options set
94
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
95
+	 *
96
+	 * @access public
97
+	 * @static
98
+	 * @return void
99
+	 */
100
+	public static function system_initialization()
101
+	{
102
+		EEH_Activation::reset_and_update_config();
103
+		// which is fired BEFORE activation of plugin anyways
104
+		EEH_Activation::verify_default_pages_exist();
105
+	}
106
+
107
+
108
+	/**
109
+	 * Sets the database schema and creates folders. This should
110
+	 * be called on plugin activation and reactivation
111
+	 *
112
+	 * @return boolean success, whether the database and folders are setup properly
113
+	 * @throws \EE_Error
114
+	 */
115
+	public static function initialize_db_and_folders()
116
+	{
117
+		return EEH_Activation::create_database_tables();
118
+	}
119
+
120
+
121
+	/**
122
+	 * assuming we have an up-to-date database schema, this will populate it
123
+	 * with default and initial data. This should be called
124
+	 * upon activation of a new plugin, reactivation, and at the end
125
+	 * of running migration scripts
126
+	 *
127
+	 * @throws \EE_Error
128
+	 */
129
+	public static function initialize_db_content()
130
+	{
131
+		// let's avoid doing all this logic repeatedly, especially when addons are requesting it
132
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
133
+			return;
134
+		}
135
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
136
+
137
+		EEH_Activation::initialize_system_questions();
138
+		EEH_Activation::insert_default_status_codes();
139
+		EEH_Activation::generate_default_message_templates();
140
+		EEH_Activation::create_no_ticket_prices_array();
141
+
142
+		EEH_Activation::validate_messages_system();
143
+		EEH_Activation::insert_default_payment_methods();
144
+		// in case we've
145
+		EEH_Activation::remove_cron_tasks();
146
+		EEH_Activation::create_cron_tasks();
147
+		// remove all TXN locks since that is being done via extra meta now
148
+		delete_option('ee_locked_transactions');
149
+		// also, check for CAF default db content
150
+		do_action('AHEE__EEH_Activation__initialize_db_content');
151
+		// also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
152
+		// which users really won't care about on initial activation
153
+		EE_Error::overwrite_success();
154
+	}
155
+
156
+
157
+	/**
158
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
159
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
160
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
161
+	 * (null)
162
+	 *
163
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
164
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
165
+	 * @return array
166
+	 * @throws \EE_Error
167
+	 */
168
+	public static function get_cron_tasks($which_to_include)
169
+	{
170
+		$cron_tasks = apply_filters(
171
+			'FHEE__EEH_Activation__get_cron_tasks',
172
+			array(
173
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
174
+			//              'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
175
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
176
+				// 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
177
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
178
+			)
179
+		);
180
+		if ($which_to_include === 'old') {
181
+			$cron_tasks = array_filter(
182
+				$cron_tasks,
183
+				function ($value) {
184
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
185
+				}
186
+			);
187
+		} elseif ($which_to_include === 'current') {
188
+			$cron_tasks = array_filter($cron_tasks);
189
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
190
+			throw new EE_Error(
191
+				sprintf(
192
+					__(
193
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
194
+						'event_espresso'
195
+					),
196
+					$which_to_include
197
+				)
198
+			);
199
+		}
200
+		return $cron_tasks;
201
+	}
202
+
203
+
204
+	/**
205
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
206
+	 *
207
+	 * @throws \EE_Error
208
+	 */
209
+	public static function create_cron_tasks()
210
+	{
211
+
212
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
213
+			if (! wp_next_scheduled($hook_name)) {
214
+				/**
215
+				 * This allows client code to define the initial start timestamp for this schedule.
216
+				 */
217
+				if (is_array($frequency)
218
+					&& count($frequency) === 2
219
+					&& isset($frequency[0], $frequency[1])
220
+				) {
221
+					$start_timestamp = $frequency[0];
222
+					$frequency = $frequency[1];
223
+				} else {
224
+					$start_timestamp = time();
225
+				}
226
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
227
+			}
228
+		}
229
+	}
230
+
231
+
232
+	/**
233
+	 * Remove the currently-existing and now-removed cron tasks.
234
+	 *
235
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
236
+	 * @throws \EE_Error
237
+	 */
238
+	public static function remove_cron_tasks($remove_all = true)
239
+	{
240
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
241
+		$crons                = _get_cron_array();
242
+		$crons                = is_array($crons) ? $crons : array();
243
+		/* reminder of what $crons look like:
244 244
          * Top-level keys are timestamps, and their values are arrays.
245 245
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
246 246
          * and their values are arrays.
@@ -257,909 +257,909 @@  discard block
 block discarded – undo
257 257
          *                  ...
258 258
          *      ...
259 259
          */
260
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
261
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
262
-            if (is_array($hooks_to_fire_at_time)) {
263
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
264
-                    if (isset($ee_cron_tasks_to_remove[ $hook_name ])
265
-                        && is_array($ee_cron_tasks_to_remove[ $hook_name ])
266
-                    ) {
267
-                        unset($crons[ $timestamp ][ $hook_name ]);
268
-                    }
269
-                }
270
-                // also take care of any empty cron timestamps.
271
-                if (empty($hooks_to_fire_at_time)) {
272
-                    unset($crons[ $timestamp ]);
273
-                }
274
-            }
275
-        }
276
-        _set_cron_array($crons);
277
-    }
278
-
279
-
280
-    /**
281
-     *    CPT_initialization
282
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
283
-     *
284
-     * @access public
285
-     * @static
286
-     * @return void
287
-     */
288
-    public static function CPT_initialization()
289
-    {
290
-        // register Custom Post Types
291
-        EE_Registry::instance()->load_core('Register_CPTs');
292
-        flush_rewrite_rules();
293
-    }
294
-
295
-
296
-
297
-    /**
298
-     *    reset_and_update_config
299
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
300
-     * If there is old calendar config data saved, then it will get converted on activation.
301
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
302
-     *
303
-     * @access public
304
-     * @static
305
-     * @return void
306
-     */
307
-    public static function reset_and_update_config()
308
-    {
309
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
310
-        add_filter(
311
-            'FHEE__EE_Config___load_core_config__config_settings',
312
-            array('EEH_Activation', 'migrate_old_config_data'),
313
-            10,
314
-            3
315
-        );
316
-        // EE_Config::reset();
317
-        if (! EE_Config::logging_enabled()) {
318
-            delete_option(EE_Config::LOG_NAME);
319
-        }
320
-    }
321
-
322
-
323
-    /**
324
-     *    load_calendar_config
325
-     *
326
-     * @access    public
327
-     * @return    void
328
-     */
329
-    public static function load_calendar_config()
330
-    {
331
-        // grab array of all plugin folders and loop thru it
332
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
333
-        if (empty($plugins)) {
334
-            return;
335
-        }
336
-        foreach ($plugins as $plugin_path) {
337
-            // grab plugin folder name from path
338
-            $plugin = basename($plugin_path);
339
-            // drill down to Espresso plugins
340
-            // then to calendar related plugins
341
-            if (strpos($plugin, 'espresso') !== false
342
-                || strpos($plugin, 'Espresso') !== false
343
-                || strpos($plugin, 'ee4') !== false
344
-                || strpos($plugin, 'EE4') !== false
345
-                || strpos($plugin, 'calendar') !== false
346
-            ) {
347
-                // this is what we are looking for
348
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
349
-                // does it exist in this folder ?
350
-                if (is_readable($calendar_config)) {
351
-                    // YEAH! let's load it
352
-                    require_once($calendar_config);
353
-                }
354
-            }
355
-        }
356
-    }
357
-
358
-
359
-
360
-    /**
361
-     *    _migrate_old_config_data
362
-     *
363
-     * @access    public
364
-     * @param array|stdClass $settings
365
-     * @param string         $config
366
-     * @param \EE_Config     $EE_Config
367
-     * @return \stdClass
368
-     */
369
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
370
-    {
371
-        $convert_from_array = array('addons');
372
-        // in case old settings were saved as an array
373
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
374
-            // convert existing settings to an object
375
-            $config_array = $settings;
376
-            $settings = new stdClass();
377
-            foreach ($config_array as $key => $value) {
378
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
379
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
380
-                } else {
381
-                    $settings->{$key} = $value;
382
-                }
383
-            }
384
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
385
-        }
386
-        return $settings;
387
-    }
388
-
389
-
390
-    /**
391
-     * deactivate_event_espresso
392
-     *
393
-     * @access public
394
-     * @static
395
-     * @return void
396
-     */
397
-    public static function deactivate_event_espresso()
398
-    {
399
-        // check permissions
400
-        if (current_user_can('activate_plugins')) {
401
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
402
-        }
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * verify_default_pages_exist
409
-     *
410
-     * @access public
411
-     * @static
412
-     * @return void
413
-     * @throws InvalidDataTypeException
414
-     */
415
-    public static function verify_default_pages_exist()
416
-    {
417
-        $critical_page_problem = false;
418
-        $critical_pages = array(
419
-            array(
420
-                'id'   => 'reg_page_id',
421
-                'name' => __('Registration Checkout', 'event_espresso'),
422
-                'post' => null,
423
-                'code' => 'ESPRESSO_CHECKOUT',
424
-            ),
425
-            array(
426
-                'id'   => 'txn_page_id',
427
-                'name' => __('Transactions', 'event_espresso'),
428
-                'post' => null,
429
-                'code' => 'ESPRESSO_TXN_PAGE',
430
-            ),
431
-            array(
432
-                'id'   => 'thank_you_page_id',
433
-                'name' => __('Thank You', 'event_espresso'),
434
-                'post' => null,
435
-                'code' => 'ESPRESSO_THANK_YOU',
436
-            ),
437
-            array(
438
-                'id'   => 'cancel_page_id',
439
-                'name' => __('Registration Cancelled', 'event_espresso'),
440
-                'post' => null,
441
-                'code' => 'ESPRESSO_CANCELLED',
442
-            ),
443
-        );
444
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
445
-        foreach ($critical_pages as $critical_page) {
446
-            // is critical page ID set in config ?
447
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
448
-                // attempt to find post by ID
449
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
450
-            }
451
-            // no dice?
452
-            if ($critical_page['post'] === null) {
453
-                // attempt to find post by title
454
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
455
-                // still nothing?
456
-                if ($critical_page['post'] === null) {
457
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
458
-                    // REALLY? Still nothing ??!?!?
459
-                    if ($critical_page['post'] === null) {
460
-                        $msg = __(
461
-                            'The Event Espresso critical page configuration settings could not be updated.',
462
-                            'event_espresso'
463
-                        );
464
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
465
-                        break;
466
-                    }
467
-                }
468
-            }
469
-            // check that Post ID matches critical page ID in config
470
-            if (isset($critical_page['post']->ID)
471
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
472
-            ) {
473
-                // update Config with post ID
474
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
475
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
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
-                }
482
-            }
483
-            $critical_page_problem =
484
-                ! isset($critical_page['post']->post_status)
485
-                || $critical_page['post']->post_status !== 'publish'
486
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
487
-                    ? true
488
-                    : $critical_page_problem;
489
-        }
490
-        if ($critical_page_problem) {
491
-            new PersistentAdminNotice(
492
-                'critical_page_problem',
493
-                sprintf(
494
-                    esc_html__(
495
-                        'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
496
-                        'event_espresso'
497
-                    ),
498
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
499
-                    . __('Event Espresso Critical Pages Settings', 'event_espresso')
500
-                    . '</a>'
501
-                )
502
-            );
503
-        }
504
-        if (EE_Error::has_notices()) {
505
-            EE_Error::get_notices(false, true, true);
506
-        }
507
-    }
508
-
509
-
510
-
511
-    /**
512
-     * Returns the first post which uses the specified shortcode
513
-     *
514
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
515
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
516
-     *                             "[ESPRESSO_THANK_YOU"
517
-     *                             (we don't search for the closing shortcode bracket because they might have added
518
-     *                             parameter to the shortcode
519
-     * @return WP_Post or NULl
520
-     */
521
-    public static function get_page_by_ee_shortcode($ee_shortcode)
522
-    {
523
-        global $wpdb;
524
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
525
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
526
-        if ($post_id) {
527
-            return get_post($post_id);
528
-        } else {
529
-            return null;
530
-        }
531
-    }
532
-
533
-
534
-    /**
535
-     *    This function generates a post for critical espresso pages
536
-     *
537
-     * @access public
538
-     * @static
539
-     * @param array $critical_page
540
-     * @return array
541
-     */
542
-    public static function create_critical_page($critical_page)
543
-    {
544
-
545
-        $post_args = array(
546
-            'post_title'     => $critical_page['name'],
547
-            'post_status'    => 'publish',
548
-            'post_type'      => 'page',
549
-            'comment_status' => 'closed',
550
-            'post_content'   => '[' . $critical_page['code'] . ']',
551
-        );
552
-
553
-        $post_id = wp_insert_post($post_args);
554
-        if (! $post_id) {
555
-            $msg = sprintf(
556
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
557
-                $critical_page['name']
558
-            );
559
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
560
-            return $critical_page;
561
-        }
562
-        // get newly created post's details
563
-        if (! $critical_page['post'] = get_post($post_id)) {
564
-            $msg = sprintf(
565
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
566
-                $critical_page['name']
567
-            );
568
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
569
-        }
570
-
571
-        return $critical_page;
572
-    }
573
-
574
-
575
-
576
-
577
-    /**
578
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
579
-     * The role being used to check is filterable.
580
-     *
581
-     * @since  4.6.0
582
-     * @global WPDB $wpdb
583
-     * @return mixed null|int WP_user ID or NULL
584
-     */
585
-    public static function get_default_creator_id()
586
-    {
587
-        global $wpdb;
588
-        if (! empty(self::$_default_creator_id)) {
589
-            return self::$_default_creator_id;
590
-        }/**/
591
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
592
-        // 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.
593
-        $pre_filtered_id = apply_filters(
594
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
595
-            false,
596
-            $role_to_check
597
-        );
598
-        if ($pre_filtered_id !== false) {
599
-            return (int) $pre_filtered_id;
600
-        }
601
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
602
-        $query = $wpdb->prepare(
603
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
604
-            '%' . $role_to_check . '%'
605
-        );
606
-        $user_id = $wpdb->get_var($query);
607
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
608
-        if ($user_id && (int) $user_id) {
609
-            self::$_default_creator_id = (int) $user_id;
610
-            return self::$_default_creator_id;
611
-        } else {
612
-            return null;
613
-        }
614
-    }
615
-
616
-
617
-
618
-    /**
619
-     * used by EE and EE addons during plugin activation to create tables.
620
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
621
-     * but includes extra logic regarding activations.
622
-     *
623
-     * @access public
624
-     * @static
625
-     * @param string  $table_name              without the $wpdb->prefix
626
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
627
-     *                                         table query)
628
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
629
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
630
-     *                                         and new once this function is done (ie, you really do want to CREATE a
631
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
632
-     *                                         you just want to verify the table exists and matches this definition
633
-     *                                         (and if it HAS data in it you want to leave it be)
634
-     * @return void
635
-     * @throws EE_Error if there are database errors
636
-     */
637
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
638
-    {
639
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
640
-            return;
641
-        }
642
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
643
-        if (! function_exists('dbDelta')) {
644
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
645
-        }
646
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
647
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
648
-        // do we need to first delete an existing version of this table ?
649
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
650
-            // ok, delete the table... but ONLY if it's empty
651
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
652
-            // table is NOT empty, are you SURE you want to delete this table ???
653
-            if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
654
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
655
-            } elseif (! $deleted_safely) {
656
-                // so we should be more cautious rather than just dropping tables so easily
657
-                error_log(
658
-                    sprintf(
659
-                        __(
660
-                            '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.',
661
-                            'event_espresso'
662
-                        ),
663
-                        $wp_table_name,
664
-                        '<br/>',
665
-                        'espresso_db_update'
666
-                    )
667
-                );
668
-            }
669
-        }
670
-        $engine = str_replace('ENGINE=', '', $engine);
671
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
672
-    }
673
-
674
-
675
-
676
-    /**
677
-     *    add_column_if_it_doesn't_exist
678
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
679
-     *
680
-     * @access     public
681
-     * @static
682
-     * @deprecated instead use TableManager::addColumn()
683
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
684
-     * @param string $column_name
685
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
686
-     *                            'VARCHAR(10)'
687
-     * @return bool|int
688
-     */
689
-    public static function add_column_if_it_doesnt_exist(
690
-        $table_name,
691
-        $column_name,
692
-        $column_info = 'INT UNSIGNED NOT NULL'
693
-    ) {
694
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
695
-    }
696
-
697
-
698
-    /**
699
-     * get_fields_on_table
700
-     * Gets all the fields on the database table.
701
-     *
702
-     * @access     public
703
-     * @deprecated instead use TableManager::getTableColumns()
704
-     * @static
705
-     * @param string $table_name , without prefixed $wpdb->prefix
706
-     * @return array of database column names
707
-     */
708
-    public static function get_fields_on_table($table_name = null)
709
-    {
710
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
711
-    }
712
-
713
-
714
-    /**
715
-     * db_table_is_empty
716
-     *
717
-     * @access     public\
718
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
719
-     * @static
720
-     * @param string $table_name
721
-     * @return bool
722
-     */
723
-    public static function db_table_is_empty($table_name)
724
-    {
725
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
726
-    }
727
-
728
-
729
-    /**
730
-     * delete_db_table_if_empty
731
-     *
732
-     * @access public
733
-     * @static
734
-     * @param string $table_name
735
-     * @return bool | int
736
-     */
737
-    public static function delete_db_table_if_empty($table_name)
738
-    {
739
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
740
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
741
-        }
742
-        return false;
743
-    }
744
-
745
-
746
-    /**
747
-     * delete_unused_db_table
748
-     *
749
-     * @access     public
750
-     * @static
751
-     * @deprecated instead use TableManager::dropTable()
752
-     * @param string $table_name
753
-     * @return bool | int
754
-     */
755
-    public static function delete_unused_db_table($table_name)
756
-    {
757
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
758
-    }
759
-
760
-
761
-    /**
762
-     * drop_index
763
-     *
764
-     * @access     public
765
-     * @static
766
-     * @deprecated instead use TableManager::dropIndex()
767
-     * @param string $table_name
768
-     * @param string $index_name
769
-     * @return bool | int
770
-     */
771
-    public static function drop_index($table_name, $index_name)
772
-    {
773
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
774
-    }
775
-
776
-
777
-
778
-    /**
779
-     * create_database_tables
780
-     *
781
-     * @access public
782
-     * @static
783
-     * @throws EE_Error
784
-     * @return boolean success (whether database is setup properly or not)
785
-     */
786
-    public static function create_database_tables()
787
-    {
788
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
789
-        // find the migration script that sets the database to be compatible with the code
790
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
791
-        if ($dms_name) {
792
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
793
-            $current_data_migration_script->set_migrating(false);
794
-            $current_data_migration_script->schema_changes_before_migration();
795
-            $current_data_migration_script->schema_changes_after_migration();
796
-            if ($current_data_migration_script->get_errors()) {
797
-                if (WP_DEBUG) {
798
-                    foreach ($current_data_migration_script->get_errors() as $error) {
799
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
800
-                    }
801
-                } else {
802
-                    EE_Error::add_error(
803
-                        __(
804
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
260
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
261
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
262
+			if (is_array($hooks_to_fire_at_time)) {
263
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
264
+					if (isset($ee_cron_tasks_to_remove[ $hook_name ])
265
+						&& is_array($ee_cron_tasks_to_remove[ $hook_name ])
266
+					) {
267
+						unset($crons[ $timestamp ][ $hook_name ]);
268
+					}
269
+				}
270
+				// also take care of any empty cron timestamps.
271
+				if (empty($hooks_to_fire_at_time)) {
272
+					unset($crons[ $timestamp ]);
273
+				}
274
+			}
275
+		}
276
+		_set_cron_array($crons);
277
+	}
278
+
279
+
280
+	/**
281
+	 *    CPT_initialization
282
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
283
+	 *
284
+	 * @access public
285
+	 * @static
286
+	 * @return void
287
+	 */
288
+	public static function CPT_initialization()
289
+	{
290
+		// register Custom Post Types
291
+		EE_Registry::instance()->load_core('Register_CPTs');
292
+		flush_rewrite_rules();
293
+	}
294
+
295
+
296
+
297
+	/**
298
+	 *    reset_and_update_config
299
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
300
+	 * If there is old calendar config data saved, then it will get converted on activation.
301
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
302
+	 *
303
+	 * @access public
304
+	 * @static
305
+	 * @return void
306
+	 */
307
+	public static function reset_and_update_config()
308
+	{
309
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
310
+		add_filter(
311
+			'FHEE__EE_Config___load_core_config__config_settings',
312
+			array('EEH_Activation', 'migrate_old_config_data'),
313
+			10,
314
+			3
315
+		);
316
+		// EE_Config::reset();
317
+		if (! EE_Config::logging_enabled()) {
318
+			delete_option(EE_Config::LOG_NAME);
319
+		}
320
+	}
321
+
322
+
323
+	/**
324
+	 *    load_calendar_config
325
+	 *
326
+	 * @access    public
327
+	 * @return    void
328
+	 */
329
+	public static function load_calendar_config()
330
+	{
331
+		// grab array of all plugin folders and loop thru it
332
+		$plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
333
+		if (empty($plugins)) {
334
+			return;
335
+		}
336
+		foreach ($plugins as $plugin_path) {
337
+			// grab plugin folder name from path
338
+			$plugin = basename($plugin_path);
339
+			// drill down to Espresso plugins
340
+			// then to calendar related plugins
341
+			if (strpos($plugin, 'espresso') !== false
342
+				|| strpos($plugin, 'Espresso') !== false
343
+				|| strpos($plugin, 'ee4') !== false
344
+				|| strpos($plugin, 'EE4') !== false
345
+				|| strpos($plugin, 'calendar') !== false
346
+			) {
347
+				// this is what we are looking for
348
+				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
349
+				// does it exist in this folder ?
350
+				if (is_readable($calendar_config)) {
351
+					// YEAH! let's load it
352
+					require_once($calendar_config);
353
+				}
354
+			}
355
+		}
356
+	}
357
+
358
+
359
+
360
+	/**
361
+	 *    _migrate_old_config_data
362
+	 *
363
+	 * @access    public
364
+	 * @param array|stdClass $settings
365
+	 * @param string         $config
366
+	 * @param \EE_Config     $EE_Config
367
+	 * @return \stdClass
368
+	 */
369
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
370
+	{
371
+		$convert_from_array = array('addons');
372
+		// in case old settings were saved as an array
373
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
374
+			// convert existing settings to an object
375
+			$config_array = $settings;
376
+			$settings = new stdClass();
377
+			foreach ($config_array as $key => $value) {
378
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
379
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
380
+				} else {
381
+					$settings->{$key} = $value;
382
+				}
383
+			}
384
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
385
+		}
386
+		return $settings;
387
+	}
388
+
389
+
390
+	/**
391
+	 * deactivate_event_espresso
392
+	 *
393
+	 * @access public
394
+	 * @static
395
+	 * @return void
396
+	 */
397
+	public static function deactivate_event_espresso()
398
+	{
399
+		// check permissions
400
+		if (current_user_can('activate_plugins')) {
401
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
402
+		}
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * verify_default_pages_exist
409
+	 *
410
+	 * @access public
411
+	 * @static
412
+	 * @return void
413
+	 * @throws InvalidDataTypeException
414
+	 */
415
+	public static function verify_default_pages_exist()
416
+	{
417
+		$critical_page_problem = false;
418
+		$critical_pages = array(
419
+			array(
420
+				'id'   => 'reg_page_id',
421
+				'name' => __('Registration Checkout', 'event_espresso'),
422
+				'post' => null,
423
+				'code' => 'ESPRESSO_CHECKOUT',
424
+			),
425
+			array(
426
+				'id'   => 'txn_page_id',
427
+				'name' => __('Transactions', 'event_espresso'),
428
+				'post' => null,
429
+				'code' => 'ESPRESSO_TXN_PAGE',
430
+			),
431
+			array(
432
+				'id'   => 'thank_you_page_id',
433
+				'name' => __('Thank You', 'event_espresso'),
434
+				'post' => null,
435
+				'code' => 'ESPRESSO_THANK_YOU',
436
+			),
437
+			array(
438
+				'id'   => 'cancel_page_id',
439
+				'name' => __('Registration Cancelled', 'event_espresso'),
440
+				'post' => null,
441
+				'code' => 'ESPRESSO_CANCELLED',
442
+			),
443
+		);
444
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
445
+		foreach ($critical_pages as $critical_page) {
446
+			// is critical page ID set in config ?
447
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
448
+				// attempt to find post by ID
449
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
450
+			}
451
+			// no dice?
452
+			if ($critical_page['post'] === null) {
453
+				// attempt to find post by title
454
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
455
+				// still nothing?
456
+				if ($critical_page['post'] === null) {
457
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
458
+					// REALLY? Still nothing ??!?!?
459
+					if ($critical_page['post'] === null) {
460
+						$msg = __(
461
+							'The Event Espresso critical page configuration settings could not be updated.',
462
+							'event_espresso'
463
+						);
464
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
465
+						break;
466
+					}
467
+				}
468
+			}
469
+			// check that Post ID matches critical page ID in config
470
+			if (isset($critical_page['post']->ID)
471
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
472
+			) {
473
+				// update Config with post ID
474
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
475
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
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
+				}
482
+			}
483
+			$critical_page_problem =
484
+				! isset($critical_page['post']->post_status)
485
+				|| $critical_page['post']->post_status !== 'publish'
486
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
487
+					? true
488
+					: $critical_page_problem;
489
+		}
490
+		if ($critical_page_problem) {
491
+			new PersistentAdminNotice(
492
+				'critical_page_problem',
493
+				sprintf(
494
+					esc_html__(
495
+						'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
496
+						'event_espresso'
497
+					),
498
+					'<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
499
+					. __('Event Espresso Critical Pages Settings', 'event_espresso')
500
+					. '</a>'
501
+				)
502
+			);
503
+		}
504
+		if (EE_Error::has_notices()) {
505
+			EE_Error::get_notices(false, true, true);
506
+		}
507
+	}
508
+
509
+
510
+
511
+	/**
512
+	 * Returns the first post which uses the specified shortcode
513
+	 *
514
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
515
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
516
+	 *                             "[ESPRESSO_THANK_YOU"
517
+	 *                             (we don't search for the closing shortcode bracket because they might have added
518
+	 *                             parameter to the shortcode
519
+	 * @return WP_Post or NULl
520
+	 */
521
+	public static function get_page_by_ee_shortcode($ee_shortcode)
522
+	{
523
+		global $wpdb;
524
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
525
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
526
+		if ($post_id) {
527
+			return get_post($post_id);
528
+		} else {
529
+			return null;
530
+		}
531
+	}
532
+
533
+
534
+	/**
535
+	 *    This function generates a post for critical espresso pages
536
+	 *
537
+	 * @access public
538
+	 * @static
539
+	 * @param array $critical_page
540
+	 * @return array
541
+	 */
542
+	public static function create_critical_page($critical_page)
543
+	{
544
+
545
+		$post_args = array(
546
+			'post_title'     => $critical_page['name'],
547
+			'post_status'    => 'publish',
548
+			'post_type'      => 'page',
549
+			'comment_status' => 'closed',
550
+			'post_content'   => '[' . $critical_page['code'] . ']',
551
+		);
552
+
553
+		$post_id = wp_insert_post($post_args);
554
+		if (! $post_id) {
555
+			$msg = sprintf(
556
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
557
+				$critical_page['name']
558
+			);
559
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
560
+			return $critical_page;
561
+		}
562
+		// get newly created post's details
563
+		if (! $critical_page['post'] = get_post($post_id)) {
564
+			$msg = sprintf(
565
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
566
+				$critical_page['name']
567
+			);
568
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
569
+		}
570
+
571
+		return $critical_page;
572
+	}
573
+
574
+
575
+
576
+
577
+	/**
578
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
579
+	 * The role being used to check is filterable.
580
+	 *
581
+	 * @since  4.6.0
582
+	 * @global WPDB $wpdb
583
+	 * @return mixed null|int WP_user ID or NULL
584
+	 */
585
+	public static function get_default_creator_id()
586
+	{
587
+		global $wpdb;
588
+		if (! empty(self::$_default_creator_id)) {
589
+			return self::$_default_creator_id;
590
+		}/**/
591
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
592
+		// 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.
593
+		$pre_filtered_id = apply_filters(
594
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
595
+			false,
596
+			$role_to_check
597
+		);
598
+		if ($pre_filtered_id !== false) {
599
+			return (int) $pre_filtered_id;
600
+		}
601
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
602
+		$query = $wpdb->prepare(
603
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
604
+			'%' . $role_to_check . '%'
605
+		);
606
+		$user_id = $wpdb->get_var($query);
607
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
608
+		if ($user_id && (int) $user_id) {
609
+			self::$_default_creator_id = (int) $user_id;
610
+			return self::$_default_creator_id;
611
+		} else {
612
+			return null;
613
+		}
614
+	}
615
+
616
+
617
+
618
+	/**
619
+	 * used by EE and EE addons during plugin activation to create tables.
620
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
621
+	 * but includes extra logic regarding activations.
622
+	 *
623
+	 * @access public
624
+	 * @static
625
+	 * @param string  $table_name              without the $wpdb->prefix
626
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
627
+	 *                                         table query)
628
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
629
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
630
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
631
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
632
+	 *                                         you just want to verify the table exists and matches this definition
633
+	 *                                         (and if it HAS data in it you want to leave it be)
634
+	 * @return void
635
+	 * @throws EE_Error if there are database errors
636
+	 */
637
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
638
+	{
639
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
640
+			return;
641
+		}
642
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
643
+		if (! function_exists('dbDelta')) {
644
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
645
+		}
646
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
647
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
648
+		// do we need to first delete an existing version of this table ?
649
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
650
+			// ok, delete the table... but ONLY if it's empty
651
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
652
+			// table is NOT empty, are you SURE you want to delete this table ???
653
+			if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
654
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
655
+			} elseif (! $deleted_safely) {
656
+				// so we should be more cautious rather than just dropping tables so easily
657
+				error_log(
658
+					sprintf(
659
+						__(
660
+							'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.',
661
+							'event_espresso'
662
+						),
663
+						$wp_table_name,
664
+						'<br/>',
665
+						'espresso_db_update'
666
+					)
667
+				);
668
+			}
669
+		}
670
+		$engine = str_replace('ENGINE=', '', $engine);
671
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
672
+	}
673
+
674
+
675
+
676
+	/**
677
+	 *    add_column_if_it_doesn't_exist
678
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
679
+	 *
680
+	 * @access     public
681
+	 * @static
682
+	 * @deprecated instead use TableManager::addColumn()
683
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
684
+	 * @param string $column_name
685
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
686
+	 *                            'VARCHAR(10)'
687
+	 * @return bool|int
688
+	 */
689
+	public static function add_column_if_it_doesnt_exist(
690
+		$table_name,
691
+		$column_name,
692
+		$column_info = 'INT UNSIGNED NOT NULL'
693
+	) {
694
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
695
+	}
696
+
697
+
698
+	/**
699
+	 * get_fields_on_table
700
+	 * Gets all the fields on the database table.
701
+	 *
702
+	 * @access     public
703
+	 * @deprecated instead use TableManager::getTableColumns()
704
+	 * @static
705
+	 * @param string $table_name , without prefixed $wpdb->prefix
706
+	 * @return array of database column names
707
+	 */
708
+	public static function get_fields_on_table($table_name = null)
709
+	{
710
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
711
+	}
712
+
713
+
714
+	/**
715
+	 * db_table_is_empty
716
+	 *
717
+	 * @access     public\
718
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
719
+	 * @static
720
+	 * @param string $table_name
721
+	 * @return bool
722
+	 */
723
+	public static function db_table_is_empty($table_name)
724
+	{
725
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
726
+	}
727
+
728
+
729
+	/**
730
+	 * delete_db_table_if_empty
731
+	 *
732
+	 * @access public
733
+	 * @static
734
+	 * @param string $table_name
735
+	 * @return bool | int
736
+	 */
737
+	public static function delete_db_table_if_empty($table_name)
738
+	{
739
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
740
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
741
+		}
742
+		return false;
743
+	}
744
+
745
+
746
+	/**
747
+	 * delete_unused_db_table
748
+	 *
749
+	 * @access     public
750
+	 * @static
751
+	 * @deprecated instead use TableManager::dropTable()
752
+	 * @param string $table_name
753
+	 * @return bool | int
754
+	 */
755
+	public static function delete_unused_db_table($table_name)
756
+	{
757
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
758
+	}
759
+
760
+
761
+	/**
762
+	 * drop_index
763
+	 *
764
+	 * @access     public
765
+	 * @static
766
+	 * @deprecated instead use TableManager::dropIndex()
767
+	 * @param string $table_name
768
+	 * @param string $index_name
769
+	 * @return bool | int
770
+	 */
771
+	public static function drop_index($table_name, $index_name)
772
+	{
773
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
774
+	}
775
+
776
+
777
+
778
+	/**
779
+	 * create_database_tables
780
+	 *
781
+	 * @access public
782
+	 * @static
783
+	 * @throws EE_Error
784
+	 * @return boolean success (whether database is setup properly or not)
785
+	 */
786
+	public static function create_database_tables()
787
+	{
788
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
789
+		// find the migration script that sets the database to be compatible with the code
790
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
791
+		if ($dms_name) {
792
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
793
+			$current_data_migration_script->set_migrating(false);
794
+			$current_data_migration_script->schema_changes_before_migration();
795
+			$current_data_migration_script->schema_changes_after_migration();
796
+			if ($current_data_migration_script->get_errors()) {
797
+				if (WP_DEBUG) {
798
+					foreach ($current_data_migration_script->get_errors() as $error) {
799
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
800
+					}
801
+				} else {
802
+					EE_Error::add_error(
803
+						__(
804
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
805 805
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
806
-                            'event_espresso'
807
-                        )
808
-                    );
809
-                }
810
-                return false;
811
-            }
812
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
813
-        } else {
814
-            EE_Error::add_error(
815
-                __(
816
-                    'Could not determine most up-to-date data migration script from which to pull database schema
806
+							'event_espresso'
807
+						)
808
+					);
809
+				}
810
+				return false;
811
+			}
812
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
813
+		} else {
814
+			EE_Error::add_error(
815
+				__(
816
+					'Could not determine most up-to-date data migration script from which to pull database schema
817 817
                      structure. So database is probably not setup properly',
818
-                    'event_espresso'
819
-                ),
820
-                __FILE__,
821
-                __FUNCTION__,
822
-                __LINE__
823
-            );
824
-            return false;
825
-        }
826
-        return true;
827
-    }
828
-
829
-
830
-
831
-    /**
832
-     * initialize_system_questions
833
-     *
834
-     * @access public
835
-     * @static
836
-     * @return void
837
-     */
838
-    public static function initialize_system_questions()
839
-    {
840
-        // QUESTION GROUPS
841
-        global $wpdb;
842
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
843
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
844
-        // what we have
845
-        $question_groups = $wpdb->get_col($SQL);
846
-        // check the response
847
-        $question_groups = is_array($question_groups) ? $question_groups : array();
848
-        // what we should have
849
-        $QSG_systems = array(1, 2);
850
-        // loop thru what we should have and compare to what we have
851
-        foreach ($QSG_systems as $QSG_system) {
852
-            // reset values array
853
-            $QSG_values = array();
854
-            // 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)
855
-            if (! in_array("$QSG_system", $question_groups)) {
856
-                // add it
857
-                switch ($QSG_system) {
858
-                    case 1:
859
-                        $QSG_values = array(
860
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
861
-                            'QSG_identifier'      => 'personal-information-' . time(),
862
-                            'QSG_desc'            => '',
863
-                            'QSG_order'           => 1,
864
-                            'QSG_show_group_name' => 1,
865
-                            'QSG_show_group_desc' => 1,
866
-                            'QSG_system'          => EEM_Question_Group::system_personal,
867
-                            'QSG_deleted'         => 0,
868
-                        );
869
-                        break;
870
-                    case 2:
871
-                        $QSG_values = array(
872
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
873
-                            'QSG_identifier'      => 'address-information-' . time(),
874
-                            'QSG_desc'            => '',
875
-                            'QSG_order'           => 2,
876
-                            'QSG_show_group_name' => 1,
877
-                            'QSG_show_group_desc' => 1,
878
-                            'QSG_system'          => EEM_Question_Group::system_address,
879
-                            'QSG_deleted'         => 0,
880
-                        );
881
-                        break;
882
-                }
883
-                // make sure we have some values before inserting them
884
-                if (! empty($QSG_values)) {
885
-                    // insert system question
886
-                    $wpdb->insert(
887
-                        $table_name,
888
-                        $QSG_values,
889
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
890
-                    );
891
-                    $QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
892
-                }
893
-            }
894
-        }
895
-        // QUESTIONS
896
-        global $wpdb;
897
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
898
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
899
-        // what we have
900
-        $questions = $wpdb->get_col($SQL);
901
-        // what we should have
902
-        $QST_systems = array(
903
-            'fname',
904
-            'lname',
905
-            'email',
906
-            'address',
907
-            'address2',
908
-            'city',
909
-            'country',
910
-            'state',
911
-            'zip',
912
-            'phone',
913
-        );
914
-        $order_for_group_1 = 1;
915
-        $order_for_group_2 = 1;
916
-        // loop thru what we should have and compare to what we have
917
-        foreach ($QST_systems as $QST_system) {
918
-            // reset values array
919
-            $QST_values = array();
920
-            // if we don't have what we should have
921
-            if (! in_array($QST_system, $questions)) {
922
-                // add it
923
-                switch ($QST_system) {
924
-                    case 'fname':
925
-                        $QST_values = array(
926
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
927
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
928
-                            'QST_system'        => 'fname',
929
-                            'QST_type'          => 'TEXT',
930
-                            'QST_required'      => 1,
931
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
932
-                            'QST_order'         => 1,
933
-                            'QST_admin_only'    => 0,
934
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
935
-                            'QST_wp_user'       => self::get_default_creator_id(),
936
-                            'QST_deleted'       => 0,
937
-                        );
938
-                        break;
939
-                    case 'lname':
940
-                        $QST_values = array(
941
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
942
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
943
-                            'QST_system'        => 'lname',
944
-                            'QST_type'          => 'TEXT',
945
-                            'QST_required'      => 1,
946
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
947
-                            'QST_order'         => 2,
948
-                            'QST_admin_only'    => 0,
949
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
950
-                            'QST_wp_user'       => self::get_default_creator_id(),
951
-                            'QST_deleted'       => 0,
952
-                        );
953
-                        break;
954
-                    case 'email':
955
-                        $QST_values = array(
956
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
957
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
958
-                            'QST_system'        => 'email',
959
-                            'QST_type'          => 'EMAIL',
960
-                            'QST_required'      => 1,
961
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
962
-                            'QST_order'         => 3,
963
-                            'QST_admin_only'    => 0,
964
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
965
-                            'QST_wp_user'       => self::get_default_creator_id(),
966
-                            'QST_deleted'       => 0,
967
-                        );
968
-                        break;
969
-                    case 'address':
970
-                        $QST_values = array(
971
-                            'QST_display_text'  => __('Address', 'event_espresso'),
972
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
973
-                            'QST_system'        => 'address',
974
-                            'QST_type'          => 'TEXT',
975
-                            'QST_required'      => 0,
976
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
977
-                            'QST_order'         => 4,
978
-                            'QST_admin_only'    => 0,
979
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
980
-                            'QST_wp_user'       => self::get_default_creator_id(),
981
-                            'QST_deleted'       => 0,
982
-                        );
983
-                        break;
984
-                    case 'address2':
985
-                        $QST_values = array(
986
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
987
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
988
-                            'QST_system'        => 'address2',
989
-                            'QST_type'          => 'TEXT',
990
-                            'QST_required'      => 0,
991
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
992
-                            'QST_order'         => 5,
993
-                            'QST_admin_only'    => 0,
994
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
995
-                            'QST_wp_user'       => self::get_default_creator_id(),
996
-                            'QST_deleted'       => 0,
997
-                        );
998
-                        break;
999
-                    case 'city':
1000
-                        $QST_values = array(
1001
-                            'QST_display_text'  => __('City', 'event_espresso'),
1002
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1003
-                            'QST_system'        => 'city',
1004
-                            'QST_type'          => 'TEXT',
1005
-                            'QST_required'      => 0,
1006
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1007
-                            'QST_order'         => 6,
1008
-                            'QST_admin_only'    => 0,
1009
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1010
-                            'QST_wp_user'       => self::get_default_creator_id(),
1011
-                            'QST_deleted'       => 0,
1012
-                        );
1013
-                        break;
1014
-                    case 'country':
1015
-                        $QST_values = array(
1016
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1017
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1018
-                            'QST_system'        => 'country',
1019
-                            'QST_type'          => 'COUNTRY',
1020
-                            'QST_required'      => 0,
1021
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1022
-                            'QST_order'         => 7,
1023
-                            'QST_admin_only'    => 0,
1024
-                            'QST_wp_user'       => self::get_default_creator_id(),
1025
-                            'QST_deleted'       => 0,
1026
-                        );
1027
-                        break;
1028
-                    case 'state':
1029
-                        $QST_values = array(
1030
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1031
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1032
-                            'QST_system'        => 'state',
1033
-                            'QST_type'          => 'STATE',
1034
-                            'QST_required'      => 0,
1035
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1036
-                            'QST_order'         => 8,
1037
-                            'QST_admin_only'    => 0,
1038
-                            'QST_wp_user'       => self::get_default_creator_id(),
1039
-                            'QST_deleted'       => 0,
1040
-                        );
1041
-                        break;
1042
-                    case 'zip':
1043
-                        $QST_values = array(
1044
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1045
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1046
-                            'QST_system'        => 'zip',
1047
-                            'QST_type'          => 'TEXT',
1048
-                            'QST_required'      => 0,
1049
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1050
-                            'QST_order'         => 9,
1051
-                            'QST_admin_only'    => 0,
1052
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1053
-                            'QST_wp_user'       => self::get_default_creator_id(),
1054
-                            'QST_deleted'       => 0,
1055
-                        );
1056
-                        break;
1057
-                    case 'phone':
1058
-                        $QST_values = array(
1059
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1060
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1061
-                            'QST_system'        => 'phone',
1062
-                            'QST_type'          => 'TEXT',
1063
-                            'QST_required'      => 0,
1064
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1065
-                            'QST_order'         => 10,
1066
-                            'QST_admin_only'    => 0,
1067
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1068
-                            'QST_wp_user'       => self::get_default_creator_id(),
1069
-                            'QST_deleted'       => 0,
1070
-                        );
1071
-                        break;
1072
-                }
1073
-                if (! empty($QST_values)) {
1074
-                    // insert system question
1075
-                    $wpdb->insert(
1076
-                        $table_name,
1077
-                        $QST_values,
1078
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1079
-                    );
1080
-                    $QST_ID = $wpdb->insert_id;
1081
-                    // QUESTION GROUP QUESTIONS
1082
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1083
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1084
-                    } else {
1085
-                        $system_question_we_want = EEM_Question_Group::system_address;
1086
-                    }
1087
-                    if (isset($QSG_IDs[ $system_question_we_want ])) {
1088
-                        $QSG_ID = $QSG_IDs[ $system_question_we_want ];
1089
-                    } else {
1090
-                        $id_col = EEM_Question_Group::instance()
1091
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1092
-                        if (is_array($id_col)) {
1093
-                            $QSG_ID = reset($id_col);
1094
-                        } else {
1095
-                            // 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
1096
-                            EE_Log::instance()->log(
1097
-                                __FILE__,
1098
-                                __FUNCTION__,
1099
-                                sprintf(
1100
-                                    __(
1101
-                                        'Could not associate question %1$s to a question group because no system question
818
+					'event_espresso'
819
+				),
820
+				__FILE__,
821
+				__FUNCTION__,
822
+				__LINE__
823
+			);
824
+			return false;
825
+		}
826
+		return true;
827
+	}
828
+
829
+
830
+
831
+	/**
832
+	 * initialize_system_questions
833
+	 *
834
+	 * @access public
835
+	 * @static
836
+	 * @return void
837
+	 */
838
+	public static function initialize_system_questions()
839
+	{
840
+		// QUESTION GROUPS
841
+		global $wpdb;
842
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
843
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
844
+		// what we have
845
+		$question_groups = $wpdb->get_col($SQL);
846
+		// check the response
847
+		$question_groups = is_array($question_groups) ? $question_groups : array();
848
+		// what we should have
849
+		$QSG_systems = array(1, 2);
850
+		// loop thru what we should have and compare to what we have
851
+		foreach ($QSG_systems as $QSG_system) {
852
+			// reset values array
853
+			$QSG_values = array();
854
+			// 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)
855
+			if (! in_array("$QSG_system", $question_groups)) {
856
+				// add it
857
+				switch ($QSG_system) {
858
+					case 1:
859
+						$QSG_values = array(
860
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
861
+							'QSG_identifier'      => 'personal-information-' . time(),
862
+							'QSG_desc'            => '',
863
+							'QSG_order'           => 1,
864
+							'QSG_show_group_name' => 1,
865
+							'QSG_show_group_desc' => 1,
866
+							'QSG_system'          => EEM_Question_Group::system_personal,
867
+							'QSG_deleted'         => 0,
868
+						);
869
+						break;
870
+					case 2:
871
+						$QSG_values = array(
872
+							'QSG_name'            => __('Address Information', 'event_espresso'),
873
+							'QSG_identifier'      => 'address-information-' . time(),
874
+							'QSG_desc'            => '',
875
+							'QSG_order'           => 2,
876
+							'QSG_show_group_name' => 1,
877
+							'QSG_show_group_desc' => 1,
878
+							'QSG_system'          => EEM_Question_Group::system_address,
879
+							'QSG_deleted'         => 0,
880
+						);
881
+						break;
882
+				}
883
+				// make sure we have some values before inserting them
884
+				if (! empty($QSG_values)) {
885
+					// insert system question
886
+					$wpdb->insert(
887
+						$table_name,
888
+						$QSG_values,
889
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
890
+					);
891
+					$QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
892
+				}
893
+			}
894
+		}
895
+		// QUESTIONS
896
+		global $wpdb;
897
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
898
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
899
+		// what we have
900
+		$questions = $wpdb->get_col($SQL);
901
+		// what we should have
902
+		$QST_systems = array(
903
+			'fname',
904
+			'lname',
905
+			'email',
906
+			'address',
907
+			'address2',
908
+			'city',
909
+			'country',
910
+			'state',
911
+			'zip',
912
+			'phone',
913
+		);
914
+		$order_for_group_1 = 1;
915
+		$order_for_group_2 = 1;
916
+		// loop thru what we should have and compare to what we have
917
+		foreach ($QST_systems as $QST_system) {
918
+			// reset values array
919
+			$QST_values = array();
920
+			// if we don't have what we should have
921
+			if (! in_array($QST_system, $questions)) {
922
+				// add it
923
+				switch ($QST_system) {
924
+					case 'fname':
925
+						$QST_values = array(
926
+							'QST_display_text'  => __('First Name', 'event_espresso'),
927
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
928
+							'QST_system'        => 'fname',
929
+							'QST_type'          => 'TEXT',
930
+							'QST_required'      => 1,
931
+							'QST_required_text' => __('This field is required', 'event_espresso'),
932
+							'QST_order'         => 1,
933
+							'QST_admin_only'    => 0,
934
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
935
+							'QST_wp_user'       => self::get_default_creator_id(),
936
+							'QST_deleted'       => 0,
937
+						);
938
+						break;
939
+					case 'lname':
940
+						$QST_values = array(
941
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
942
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
943
+							'QST_system'        => 'lname',
944
+							'QST_type'          => 'TEXT',
945
+							'QST_required'      => 1,
946
+							'QST_required_text' => __('This field is required', 'event_espresso'),
947
+							'QST_order'         => 2,
948
+							'QST_admin_only'    => 0,
949
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
950
+							'QST_wp_user'       => self::get_default_creator_id(),
951
+							'QST_deleted'       => 0,
952
+						);
953
+						break;
954
+					case 'email':
955
+						$QST_values = array(
956
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
957
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
958
+							'QST_system'        => 'email',
959
+							'QST_type'          => 'EMAIL',
960
+							'QST_required'      => 1,
961
+							'QST_required_text' => __('This field is required', 'event_espresso'),
962
+							'QST_order'         => 3,
963
+							'QST_admin_only'    => 0,
964
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
965
+							'QST_wp_user'       => self::get_default_creator_id(),
966
+							'QST_deleted'       => 0,
967
+						);
968
+						break;
969
+					case 'address':
970
+						$QST_values = array(
971
+							'QST_display_text'  => __('Address', 'event_espresso'),
972
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
973
+							'QST_system'        => 'address',
974
+							'QST_type'          => 'TEXT',
975
+							'QST_required'      => 0,
976
+							'QST_required_text' => __('This field is required', 'event_espresso'),
977
+							'QST_order'         => 4,
978
+							'QST_admin_only'    => 0,
979
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
980
+							'QST_wp_user'       => self::get_default_creator_id(),
981
+							'QST_deleted'       => 0,
982
+						);
983
+						break;
984
+					case 'address2':
985
+						$QST_values = array(
986
+							'QST_display_text'  => __('Address2', 'event_espresso'),
987
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
988
+							'QST_system'        => 'address2',
989
+							'QST_type'          => 'TEXT',
990
+							'QST_required'      => 0,
991
+							'QST_required_text' => __('This field is required', 'event_espresso'),
992
+							'QST_order'         => 5,
993
+							'QST_admin_only'    => 0,
994
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
995
+							'QST_wp_user'       => self::get_default_creator_id(),
996
+							'QST_deleted'       => 0,
997
+						);
998
+						break;
999
+					case 'city':
1000
+						$QST_values = array(
1001
+							'QST_display_text'  => __('City', 'event_espresso'),
1002
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1003
+							'QST_system'        => 'city',
1004
+							'QST_type'          => 'TEXT',
1005
+							'QST_required'      => 0,
1006
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1007
+							'QST_order'         => 6,
1008
+							'QST_admin_only'    => 0,
1009
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1010
+							'QST_wp_user'       => self::get_default_creator_id(),
1011
+							'QST_deleted'       => 0,
1012
+						);
1013
+						break;
1014
+					case 'country':
1015
+						$QST_values = array(
1016
+							'QST_display_text'  => __('Country', 'event_espresso'),
1017
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1018
+							'QST_system'        => 'country',
1019
+							'QST_type'          => 'COUNTRY',
1020
+							'QST_required'      => 0,
1021
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1022
+							'QST_order'         => 7,
1023
+							'QST_admin_only'    => 0,
1024
+							'QST_wp_user'       => self::get_default_creator_id(),
1025
+							'QST_deleted'       => 0,
1026
+						);
1027
+						break;
1028
+					case 'state':
1029
+						$QST_values = array(
1030
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1031
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1032
+							'QST_system'        => 'state',
1033
+							'QST_type'          => 'STATE',
1034
+							'QST_required'      => 0,
1035
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1036
+							'QST_order'         => 8,
1037
+							'QST_admin_only'    => 0,
1038
+							'QST_wp_user'       => self::get_default_creator_id(),
1039
+							'QST_deleted'       => 0,
1040
+						);
1041
+						break;
1042
+					case 'zip':
1043
+						$QST_values = array(
1044
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1045
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1046
+							'QST_system'        => 'zip',
1047
+							'QST_type'          => 'TEXT',
1048
+							'QST_required'      => 0,
1049
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1050
+							'QST_order'         => 9,
1051
+							'QST_admin_only'    => 0,
1052
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1053
+							'QST_wp_user'       => self::get_default_creator_id(),
1054
+							'QST_deleted'       => 0,
1055
+						);
1056
+						break;
1057
+					case 'phone':
1058
+						$QST_values = array(
1059
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1060
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1061
+							'QST_system'        => 'phone',
1062
+							'QST_type'          => 'TEXT',
1063
+							'QST_required'      => 0,
1064
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1065
+							'QST_order'         => 10,
1066
+							'QST_admin_only'    => 0,
1067
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1068
+							'QST_wp_user'       => self::get_default_creator_id(),
1069
+							'QST_deleted'       => 0,
1070
+						);
1071
+						break;
1072
+				}
1073
+				if (! empty($QST_values)) {
1074
+					// insert system question
1075
+					$wpdb->insert(
1076
+						$table_name,
1077
+						$QST_values,
1078
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1079
+					);
1080
+					$QST_ID = $wpdb->insert_id;
1081
+					// QUESTION GROUP QUESTIONS
1082
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1083
+						$system_question_we_want = EEM_Question_Group::system_personal;
1084
+					} else {
1085
+						$system_question_we_want = EEM_Question_Group::system_address;
1086
+					}
1087
+					if (isset($QSG_IDs[ $system_question_we_want ])) {
1088
+						$QSG_ID = $QSG_IDs[ $system_question_we_want ];
1089
+					} else {
1090
+						$id_col = EEM_Question_Group::instance()
1091
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1092
+						if (is_array($id_col)) {
1093
+							$QSG_ID = reset($id_col);
1094
+						} else {
1095
+							// 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
1096
+							EE_Log::instance()->log(
1097
+								__FILE__,
1098
+								__FUNCTION__,
1099
+								sprintf(
1100
+									__(
1101
+										'Could not associate question %1$s to a question group because no system question
1102 1102
                                          group existed',
1103
-                                        'event_espresso'
1104
-                                    ),
1105
-                                    $QST_ID
1106
-                                ),
1107
-                                'error'
1108
-                            );
1109
-                            continue;
1110
-                        }
1111
-                    }
1112
-                    // add system questions to groups
1113
-                    $wpdb->insert(
1114
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1115
-                        array(
1116
-                            'QSG_ID'    => $QSG_ID,
1117
-                            'QST_ID'    => $QST_ID,
1118
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1119
-                        ),
1120
-                        array('%d', '%d', '%d')
1121
-                    );
1122
-                }
1123
-            }
1124
-        }
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * Makes sure the default payment method (Invoice) is active.
1130
-     * This used to be done automatically as part of constructing the old gateways config
1131
-     *
1132
-     * @throws \EE_Error
1133
-     */
1134
-    public static function insert_default_payment_methods()
1135
-    {
1136
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1137
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1138
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1139
-        } else {
1140
-            EEM_Payment_Method::instance()->verify_button_urls();
1141
-        }
1142
-    }
1143
-
1144
-    /**
1145
-     * insert_default_status_codes
1146
-     *
1147
-     * @access public
1148
-     * @static
1149
-     * @return void
1150
-     */
1151
-    public static function insert_default_status_codes()
1152
-    {
1153
-
1154
-        global $wpdb;
1155
-
1156
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1157
-            $table_name = EEM_Status::instance()->table();
1158
-
1159
-            $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' );";
1160
-            $wpdb->query($SQL);
1161
-
1162
-            $SQL = "INSERT INTO $table_name
1103
+										'event_espresso'
1104
+									),
1105
+									$QST_ID
1106
+								),
1107
+								'error'
1108
+							);
1109
+							continue;
1110
+						}
1111
+					}
1112
+					// add system questions to groups
1113
+					$wpdb->insert(
1114
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1115
+						array(
1116
+							'QSG_ID'    => $QSG_ID,
1117
+							'QST_ID'    => $QST_ID,
1118
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1119
+						),
1120
+						array('%d', '%d', '%d')
1121
+					);
1122
+				}
1123
+			}
1124
+		}
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * Makes sure the default payment method (Invoice) is active.
1130
+	 * This used to be done automatically as part of constructing the old gateways config
1131
+	 *
1132
+	 * @throws \EE_Error
1133
+	 */
1134
+	public static function insert_default_payment_methods()
1135
+	{
1136
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1137
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1138
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1139
+		} else {
1140
+			EEM_Payment_Method::instance()->verify_button_urls();
1141
+		}
1142
+	}
1143
+
1144
+	/**
1145
+	 * insert_default_status_codes
1146
+	 *
1147
+	 * @access public
1148
+	 * @static
1149
+	 * @return void
1150
+	 */
1151
+	public static function insert_default_status_codes()
1152
+	{
1153
+
1154
+		global $wpdb;
1155
+
1156
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1157
+			$table_name = EEM_Status::instance()->table();
1158
+
1159
+			$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' );";
1160
+			$wpdb->query($SQL);
1161
+
1162
+			$SQL = "INSERT INTO $table_name
1163 1163
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1164 1164
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1165 1165
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1199,457 +1199,457 @@  discard block
 block discarded – undo
1199 1199
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1200 1200
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1201 1201
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1202
-            $wpdb->query($SQL);
1203
-        }
1204
-    }
1205
-
1206
-
1207
-    /**
1208
-     * generate_default_message_templates
1209
-     *
1210
-     * @static
1211
-     * @throws EE_Error
1212
-     * @return bool     true means new templates were created.
1213
-     *                  false means no templates were created.
1214
-     *                  This is NOT an error flag. To check for errors you will want
1215
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1216
-     */
1217
-    public static function generate_default_message_templates()
1218
-    {
1219
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1220
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1221
-        /*
1202
+			$wpdb->query($SQL);
1203
+		}
1204
+	}
1205
+
1206
+
1207
+	/**
1208
+	 * generate_default_message_templates
1209
+	 *
1210
+	 * @static
1211
+	 * @throws EE_Error
1212
+	 * @return bool     true means new templates were created.
1213
+	 *                  false means no templates were created.
1214
+	 *                  This is NOT an error flag. To check for errors you will want
1215
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1216
+	 */
1217
+	public static function generate_default_message_templates()
1218
+	{
1219
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1220
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1221
+		/*
1222 1222
          * This first method is taking care of ensuring any default messengers
1223 1223
          * that should be made active and have templates generated are done.
1224 1224
          */
1225
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1226
-            $message_resource_manager
1227
-        );
1228
-        /**
1229
-         * This method is verifying there are no NEW default message types
1230
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1231
-         */
1232
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1233
-            $message_resource_manager
1234
-        );
1235
-        // after all is done, let's persist these changes to the db.
1236
-        $message_resource_manager->update_has_activated_messengers_option();
1237
-        $message_resource_manager->update_active_messengers_option();
1238
-        // will return true if either of these are true.  Otherwise will return false.
1239
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1240
-    }
1241
-
1242
-
1243
-
1244
-    /**
1245
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1246
-     * @return array|bool
1247
-     * @throws \EE_Error
1248
-     */
1249
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1250
-        EE_Message_Resource_Manager $message_resource_manager
1251
-    ) {
1252
-        /** @type EE_messenger[] $active_messengers */
1253
-        $active_messengers = $message_resource_manager->active_messengers();
1254
-        $installed_message_types = $message_resource_manager->installed_message_types();
1255
-        $templates_created = false;
1256
-        foreach ($active_messengers as $active_messenger) {
1257
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1258
-            $default_message_type_names_to_activate = array();
1259
-            // looping through each default message type reported by the messenger
1260
-            // and setup the actual message types to activate.
1261
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1262
-                // if already active or has already been activated before we skip
1263
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1264
-                // we also skip if the message type is not installed.
1265
-                if ($message_resource_manager->has_message_type_been_activated_for_messenger(
1266
-                    $default_message_type_name_for_messenger,
1267
-                    $active_messenger->name
1268
-                )
1269
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1270
-                        $active_messenger->name,
1271
-                        $default_message_type_name_for_messenger
1272
-                    )
1273
-                    || ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1274
-                ) {
1275
-                    continue;
1276
-                }
1277
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1278
-            }
1279
-            // let's activate!
1280
-            $message_resource_manager->ensure_message_types_are_active(
1281
-                $default_message_type_names_to_activate,
1282
-                $active_messenger->name,
1283
-                false
1284
-            );
1285
-            // activate the templates for these message types
1286
-            if (! empty($default_message_type_names_to_activate)) {
1287
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1288
-                    $active_messenger->name,
1289
-                    $default_message_type_names_for_messenger,
1290
-                    '',
1291
-                    true
1292
-                );
1293
-            }
1294
-        }
1295
-        return $templates_created;
1296
-    }
1297
-
1298
-
1299
-
1300
-    /**
1301
-     * This will activate and generate default messengers and default message types for those messengers.
1302
-     *
1303
-     * @param EE_message_Resource_Manager $message_resource_manager
1304
-     * @return array|bool  True means there were default messengers and message type templates generated.
1305
-     *                     False means that there were no templates generated
1306
-     *                     (which could simply mean there are no default message types for a messenger).
1307
-     * @throws EE_Error
1308
-     */
1309
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1310
-        EE_Message_Resource_Manager $message_resource_manager
1311
-    ) {
1312
-        /** @type EE_messenger[] $messengers_to_generate */
1313
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1314
-        $installed_message_types = $message_resource_manager->installed_message_types();
1315
-        $templates_generated = false;
1316
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1317
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1318
-            // verify the default message types match an installed message type.
1319
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1320
-                if (! isset($installed_message_types[ $name ])
1321
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1322
-                        $name,
1323
-                        $messenger_to_generate->name
1324
-                    )
1325
-                ) {
1326
-                    unset($default_message_type_names_for_messenger[ $key ]);
1327
-                }
1328
-            }
1329
-            // in previous iterations, the active_messengers option in the db
1330
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1331
-            // This comment is left here just in case we discover that we _do_ need to update before
1332
-            // passing off to create templates (after the refactor is done).
1333
-            // @todo remove this comment when determined not necessary.
1334
-            $message_resource_manager->activate_messenger(
1335
-                $messenger_to_generate->name,
1336
-                $default_message_type_names_for_messenger,
1337
-                false
1338
-            );
1339
-            // create any templates needing created (or will reactivate templates already generated as necessary).
1340
-            if (! empty($default_message_type_names_for_messenger)) {
1341
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1342
-                    $messenger_to_generate->name,
1343
-                    $default_message_type_names_for_messenger,
1344
-                    '',
1345
-                    true
1346
-                );
1347
-            }
1348
-        }
1349
-        return $templates_generated;
1350
-    }
1351
-
1352
-
1353
-    /**
1354
-     * This returns the default messengers to generate templates for on activation of EE.
1355
-     * It considers:
1356
-     * - whether a messenger is already active in the db.
1357
-     * - whether a messenger has been made active at any time in the past.
1358
-     *
1359
-     * @static
1360
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1361
-     * @return EE_messenger[]
1362
-     */
1363
-    protected static function _get_default_messengers_to_generate_on_activation(
1364
-        EE_Message_Resource_Manager $message_resource_manager
1365
-    ) {
1366
-        $active_messengers    = $message_resource_manager->active_messengers();
1367
-        $installed_messengers = $message_resource_manager->installed_messengers();
1368
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1369
-
1370
-        $messengers_to_generate = array();
1371
-        foreach ($installed_messengers as $installed_messenger) {
1372
-            // if installed messenger is a messenger that should be activated on install
1373
-            // and is not already active
1374
-            // and has never been activated
1375
-            if (! $installed_messenger->activate_on_install
1376
-                || isset($active_messengers[ $installed_messenger->name ])
1377
-                || isset($has_activated[ $installed_messenger->name ])
1378
-            ) {
1379
-                continue;
1380
-            }
1381
-            $messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1382
-        }
1383
-        return $messengers_to_generate;
1384
-    }
1385
-
1386
-
1387
-    /**
1388
-     * This simply validates active message types to ensure they actually match installed
1389
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1390
-     * rows are set inactive.
1391
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1392
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1393
-     * are still handled in here.
1394
-     *
1395
-     * @since 4.3.1
1396
-     * @return void
1397
-     */
1398
-    public static function validate_messages_system()
1399
-    {
1400
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1401
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1402
-        $message_resource_manager->validate_active_message_types_are_installed();
1403
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1404
-    }
1405
-
1406
-
1407
-    /**
1408
-     * create_no_ticket_prices_array
1409
-     *
1410
-     * @access public
1411
-     * @static
1412
-     * @return void
1413
-     */
1414
-    public static function create_no_ticket_prices_array()
1415
-    {
1416
-        // this creates an array for tracking events that have no active ticket prices created
1417
-        // this allows us to warn admins of the situation so that it can be corrected
1418
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1419
-        if (! $espresso_no_ticket_prices) {
1420
-            add_option('ee_no_ticket_prices', array(), '', false);
1421
-        }
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * plugin_deactivation
1427
-     *
1428
-     * @access public
1429
-     * @static
1430
-     * @return void
1431
-     */
1432
-    public static function plugin_deactivation()
1433
-    {
1434
-    }
1435
-
1436
-
1437
-    /**
1438
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1439
-     * (like post meta or term relations)
1440
-     *
1441
-     * @global wpdb $wpdb
1442
-     * @throws \EE_Error
1443
-     */
1444
-    public static function delete_all_espresso_cpt_data()
1445
-    {
1446
-        global $wpdb;
1447
-        // get all the CPT post_types
1448
-        $ee_post_types = array();
1449
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1450
-            if (method_exists($model_name, 'instance')) {
1451
-                $model_obj = call_user_func(array($model_name, 'instance'));
1452
-                if ($model_obj instanceof EEM_CPT_Base) {
1453
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1454
-                }
1455
-            }
1456
-        }
1457
-        // get all our CPTs
1458
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1459
-        $cpt_ids = $wpdb->get_col($query);
1460
-        // delete each post meta and term relations too
1461
-        foreach ($cpt_ids as $post_id) {
1462
-            wp_delete_post($post_id, true);
1463
-        }
1464
-    }
1465
-
1466
-    /**
1467
-     * Deletes all EE custom tables
1468
-     *
1469
-     * @return array
1470
-     */
1471
-    public static function drop_espresso_tables()
1472
-    {
1473
-        $tables = array();
1474
-        // load registry
1475
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1476
-            if (method_exists($model_name, 'instance')) {
1477
-                $model_obj = call_user_func(array($model_name, 'instance'));
1478
-                if ($model_obj instanceof EEM_Base) {
1479
-                    foreach ($model_obj->get_tables() as $table) {
1480
-                        if (strpos($table->get_table_name(), 'esp_')
1481
-                            &&
1482
-                            (
1483
-                                is_main_site()// main site? nuke them all
1484
-                                || ! $table->is_global()// not main site,but not global either. nuke it
1485
-                            )
1486
-                        ) {
1487
-                            $tables[ $table->get_table_name() ] = $table->get_table_name();
1488
-                        }
1489
-                    }
1490
-                }
1491
-            }
1492
-        }
1493
-
1494
-        // there are some tables whose models were removed.
1495
-        // they should be removed when removing all EE core's data
1496
-        $tables_without_models = array(
1497
-            'esp_promotion',
1498
-            'esp_promotion_applied',
1499
-            'esp_promotion_object',
1500
-            'esp_promotion_rule',
1501
-            'esp_rule',
1502
-        );
1503
-        foreach ($tables_without_models as $table) {
1504
-            $tables[ $table ] = $table;
1505
-        }
1506
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1507
-    }
1508
-
1509
-
1510
-
1511
-    /**
1512
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1513
-     * each table name provided has a wpdb prefix attached, and that it exists.
1514
-     * Returns the list actually deleted
1515
-     *
1516
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1517
-     * @global WPDB $wpdb
1518
-     * @param array $table_names
1519
-     * @return array of table names which we deleted
1520
-     */
1521
-    public static function drop_tables($table_names)
1522
-    {
1523
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1524
-    }
1525
-
1526
-
1527
-
1528
-    /**
1529
-     * plugin_uninstall
1530
-     *
1531
-     * @access public
1532
-     * @static
1533
-     * @param bool $remove_all
1534
-     * @return void
1535
-     */
1536
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1537
-    {
1538
-        global $wpdb;
1539
-        self::drop_espresso_tables();
1540
-        $wp_options_to_delete = array(
1541
-            'ee_no_ticket_prices'                => true,
1542
-            'ee_active_messengers'               => true,
1543
-            'ee_has_activated_messenger'         => true,
1544
-            RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1545
-            'ee_config'                          => false,
1546
-            'ee_data_migration_current_db_state' => true,
1547
-            'ee_data_migration_mapping_'         => false,
1548
-            'ee_data_migration_script_'          => false,
1549
-            'ee_data_migrations'                 => true,
1550
-            'ee_dms_map'                         => false,
1551
-            'ee_notices'                         => true,
1552
-            'lang_file_check_'                   => false,
1553
-            'ee_maintenance_mode'                => true,
1554
-            'ee_ueip_optin'                      => true,
1555
-            'ee_ueip_has_notified'               => true,
1556
-            'ee_plugin_activation_errors'        => true,
1557
-            'ee_id_mapping_from'                 => false,
1558
-            'espresso_persistent_admin_notices'  => true,
1559
-            'ee_encryption_key'                  => true,
1560
-            'pue_force_upgrade_'                 => false,
1561
-            'pue_json_error_'                    => false,
1562
-            'pue_install_key_'                   => false,
1563
-            'pue_verification_error_'            => false,
1564
-            'pu_dismissed_upgrade_'              => false,
1565
-            'external_updates-'                  => false,
1566
-            'ee_extra_data'                      => true,
1567
-            'ee_ssn_'                            => false,
1568
-            'ee_rss_'                            => false,
1569
-            'ee_rte_n_tx_'                       => false,
1570
-            'ee_pers_admin_notices'              => true,
1571
-            'ee_job_parameters_'                 => false,
1572
-            'ee_upload_directories_incomplete'   => true,
1573
-            'ee_verified_db_collations'          => true,
1574
-        );
1575
-        if (is_main_site()) {
1576
-            $wp_options_to_delete['ee_network_config'] = true;
1577
-        }
1578
-        $undeleted_options = array();
1579
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1580
-            if ($no_wildcard) {
1581
-                if (! delete_option($option_name)) {
1582
-                    $undeleted_options[] = $option_name;
1583
-                }
1584
-            } else {
1585
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1586
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1587
-                    if (! delete_option($option_name_from_wildcard)) {
1588
-                        $undeleted_options[] = $option_name_from_wildcard;
1589
-                    }
1590
-                }
1591
-            }
1592
-        }
1593
-        // also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1594
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1595
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1596
-            $db_update_sans_ee4 = array();
1597
-            foreach ($espresso_db_update as $version => $times_activated) {
1598
-                if ((string) $version[0] === '3') {// if its NON EE4
1599
-                    $db_update_sans_ee4[ $version ] = $times_activated;
1600
-                }
1601
-            }
1602
-            update_option('espresso_db_update', $db_update_sans_ee4);
1603
-        }
1604
-        $errors = '';
1605
-        if (! empty($undeleted_options)) {
1606
-            $errors .= sprintf(
1607
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1608
-                '<br/>',
1609
-                implode(',<br/>', $undeleted_options)
1610
-            );
1611
-        }
1612
-        if (! empty($errors)) {
1613
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1614
-        }
1615
-    }
1616
-
1617
-    /**
1618
-     * Gets the mysql error code from the last used query by wpdb
1619
-     *
1620
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1621
-     */
1622
-    public static function last_wpdb_error_code()
1623
-    {
1624
-        // phpcs:disable PHPCompatibility.PHP.RemovedExtensions.mysql_DeprecatedRemoved
1625
-        global $wpdb;
1626
-        if ($wpdb->use_mysqli) {
1627
-            return mysqli_errno($wpdb->dbh);
1628
-        } else {
1629
-            return mysql_errno($wpdb->dbh);
1630
-        }
1631
-        // phpcs:enable
1632
-    }
1633
-
1634
-    /**
1635
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1636
-     *
1637
-     * @global wpdb  $wpdb
1638
-     * @deprecated instead use TableAnalysis::tableExists()
1639
-     * @param string $table_name with or without $wpdb->prefix
1640
-     * @return boolean
1641
-     */
1642
-    public static function table_exists($table_name)
1643
-    {
1644
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1645
-    }
1646
-
1647
-    /**
1648
-     * Resets the cache on EEH_Activation
1649
-     */
1650
-    public static function reset()
1651
-    {
1652
-        self::$_default_creator_id                             = null;
1653
-        self::$_initialized_db_content_already_in_this_request = false;
1654
-    }
1225
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1226
+			$message_resource_manager
1227
+		);
1228
+		/**
1229
+		 * This method is verifying there are no NEW default message types
1230
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1231
+		 */
1232
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1233
+			$message_resource_manager
1234
+		);
1235
+		// after all is done, let's persist these changes to the db.
1236
+		$message_resource_manager->update_has_activated_messengers_option();
1237
+		$message_resource_manager->update_active_messengers_option();
1238
+		// will return true if either of these are true.  Otherwise will return false.
1239
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1240
+	}
1241
+
1242
+
1243
+
1244
+	/**
1245
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1246
+	 * @return array|bool
1247
+	 * @throws \EE_Error
1248
+	 */
1249
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1250
+		EE_Message_Resource_Manager $message_resource_manager
1251
+	) {
1252
+		/** @type EE_messenger[] $active_messengers */
1253
+		$active_messengers = $message_resource_manager->active_messengers();
1254
+		$installed_message_types = $message_resource_manager->installed_message_types();
1255
+		$templates_created = false;
1256
+		foreach ($active_messengers as $active_messenger) {
1257
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1258
+			$default_message_type_names_to_activate = array();
1259
+			// looping through each default message type reported by the messenger
1260
+			// and setup the actual message types to activate.
1261
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1262
+				// if already active or has already been activated before we skip
1263
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1264
+				// we also skip if the message type is not installed.
1265
+				if ($message_resource_manager->has_message_type_been_activated_for_messenger(
1266
+					$default_message_type_name_for_messenger,
1267
+					$active_messenger->name
1268
+				)
1269
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1270
+						$active_messenger->name,
1271
+						$default_message_type_name_for_messenger
1272
+					)
1273
+					|| ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1274
+				) {
1275
+					continue;
1276
+				}
1277
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1278
+			}
1279
+			// let's activate!
1280
+			$message_resource_manager->ensure_message_types_are_active(
1281
+				$default_message_type_names_to_activate,
1282
+				$active_messenger->name,
1283
+				false
1284
+			);
1285
+			// activate the templates for these message types
1286
+			if (! empty($default_message_type_names_to_activate)) {
1287
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1288
+					$active_messenger->name,
1289
+					$default_message_type_names_for_messenger,
1290
+					'',
1291
+					true
1292
+				);
1293
+			}
1294
+		}
1295
+		return $templates_created;
1296
+	}
1297
+
1298
+
1299
+
1300
+	/**
1301
+	 * This will activate and generate default messengers and default message types for those messengers.
1302
+	 *
1303
+	 * @param EE_message_Resource_Manager $message_resource_manager
1304
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1305
+	 *                     False means that there were no templates generated
1306
+	 *                     (which could simply mean there are no default message types for a messenger).
1307
+	 * @throws EE_Error
1308
+	 */
1309
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1310
+		EE_Message_Resource_Manager $message_resource_manager
1311
+	) {
1312
+		/** @type EE_messenger[] $messengers_to_generate */
1313
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1314
+		$installed_message_types = $message_resource_manager->installed_message_types();
1315
+		$templates_generated = false;
1316
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1317
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1318
+			// verify the default message types match an installed message type.
1319
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1320
+				if (! isset($installed_message_types[ $name ])
1321
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1322
+						$name,
1323
+						$messenger_to_generate->name
1324
+					)
1325
+				) {
1326
+					unset($default_message_type_names_for_messenger[ $key ]);
1327
+				}
1328
+			}
1329
+			// in previous iterations, the active_messengers option in the db
1330
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1331
+			// This comment is left here just in case we discover that we _do_ need to update before
1332
+			// passing off to create templates (after the refactor is done).
1333
+			// @todo remove this comment when determined not necessary.
1334
+			$message_resource_manager->activate_messenger(
1335
+				$messenger_to_generate->name,
1336
+				$default_message_type_names_for_messenger,
1337
+				false
1338
+			);
1339
+			// create any templates needing created (or will reactivate templates already generated as necessary).
1340
+			if (! empty($default_message_type_names_for_messenger)) {
1341
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1342
+					$messenger_to_generate->name,
1343
+					$default_message_type_names_for_messenger,
1344
+					'',
1345
+					true
1346
+				);
1347
+			}
1348
+		}
1349
+		return $templates_generated;
1350
+	}
1351
+
1352
+
1353
+	/**
1354
+	 * This returns the default messengers to generate templates for on activation of EE.
1355
+	 * It considers:
1356
+	 * - whether a messenger is already active in the db.
1357
+	 * - whether a messenger has been made active at any time in the past.
1358
+	 *
1359
+	 * @static
1360
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1361
+	 * @return EE_messenger[]
1362
+	 */
1363
+	protected static function _get_default_messengers_to_generate_on_activation(
1364
+		EE_Message_Resource_Manager $message_resource_manager
1365
+	) {
1366
+		$active_messengers    = $message_resource_manager->active_messengers();
1367
+		$installed_messengers = $message_resource_manager->installed_messengers();
1368
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1369
+
1370
+		$messengers_to_generate = array();
1371
+		foreach ($installed_messengers as $installed_messenger) {
1372
+			// if installed messenger is a messenger that should be activated on install
1373
+			// and is not already active
1374
+			// and has never been activated
1375
+			if (! $installed_messenger->activate_on_install
1376
+				|| isset($active_messengers[ $installed_messenger->name ])
1377
+				|| isset($has_activated[ $installed_messenger->name ])
1378
+			) {
1379
+				continue;
1380
+			}
1381
+			$messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1382
+		}
1383
+		return $messengers_to_generate;
1384
+	}
1385
+
1386
+
1387
+	/**
1388
+	 * This simply validates active message types to ensure they actually match installed
1389
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1390
+	 * rows are set inactive.
1391
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1392
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1393
+	 * are still handled in here.
1394
+	 *
1395
+	 * @since 4.3.1
1396
+	 * @return void
1397
+	 */
1398
+	public static function validate_messages_system()
1399
+	{
1400
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1401
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1402
+		$message_resource_manager->validate_active_message_types_are_installed();
1403
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1404
+	}
1405
+
1406
+
1407
+	/**
1408
+	 * create_no_ticket_prices_array
1409
+	 *
1410
+	 * @access public
1411
+	 * @static
1412
+	 * @return void
1413
+	 */
1414
+	public static function create_no_ticket_prices_array()
1415
+	{
1416
+		// this creates an array for tracking events that have no active ticket prices created
1417
+		// this allows us to warn admins of the situation so that it can be corrected
1418
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1419
+		if (! $espresso_no_ticket_prices) {
1420
+			add_option('ee_no_ticket_prices', array(), '', false);
1421
+		}
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * plugin_deactivation
1427
+	 *
1428
+	 * @access public
1429
+	 * @static
1430
+	 * @return void
1431
+	 */
1432
+	public static function plugin_deactivation()
1433
+	{
1434
+	}
1435
+
1436
+
1437
+	/**
1438
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1439
+	 * (like post meta or term relations)
1440
+	 *
1441
+	 * @global wpdb $wpdb
1442
+	 * @throws \EE_Error
1443
+	 */
1444
+	public static function delete_all_espresso_cpt_data()
1445
+	{
1446
+		global $wpdb;
1447
+		// get all the CPT post_types
1448
+		$ee_post_types = array();
1449
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1450
+			if (method_exists($model_name, 'instance')) {
1451
+				$model_obj = call_user_func(array($model_name, 'instance'));
1452
+				if ($model_obj instanceof EEM_CPT_Base) {
1453
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1454
+				}
1455
+			}
1456
+		}
1457
+		// get all our CPTs
1458
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1459
+		$cpt_ids = $wpdb->get_col($query);
1460
+		// delete each post meta and term relations too
1461
+		foreach ($cpt_ids as $post_id) {
1462
+			wp_delete_post($post_id, true);
1463
+		}
1464
+	}
1465
+
1466
+	/**
1467
+	 * Deletes all EE custom tables
1468
+	 *
1469
+	 * @return array
1470
+	 */
1471
+	public static function drop_espresso_tables()
1472
+	{
1473
+		$tables = array();
1474
+		// load registry
1475
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1476
+			if (method_exists($model_name, 'instance')) {
1477
+				$model_obj = call_user_func(array($model_name, 'instance'));
1478
+				if ($model_obj instanceof EEM_Base) {
1479
+					foreach ($model_obj->get_tables() as $table) {
1480
+						if (strpos($table->get_table_name(), 'esp_')
1481
+							&&
1482
+							(
1483
+								is_main_site()// main site? nuke them all
1484
+								|| ! $table->is_global()// not main site,but not global either. nuke it
1485
+							)
1486
+						) {
1487
+							$tables[ $table->get_table_name() ] = $table->get_table_name();
1488
+						}
1489
+					}
1490
+				}
1491
+			}
1492
+		}
1493
+
1494
+		// there are some tables whose models were removed.
1495
+		// they should be removed when removing all EE core's data
1496
+		$tables_without_models = array(
1497
+			'esp_promotion',
1498
+			'esp_promotion_applied',
1499
+			'esp_promotion_object',
1500
+			'esp_promotion_rule',
1501
+			'esp_rule',
1502
+		);
1503
+		foreach ($tables_without_models as $table) {
1504
+			$tables[ $table ] = $table;
1505
+		}
1506
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1507
+	}
1508
+
1509
+
1510
+
1511
+	/**
1512
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1513
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1514
+	 * Returns the list actually deleted
1515
+	 *
1516
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1517
+	 * @global WPDB $wpdb
1518
+	 * @param array $table_names
1519
+	 * @return array of table names which we deleted
1520
+	 */
1521
+	public static function drop_tables($table_names)
1522
+	{
1523
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1524
+	}
1525
+
1526
+
1527
+
1528
+	/**
1529
+	 * plugin_uninstall
1530
+	 *
1531
+	 * @access public
1532
+	 * @static
1533
+	 * @param bool $remove_all
1534
+	 * @return void
1535
+	 */
1536
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1537
+	{
1538
+		global $wpdb;
1539
+		self::drop_espresso_tables();
1540
+		$wp_options_to_delete = array(
1541
+			'ee_no_ticket_prices'                => true,
1542
+			'ee_active_messengers'               => true,
1543
+			'ee_has_activated_messenger'         => true,
1544
+			RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1545
+			'ee_config'                          => false,
1546
+			'ee_data_migration_current_db_state' => true,
1547
+			'ee_data_migration_mapping_'         => false,
1548
+			'ee_data_migration_script_'          => false,
1549
+			'ee_data_migrations'                 => true,
1550
+			'ee_dms_map'                         => false,
1551
+			'ee_notices'                         => true,
1552
+			'lang_file_check_'                   => false,
1553
+			'ee_maintenance_mode'                => true,
1554
+			'ee_ueip_optin'                      => true,
1555
+			'ee_ueip_has_notified'               => true,
1556
+			'ee_plugin_activation_errors'        => true,
1557
+			'ee_id_mapping_from'                 => false,
1558
+			'espresso_persistent_admin_notices'  => true,
1559
+			'ee_encryption_key'                  => true,
1560
+			'pue_force_upgrade_'                 => false,
1561
+			'pue_json_error_'                    => false,
1562
+			'pue_install_key_'                   => false,
1563
+			'pue_verification_error_'            => false,
1564
+			'pu_dismissed_upgrade_'              => false,
1565
+			'external_updates-'                  => false,
1566
+			'ee_extra_data'                      => true,
1567
+			'ee_ssn_'                            => false,
1568
+			'ee_rss_'                            => false,
1569
+			'ee_rte_n_tx_'                       => false,
1570
+			'ee_pers_admin_notices'              => true,
1571
+			'ee_job_parameters_'                 => false,
1572
+			'ee_upload_directories_incomplete'   => true,
1573
+			'ee_verified_db_collations'          => true,
1574
+		);
1575
+		if (is_main_site()) {
1576
+			$wp_options_to_delete['ee_network_config'] = true;
1577
+		}
1578
+		$undeleted_options = array();
1579
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1580
+			if ($no_wildcard) {
1581
+				if (! delete_option($option_name)) {
1582
+					$undeleted_options[] = $option_name;
1583
+				}
1584
+			} else {
1585
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1586
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1587
+					if (! delete_option($option_name_from_wildcard)) {
1588
+						$undeleted_options[] = $option_name_from_wildcard;
1589
+					}
1590
+				}
1591
+			}
1592
+		}
1593
+		// also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1594
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1595
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1596
+			$db_update_sans_ee4 = array();
1597
+			foreach ($espresso_db_update as $version => $times_activated) {
1598
+				if ((string) $version[0] === '3') {// if its NON EE4
1599
+					$db_update_sans_ee4[ $version ] = $times_activated;
1600
+				}
1601
+			}
1602
+			update_option('espresso_db_update', $db_update_sans_ee4);
1603
+		}
1604
+		$errors = '';
1605
+		if (! empty($undeleted_options)) {
1606
+			$errors .= sprintf(
1607
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1608
+				'<br/>',
1609
+				implode(',<br/>', $undeleted_options)
1610
+			);
1611
+		}
1612
+		if (! empty($errors)) {
1613
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1614
+		}
1615
+	}
1616
+
1617
+	/**
1618
+	 * Gets the mysql error code from the last used query by wpdb
1619
+	 *
1620
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1621
+	 */
1622
+	public static function last_wpdb_error_code()
1623
+	{
1624
+		// phpcs:disable PHPCompatibility.PHP.RemovedExtensions.mysql_DeprecatedRemoved
1625
+		global $wpdb;
1626
+		if ($wpdb->use_mysqli) {
1627
+			return mysqli_errno($wpdb->dbh);
1628
+		} else {
1629
+			return mysql_errno($wpdb->dbh);
1630
+		}
1631
+		// phpcs:enable
1632
+	}
1633
+
1634
+	/**
1635
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1636
+	 *
1637
+	 * @global wpdb  $wpdb
1638
+	 * @deprecated instead use TableAnalysis::tableExists()
1639
+	 * @param string $table_name with or without $wpdb->prefix
1640
+	 * @return boolean
1641
+	 */
1642
+	public static function table_exists($table_name)
1643
+	{
1644
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1645
+	}
1646
+
1647
+	/**
1648
+	 * Resets the cache on EEH_Activation
1649
+	 */
1650
+	public static function reset()
1651
+	{
1652
+		self::$_default_creator_id                             = null;
1653
+		self::$_initialized_db_content_already_in_this_request = false;
1654
+	}
1655 1655
 }
Please login to merge, or discard this patch.
Spacing   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
      */
55 55
     public static function getTableAnalysis()
56 56
     {
57
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
57
+        if ( ! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
58 58
             self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
59 59
         }
60 60
         return self::$table_analysis;
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
      */
67 67
     public static function getTableManager()
68 68
     {
69
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
69
+        if ( ! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
70 70
             self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
71 71
         }
72 72
         return self::$table_manager;
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
         if ($which_to_include === 'old') {
181 181
             $cron_tasks = array_filter(
182 182
                 $cron_tasks,
183
-                function ($value) {
183
+                function($value) {
184 184
                     return $value === EEH_Activation::cron_task_no_longer_in_use;
185 185
                 }
186 186
             );
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
     {
211 211
 
212 212
         foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
213
-            if (! wp_next_scheduled($hook_name)) {
213
+            if ( ! wp_next_scheduled($hook_name)) {
214 214
                 /**
215 215
                  * This allows client code to define the initial start timestamp for this schedule.
216 216
                  */
@@ -261,15 +261,15 @@  discard block
 block discarded – undo
261 261
         foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
262 262
             if (is_array($hooks_to_fire_at_time)) {
263 263
                 foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
264
-                    if (isset($ee_cron_tasks_to_remove[ $hook_name ])
265
-                        && is_array($ee_cron_tasks_to_remove[ $hook_name ])
264
+                    if (isset($ee_cron_tasks_to_remove[$hook_name])
265
+                        && is_array($ee_cron_tasks_to_remove[$hook_name])
266 266
                     ) {
267
-                        unset($crons[ $timestamp ][ $hook_name ]);
267
+                        unset($crons[$timestamp][$hook_name]);
268 268
                     }
269 269
                 }
270 270
                 // also take care of any empty cron timestamps.
271 271
                 if (empty($hooks_to_fire_at_time)) {
272
-                    unset($crons[ $timestamp ]);
272
+                    unset($crons[$timestamp]);
273 273
                 }
274 274
             }
275 275
         }
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
             3
315 315
         );
316 316
         // EE_Config::reset();
317
-        if (! EE_Config::logging_enabled()) {
317
+        if ( ! EE_Config::logging_enabled()) {
318 318
             delete_option(EE_Config::LOG_NAME);
319 319
         }
320 320
     }
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
     public static function load_calendar_config()
330 330
     {
331 331
         // grab array of all plugin folders and loop thru it
332
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
332
+        $plugins = glob(WP_PLUGIN_DIR.DS.'*', GLOB_ONLYDIR);
333 333
         if (empty($plugins)) {
334 334
             return;
335 335
         }
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
                 || strpos($plugin, 'calendar') !== false
346 346
             ) {
347 347
                 // this is what we are looking for
348
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
348
+                $calendar_config = $plugin_path.DS.'EE_Calendar_Config.php';
349 349
                 // does it exist in this folder ?
350 350
                 if (is_readable($calendar_config)) {
351 351
                     // YEAH! let's load it
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
             ) {
473 473
                 // update Config with post ID
474 474
                 $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
475
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
475
+                if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
476 476
                     $msg = __(
477 477
                         'The Event Espresso critical page configuration settings could not be updated.',
478 478
                         'event_espresso'
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
                         'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
496 496
                         'event_espresso'
497 497
                     ),
498
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
498
+                    '<a href="'.admin_url('admin.php?page=espresso_general_settings&action=critical_pages').'">'
499 499
                     . __('Event Espresso Critical Pages Settings', 'event_espresso')
500 500
                     . '</a>'
501 501
                 )
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
     public static function get_page_by_ee_shortcode($ee_shortcode)
522 522
     {
523 523
         global $wpdb;
524
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
524
+        $shortcode_and_opening_bracket = '['.$ee_shortcode;
525 525
         $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
526 526
         if ($post_id) {
527 527
             return get_post($post_id);
@@ -547,11 +547,11 @@  discard block
 block discarded – undo
547 547
             'post_status'    => 'publish',
548 548
             'post_type'      => 'page',
549 549
             'comment_status' => 'closed',
550
-            'post_content'   => '[' . $critical_page['code'] . ']',
550
+            'post_content'   => '['.$critical_page['code'].']',
551 551
         );
552 552
 
553 553
         $post_id = wp_insert_post($post_args);
554
-        if (! $post_id) {
554
+        if ( ! $post_id) {
555 555
             $msg = sprintf(
556 556
                 __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
557 557
                 $critical_page['name']
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
             return $critical_page;
561 561
         }
562 562
         // get newly created post's details
563
-        if (! $critical_page['post'] = get_post($post_id)) {
563
+        if ( ! $critical_page['post'] = get_post($post_id)) {
564 564
             $msg = sprintf(
565 565
                 __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
566 566
                 $critical_page['name']
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
     public static function get_default_creator_id()
586 586
     {
587 587
         global $wpdb;
588
-        if (! empty(self::$_default_creator_id)) {
588
+        if ( ! empty(self::$_default_creator_id)) {
589 589
             return self::$_default_creator_id;
590 590
         }/**/
591 591
         $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
         $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
602 602
         $query = $wpdb->prepare(
603 603
             "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
604
-            '%' . $role_to_check . '%'
604
+            '%'.$role_to_check.'%'
605 605
         );
606 606
         $user_id = $wpdb->get_var($query);
607 607
         $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
@@ -640,8 +640,8 @@  discard block
 block discarded – undo
640 640
             return;
641 641
         }
642 642
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
643
-        if (! function_exists('dbDelta')) {
644
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
643
+        if ( ! function_exists('dbDelta')) {
644
+            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
645 645
         }
646 646
         $tableAnalysis = \EEH_Activation::getTableAnalysis();
647 647
         $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
@@ -650,9 +650,9 @@  discard block
 block discarded – undo
650 650
             // ok, delete the table... but ONLY if it's empty
651 651
             $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
652 652
             // table is NOT empty, are you SURE you want to delete this table ???
653
-            if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
653
+            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
654 654
                 \EEH_Activation::getTableManager()->dropTable($wp_table_name);
655
-            } elseif (! $deleted_safely) {
655
+            } elseif ( ! $deleted_safely) {
656 656
                 // so we should be more cautious rather than just dropping tables so easily
657 657
                 error_log(
658 658
                     sprintf(
@@ -852,13 +852,13 @@  discard block
 block discarded – undo
852 852
             // reset values array
853 853
             $QSG_values = array();
854 854
             // 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)
855
-            if (! in_array("$QSG_system", $question_groups)) {
855
+            if ( ! in_array("$QSG_system", $question_groups)) {
856 856
                 // add it
857 857
                 switch ($QSG_system) {
858 858
                     case 1:
859 859
                         $QSG_values = array(
860 860
                             'QSG_name'            => __('Personal Information', 'event_espresso'),
861
-                            'QSG_identifier'      => 'personal-information-' . time(),
861
+                            'QSG_identifier'      => 'personal-information-'.time(),
862 862
                             'QSG_desc'            => '',
863 863
                             'QSG_order'           => 1,
864 864
                             'QSG_show_group_name' => 1,
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
                     case 2:
871 871
                         $QSG_values = array(
872 872
                             'QSG_name'            => __('Address Information', 'event_espresso'),
873
-                            'QSG_identifier'      => 'address-information-' . time(),
873
+                            'QSG_identifier'      => 'address-information-'.time(),
874 874
                             'QSG_desc'            => '',
875 875
                             'QSG_order'           => 2,
876 876
                             'QSG_show_group_name' => 1,
@@ -881,14 +881,14 @@  discard block
 block discarded – undo
881 881
                         break;
882 882
                 }
883 883
                 // make sure we have some values before inserting them
884
-                if (! empty($QSG_values)) {
884
+                if ( ! empty($QSG_values)) {
885 885
                     // insert system question
886 886
                     $wpdb->insert(
887 887
                         $table_name,
888 888
                         $QSG_values,
889 889
                         array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
890 890
                     );
891
-                    $QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
891
+                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
892 892
                 }
893 893
             }
894 894
         }
@@ -918,7 +918,7 @@  discard block
 block discarded – undo
918 918
             // reset values array
919 919
             $QST_values = array();
920 920
             // if we don't have what we should have
921
-            if (! in_array($QST_system, $questions)) {
921
+            if ( ! in_array($QST_system, $questions)) {
922 922
                 // add it
923 923
                 switch ($QST_system) {
924 924
                     case 'fname':
@@ -1070,7 +1070,7 @@  discard block
 block discarded – undo
1070 1070
                         );
1071 1071
                         break;
1072 1072
                 }
1073
-                if (! empty($QST_values)) {
1073
+                if ( ! empty($QST_values)) {
1074 1074
                     // insert system question
1075 1075
                     $wpdb->insert(
1076 1076
                         $table_name,
@@ -1084,8 +1084,8 @@  discard block
 block discarded – undo
1084 1084
                     } else {
1085 1085
                         $system_question_we_want = EEM_Question_Group::system_address;
1086 1086
                     }
1087
-                    if (isset($QSG_IDs[ $system_question_we_want ])) {
1088
-                        $QSG_ID = $QSG_IDs[ $system_question_we_want ];
1087
+                    if (isset($QSG_IDs[$system_question_we_want])) {
1088
+                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1089 1089
                     } else {
1090 1090
                         $id_col = EEM_Question_Group::instance()
1091 1091
                                                     ->get_col(array(array('QSG_system' => $system_question_we_want)));
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
      */
1134 1134
     public static function insert_default_payment_methods()
1135 1135
     {
1136
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1136
+        if ( ! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1137 1137
             EE_Registry::instance()->load_lib('Payment_Method_Manager');
1138 1138
             EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1139 1139
         } else {
@@ -1270,7 +1270,7 @@  discard block
 block discarded – undo
1270 1270
                         $active_messenger->name,
1271 1271
                         $default_message_type_name_for_messenger
1272 1272
                     )
1273
-                    || ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1273
+                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1274 1274
                 ) {
1275 1275
                     continue;
1276 1276
                 }
@@ -1283,7 +1283,7 @@  discard block
 block discarded – undo
1283 1283
                 false
1284 1284
             );
1285 1285
             // activate the templates for these message types
1286
-            if (! empty($default_message_type_names_to_activate)) {
1286
+            if ( ! empty($default_message_type_names_to_activate)) {
1287 1287
                 $templates_created = EEH_MSG_Template::generate_new_templates(
1288 1288
                     $active_messenger->name,
1289 1289
                     $default_message_type_names_for_messenger,
@@ -1317,13 +1317,13 @@  discard block
 block discarded – undo
1317 1317
             $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1318 1318
             // verify the default message types match an installed message type.
1319 1319
             foreach ($default_message_type_names_for_messenger as $key => $name) {
1320
-                if (! isset($installed_message_types[ $name ])
1320
+                if ( ! isset($installed_message_types[$name])
1321 1321
                     || $message_resource_manager->has_message_type_been_activated_for_messenger(
1322 1322
                         $name,
1323 1323
                         $messenger_to_generate->name
1324 1324
                     )
1325 1325
                 ) {
1326
-                    unset($default_message_type_names_for_messenger[ $key ]);
1326
+                    unset($default_message_type_names_for_messenger[$key]);
1327 1327
                 }
1328 1328
             }
1329 1329
             // in previous iterations, the active_messengers option in the db
@@ -1337,7 +1337,7 @@  discard block
 block discarded – undo
1337 1337
                 false
1338 1338
             );
1339 1339
             // create any templates needing created (or will reactivate templates already generated as necessary).
1340
-            if (! empty($default_message_type_names_for_messenger)) {
1340
+            if ( ! empty($default_message_type_names_for_messenger)) {
1341 1341
                 $templates_generated = EEH_MSG_Template::generate_new_templates(
1342 1342
                     $messenger_to_generate->name,
1343 1343
                     $default_message_type_names_for_messenger,
@@ -1372,13 +1372,13 @@  discard block
 block discarded – undo
1372 1372
             // if installed messenger is a messenger that should be activated on install
1373 1373
             // and is not already active
1374 1374
             // and has never been activated
1375
-            if (! $installed_messenger->activate_on_install
1376
-                || isset($active_messengers[ $installed_messenger->name ])
1377
-                || isset($has_activated[ $installed_messenger->name ])
1375
+            if ( ! $installed_messenger->activate_on_install
1376
+                || isset($active_messengers[$installed_messenger->name])
1377
+                || isset($has_activated[$installed_messenger->name])
1378 1378
             ) {
1379 1379
                 continue;
1380 1380
             }
1381
-            $messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1381
+            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1382 1382
         }
1383 1383
         return $messengers_to_generate;
1384 1384
     }
@@ -1416,7 +1416,7 @@  discard block
 block discarded – undo
1416 1416
         // this creates an array for tracking events that have no active ticket prices created
1417 1417
         // this allows us to warn admins of the situation so that it can be corrected
1418 1418
         $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1419
-        if (! $espresso_no_ticket_prices) {
1419
+        if ( ! $espresso_no_ticket_prices) {
1420 1420
             add_option('ee_no_ticket_prices', array(), '', false);
1421 1421
         }
1422 1422
     }
@@ -1455,7 +1455,7 @@  discard block
 block discarded – undo
1455 1455
             }
1456 1456
         }
1457 1457
         // get all our CPTs
1458
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1458
+        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (".implode(",", $ee_post_types).")";
1459 1459
         $cpt_ids = $wpdb->get_col($query);
1460 1460
         // delete each post meta and term relations too
1461 1461
         foreach ($cpt_ids as $post_id) {
@@ -1484,7 +1484,7 @@  discard block
 block discarded – undo
1484 1484
                                 || ! $table->is_global()// not main site,but not global either. nuke it
1485 1485
                             )
1486 1486
                         ) {
1487
-                            $tables[ $table->get_table_name() ] = $table->get_table_name();
1487
+                            $tables[$table->get_table_name()] = $table->get_table_name();
1488 1488
                         }
1489 1489
                     }
1490 1490
                 }
@@ -1501,7 +1501,7 @@  discard block
 block discarded – undo
1501 1501
             'esp_rule',
1502 1502
         );
1503 1503
         foreach ($tables_without_models as $table) {
1504
-            $tables[ $table ] = $table;
1504
+            $tables[$table] = $table;
1505 1505
         }
1506 1506
         return \EEH_Activation::getTableManager()->dropTables($tables);
1507 1507
     }
@@ -1578,13 +1578,13 @@  discard block
 block discarded – undo
1578 1578
         $undeleted_options = array();
1579 1579
         foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1580 1580
             if ($no_wildcard) {
1581
-                if (! delete_option($option_name)) {
1581
+                if ( ! delete_option($option_name)) {
1582 1582
                     $undeleted_options[] = $option_name;
1583 1583
                 }
1584 1584
             } else {
1585 1585
                 $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1586 1586
                 foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1587
-                    if (! delete_option($option_name_from_wildcard)) {
1587
+                    if ( ! delete_option($option_name_from_wildcard)) {
1588 1588
                         $undeleted_options[] = $option_name_from_wildcard;
1589 1589
                     }
1590 1590
                 }
@@ -1596,20 +1596,20 @@  discard block
 block discarded – undo
1596 1596
             $db_update_sans_ee4 = array();
1597 1597
             foreach ($espresso_db_update as $version => $times_activated) {
1598 1598
                 if ((string) $version[0] === '3') {// if its NON EE4
1599
-                    $db_update_sans_ee4[ $version ] = $times_activated;
1599
+                    $db_update_sans_ee4[$version] = $times_activated;
1600 1600
                 }
1601 1601
             }
1602 1602
             update_option('espresso_db_update', $db_update_sans_ee4);
1603 1603
         }
1604 1604
         $errors = '';
1605
-        if (! empty($undeleted_options)) {
1605
+        if ( ! empty($undeleted_options)) {
1606 1606
             $errors .= sprintf(
1607 1607
                 __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1608 1608
                 '<br/>',
1609 1609
                 implode(',<br/>', $undeleted_options)
1610 1610
             );
1611 1611
         }
1612
-        if (! empty($errors)) {
1612
+        if ( ! empty($errors)) {
1613 1613
             EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1614 1614
         }
1615 1615
     }
Please login to merge, or discard this patch.
core/db_models/EEM_Datetime.model.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -529,7 +529,7 @@
 block discarded – undo
529 529
     /**
530 530
      * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
531 531
      *
532
-     * @param  array $stati_to_include If included you can restrict the statuses we return counts for by including the
532
+     * @param  string[] $stati_to_include If included you can restrict the statuses we return counts for by including the
533 533
      *                                 stati you want counts for as values in the array.  An empty array returns counts
534 534
      *                                 for all valid stati.
535 535
      * @param  array $query_params     If included can be used to refine the conditions for returning the count (i.e.
Please login to merge, or discard this patch.
Indentation   +743 added lines, -743 removed lines patch added patch discarded remove patch
@@ -13,747 +13,747 @@
 block discarded – undo
13 13
 class EEM_Datetime extends EEM_Soft_Delete_Base
14 14
 {
15 15
 
16
-    /**
17
-     * @var EEM_Datetime $_instance
18
-     */
19
-    protected static $_instance;
20
-
21
-
22
-    /**
23
-     * private constructor to prevent direct creation
24
-     *
25
-     * @param string $timezone A string representing the timezone we want to set for returned Date Time Strings
26
-     *                         (and any incoming timezone data that gets saved).
27
-     *                         Note this just sends the timezone info to the date time model field objects.
28
-     *                         Default is NULL
29
-     *                         (and will be assumed using the set timezone in the 'timezone_string' wp option)
30
-     * @throws EE_Error
31
-     * @throws InvalidArgumentException
32
-     * @throws InvalidArgumentException
33
-     */
34
-    protected function __construct($timezone)
35
-    {
36
-        $this->singular_item           = esc_html__('Datetime', 'event_espresso');
37
-        $this->plural_item             = esc_html__('Datetimes', 'event_espresso');
38
-        $this->_tables                 = array(
39
-            'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
40
-        );
41
-        $this->_fields                 = array(
42
-            'Datetime' => array(
43
-                'DTT_ID'          => new EE_Primary_Key_Int_Field(
44
-                    'DTT_ID',
45
-                    esc_html__('Datetime ID', 'event_espresso')
46
-                ),
47
-                'EVT_ID'          => new EE_Foreign_Key_Int_Field(
48
-                    'EVT_ID',
49
-                    esc_html__('Event ID', 'event_espresso'),
50
-                    false,
51
-                    0,
52
-                    'Event'
53
-                ),
54
-                'DTT_name'        => new EE_Plain_Text_Field(
55
-                    'DTT_name',
56
-                    esc_html__('Datetime Name', 'event_espresso'),
57
-                    false,
58
-                    ''
59
-                ),
60
-                'DTT_description' => new EE_Post_Content_Field(
61
-                    'DTT_description',
62
-                    esc_html__('Description for Datetime', 'event_espresso'),
63
-                    false,
64
-                    ''
65
-                ),
66
-                'DTT_EVT_start'   => new EE_Datetime_Field(
67
-                    'DTT_EVT_start',
68
-                    esc_html__('Start time/date of Event', 'event_espresso'),
69
-                    false,
70
-                    EE_Datetime_Field::now,
71
-                    $timezone
72
-                ),
73
-                'DTT_EVT_end'     => new EE_Datetime_Field(
74
-                    'DTT_EVT_end',
75
-                    esc_html__('End time/date of Event', 'event_espresso'),
76
-                    false,
77
-                    EE_Datetime_Field::now,
78
-                    $timezone
79
-                ),
80
-                'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
81
-                    'DTT_reg_limit',
82
-                    esc_html__('Registration Limit for this time', 'event_espresso'),
83
-                    true,
84
-                    EE_INF
85
-                ),
86
-                'DTT_sold'        => new EE_Integer_Field(
87
-                    'DTT_sold',
88
-                    esc_html__('How many sales for this Datetime that have occurred', 'event_espresso'),
89
-                    true,
90
-                    0
91
-                ),
92
-                'DTT_reserved'    => new EE_Integer_Field(
93
-                    'DTT_reserved',
94
-                    esc_html__('Quantity of tickets reserved, but not yet fully purchased', 'event_espresso'),
95
-                    false,
96
-                    0
97
-                ),
98
-                'DTT_is_primary'  => new EE_Boolean_Field(
99
-                    'DTT_is_primary',
100
-                    esc_html__('Flag indicating datetime is primary one for event', 'event_espresso'),
101
-                    false,
102
-                    false
103
-                ),
104
-                'DTT_order'       => new EE_Integer_Field(
105
-                    'DTT_order',
106
-                    esc_html__('The order in which the Datetime is displayed', 'event_espresso'),
107
-                    false,
108
-                    0
109
-                ),
110
-                'DTT_parent'      => new EE_Integer_Field(
111
-                    'DTT_parent',
112
-                    esc_html__('Indicates what DTT_ID is the parent of this DTT_ID', 'event_espresso'),
113
-                    true,
114
-                    0
115
-                ),
116
-                'DTT_deleted'     => new EE_Trashed_Flag_Field(
117
-                    'DTT_deleted',
118
-                    esc_html__('Flag indicating datetime is archived', 'event_espresso'),
119
-                    false,
120
-                    false
121
-                ),
122
-            ),
123
-        );
124
-        $this->_model_relations        = array(
125
-            'Ticket'  => new EE_HABTM_Relation('Datetime_Ticket'),
126
-            'Event'   => new EE_Belongs_To_Relation(),
127
-            'Checkin' => new EE_Has_Many_Relation(),
128
-            'Datetime_Ticket' => new EE_Has_Many_Relation(),
129
-        );
130
-        $path_to_event_model = 'Event';
131
-        $this->model_chain_to_password = $path_to_event_model;
132
-        $this->_model_chain_to_wp_user = $path_to_event_model;
133
-        // this model is generally available for reading
134
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Event_Related_Public(
135
-            $path_to_event_model
136
-        );
137
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
138
-            $path_to_event_model
139
-        );
140
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       = new EE_Restriction_Generator_Event_Related_Protected(
141
-            $path_to_event_model
142
-        );
143
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     = new EE_Restriction_Generator_Event_Related_Protected(
144
-            $path_to_event_model,
145
-            EEM_Base::caps_edit
146
-        );
147
-        parent::__construct($timezone);
148
-    }
149
-
150
-
151
-    /**
152
-     * create new blank datetime
153
-     *
154
-     * @access public
155
-     * @return EE_Datetime[] array on success, FALSE on fail
156
-     * @throws EE_Error
157
-     * @throws InvalidArgumentException
158
-     * @throws InvalidDataTypeException
159
-     * @throws ReflectionException
160
-     * @throws InvalidInterfaceException
161
-     */
162
-    public function create_new_blank_datetime()
163
-    {
164
-        // makes sure timezone is always set.
165
-        $timezone_string = $this->get_timezone();
166
-        /**
167
-         * Filters the initial start date for the new datetime.
168
-         * Any time included in this value will be overridden later so use additional filters to modify the time.
169
-         *
170
-         * @param int $start_date Unixtimestamp representing now + 30 days in seconds.
171
-         * @return int unixtimestamp
172
-         */
173
-        $start_date = apply_filters(
174
-            'FHEE__EEM_Datetime__create_new_blank_datetime__start_date',
175
-            $this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS
176
-        );
177
-        /**
178
-         * Filters the initial end date for the new datetime.
179
-         * Any time included in this value will be overridden later so use additional filters to modify the time.
180
-         *
181
-         * @param int $end_data Unixtimestamp representing now + 30 days in seconds.
182
-         * @return int unixtimestamp
183
-         */
184
-        $end_date = apply_filters(
185
-            'FHEE__EEM_Datetime__create_new_blank_datetime__end_date',
186
-            $this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS
187
-        );
188
-        $blank_datetime = EE_Datetime::new_instance(
189
-            array(
190
-                'DTT_EVT_start' => $start_date,
191
-                'DTT_EVT_end'   => $end_date,
192
-                'DTT_order'     => 1,
193
-                'DTT_reg_limit' => EE_INF,
194
-            ),
195
-            $timezone_string
196
-        );
197
-        /**
198
-         * Filters the initial start time and format for the new EE_Datetime instance.
199
-         *
200
-         * @param array $start_time An array having size 2.  First element is the time, second element is the time
201
-         *                          format.
202
-         * @return array
203
-         */
204
-        $start_time = apply_filters(
205
-            'FHEE__EEM_Datetime__create_new_blank_datetime__start_time',
206
-            ['8am', 'ga']
207
-        );
208
-        /**
209
-         * Filters the initial end time and format for the new EE_Datetime instance.
210
-         *
211
-         * @param array $end_time An array having size 2.  First element is the time, second element is the time
212
-         *                        format
213
-         * @return array
214
-         */
215
-        $end_time = apply_filters(
216
-            'FHEE__EEM_Datetime__create_new_blank_datetime__end_time',
217
-            ['5pm', 'ga']
218
-        );
219
-        $this->validateStartAndEndTimeForBlankDate($start_time, $end_time);
220
-        $blank_datetime->set_start_time(
221
-            $this->convert_datetime_for_query(
222
-                'DTT_EVT_start',
223
-                $start_time[0],
224
-                $start_time[1],
225
-                $timezone_string
226
-            )
227
-        );
228
-        $blank_datetime->set_end_time(
229
-            $this->convert_datetime_for_query(
230
-                'DTT_EVT_end',
231
-                $end_time[0],
232
-                $end_time[1],
233
-                $timezone_string
234
-            )
235
-        );
236
-        return array($blank_datetime);
237
-    }
238
-
239
-
240
-    /**
241
-     * Validates whether the start_time and end_time are in the expected format.
242
-     * @param array $start_time
243
-     * @param array $end_time
244
-     * @throws InvalidArgumentException
245
-     * @throws InvalidDataTypeException
246
-     */
247
-    private function validateStartAndEndTimeForBlankDate($start_time, $end_time)
248
-    {
249
-        if (! is_array($start_time)) {
250
-            throw new InvalidDataTypeException('start_time', $start_time, 'array');
251
-        }
252
-        if (! is_array($end_time)) {
253
-            throw new InvalidDataTypeException('end_time', $end_time, 'array');
254
-        }
255
-        if (count($start_time) !== 2) {
256
-            throw new InvalidArgumentException(
257
-                sprintf(
258
-                    'The variable %1$s is expected to be an array with two elements.  The first item in the '
259
-                    . 'array should be a valid time string, the second item in the array should be a valid time format',
260
-                    '$start_time'
261
-                )
262
-            );
263
-        }
264
-        if (count($end_time) !== 2) {
265
-            throw new InvalidArgumentException(
266
-                sprintf(
267
-                    'The variable %1$s is expected to be an array with two elements.  The first item in the '
268
-                    . 'array should be a valid time string, the second item in the array should be a valid time format',
269
-                    '$end_time'
270
-                )
271
-            );
272
-        }
273
-    }
274
-
275
-
276
-    /**
277
-     * get event start date from db
278
-     *
279
-     * @access public
280
-     * @param  int $EVT_ID
281
-     * @return EE_Datetime[] array on success, FALSE on fail
282
-     * @throws EE_Error
283
-     */
284
-    public function get_all_event_dates($EVT_ID = 0)
285
-    {
286
-        if (! $EVT_ID) { // on add_new_event event_id gets set to 0
287
-            return $this->create_new_blank_datetime();
288
-        }
289
-        $results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
290
-        if (empty($results)) {
291
-            return $this->create_new_blank_datetime();
292
-        }
293
-        return $results;
294
-    }
295
-
296
-
297
-    /**
298
-     * get all datetimes attached to an event ordered by the DTT_order field
299
-     *
300
-     * @public
301
-     * @param  int    $EVT_ID     event id
302
-     * @param boolean $include_expired
303
-     * @param boolean $include_deleted
304
-     * @param  int    $limit      If included then limit the count of results by
305
-     *                            the given number
306
-     * @return EE_Datetime[]
307
-     * @throws EE_Error
308
-     */
309
-    public function get_datetimes_for_event_ordered_by_DTT_order(
310
-        $EVT_ID,
311
-        $include_expired = true,
312
-        $include_deleted = true,
313
-        $limit = null
314
-    ) {
315
-        // sanitize EVT_ID
316
-        $EVT_ID         = absint($EVT_ID);
317
-        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
318
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
319
-        $where_params = array('Event.EVT_ID' => $EVT_ID);
320
-        $query_params = ! empty($limit)
321
-            ? array(
322
-                $where_params,
323
-                'limit'                    => $limit,
324
-                'order_by'                 => array('DTT_order' => 'ASC'),
325
-                'default_where_conditions' => 'none',
326
-            )
327
-            : array(
328
-                $where_params,
329
-                'order_by'                 => array('DTT_order' => 'ASC'),
330
-                'default_where_conditions' => 'none',
331
-            );
332
-        if (! $include_expired) {
333
-            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
334
-        }
335
-        if ($include_deleted) {
336
-            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
337
-        }
338
-        /** @var EE_Datetime[] $result */
339
-        $result = $this->get_all($query_params);
340
-        $this->assume_values_already_prepared_by_model_object($old_assumption);
341
-        return $result;
342
-    }
343
-
344
-
345
-    /**
346
-     * Gets the datetimes for the event (with the given limit), and orders them by "importance".
347
-     * By importance, we mean that the primary datetimes are most important (DEPRECATED FOR NOW),
348
-     * and then the earlier datetimes are the most important.
349
-     * Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
350
-     *
351
-     * @param int $EVT_ID
352
-     * @param int $limit
353
-     * @return EE_Datetime[]|EE_Base_Class[]
354
-     * @throws EE_Error
355
-     */
356
-    public function get_datetimes_for_event_ordered_by_importance($EVT_ID = 0, $limit = null)
357
-    {
358
-        return $this->get_all(
359
-            array(
360
-                array('Event.EVT_ID' => $EVT_ID),
361
-                'limit'                    => $limit,
362
-                'order_by'                 => array('DTT_EVT_start' => 'ASC'),
363
-                'default_where_conditions' => 'none',
364
-            )
365
-        );
366
-    }
367
-
368
-
369
-    /**
370
-     * @param int     $EVT_ID
371
-     * @param boolean $include_expired
372
-     * @param boolean $include_deleted
373
-     * @return EE_Datetime
374
-     * @throws EE_Error
375
-     */
376
-    public function get_oldest_datetime_for_event($EVT_ID, $include_expired = false, $include_deleted = false)
377
-    {
378
-        $results = $this->get_datetimes_for_event_ordered_by_start_time(
379
-            $EVT_ID,
380
-            $include_expired,
381
-            $include_deleted,
382
-            1
383
-        );
384
-        if ($results) {
385
-            return array_shift($results);
386
-        }
387
-        return null;
388
-    }
389
-
390
-
391
-    /**
392
-     * Gets the 'primary' datetime for an event.
393
-     *
394
-     * @param int  $EVT_ID
395
-     * @param bool $try_to_exclude_expired
396
-     * @param bool $try_to_exclude_deleted
397
-     * @return \EE_Datetime
398
-     * @throws EE_Error
399
-     */
400
-    public function get_primary_datetime_for_event(
401
-        $EVT_ID,
402
-        $try_to_exclude_expired = true,
403
-        $try_to_exclude_deleted = true
404
-    ) {
405
-        if ($try_to_exclude_expired) {
406
-            $non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
407
-            if ($non_expired) {
408
-                return $non_expired;
409
-            }
410
-        }
411
-        if ($try_to_exclude_deleted) {
412
-            $expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
413
-            if ($expired_even) {
414
-                return $expired_even;
415
-            }
416
-        }
417
-        return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
418
-    }
419
-
420
-
421
-    /**
422
-     * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
423
-     * only by start date
424
-     *
425
-     * @param int     $EVT_ID
426
-     * @param boolean $include_expired
427
-     * @param boolean $include_deleted
428
-     * @param int     $limit
429
-     * @return EE_Datetime[]
430
-     * @throws EE_Error
431
-     */
432
-    public function get_datetimes_for_event_ordered_by_start_time(
433
-        $EVT_ID,
434
-        $include_expired = true,
435
-        $include_deleted = true,
436
-        $limit = null
437
-    ) {
438
-        // sanitize EVT_ID
439
-        $EVT_ID         = absint($EVT_ID);
440
-        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
441
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
442
-        $query_params = array(array('Event.EVT_ID' => $EVT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
443
-        if (! $include_expired) {
444
-            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
445
-        }
446
-        if ($include_deleted) {
447
-            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
448
-        }
449
-        if ($limit) {
450
-            $query_params['limit'] = $limit;
451
-        }
452
-        /** @var EE_Datetime[] $result */
453
-        $result = $this->get_all($query_params);
454
-        $this->assume_values_already_prepared_by_model_object($old_assumption);
455
-        return $result;
456
-    }
457
-
458
-
459
-    /**
460
-     * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
461
-     * only by start date
462
-     *
463
-     * @param int     $TKT_ID
464
-     * @param boolean $include_expired
465
-     * @param boolean $include_deleted
466
-     * @param int     $limit
467
-     * @return EE_Datetime[]
468
-     * @throws EE_Error
469
-     */
470
-    public function get_datetimes_for_ticket_ordered_by_start_time(
471
-        $TKT_ID,
472
-        $include_expired = true,
473
-        $include_deleted = true,
474
-        $limit = null
475
-    ) {
476
-        // sanitize TKT_ID
477
-        $TKT_ID         = absint($TKT_ID);
478
-        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
479
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
480
-        $query_params = array(array('Ticket.TKT_ID' => $TKT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
481
-        if (! $include_expired) {
482
-            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
483
-        }
484
-        if ($include_deleted) {
485
-            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
486
-        }
487
-        if ($limit) {
488
-            $query_params['limit'] = $limit;
489
-        }
490
-        /** @var EE_Datetime[] $result */
491
-        $result = $this->get_all($query_params);
492
-        $this->assume_values_already_prepared_by_model_object($old_assumption);
493
-        return $result;
494
-    }
495
-
496
-
497
-    /**
498
-     * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
499
-     * datetimes.
500
-     *
501
-     * @param  int      $TKT_ID          ID of ticket to retrieve the datetimes for
502
-     * @param  boolean  $include_expired whether to include expired datetimes or not
503
-     * @param  boolean  $include_deleted whether to include trashed datetimes or not.
504
-     * @param  int|null $limit           if null, no limit, if int then limit results by
505
-     *                                   that number
506
-     * @return EE_Datetime[]
507
-     * @throws EE_Error
508
-     */
509
-    public function get_datetimes_for_ticket_ordered_by_DTT_order(
510
-        $TKT_ID,
511
-        $include_expired = true,
512
-        $include_deleted = true,
513
-        $limit = null
514
-    ) {
515
-        // sanitize id.
516
-        $TKT_ID         = absint($TKT_ID);
517
-        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
518
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
519
-        $where_params = array('Ticket.TKT_ID' => $TKT_ID);
520
-        $query_params = array($where_params, 'order_by' => array('DTT_order' => 'ASC'));
521
-        if (! $include_expired) {
522
-            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
523
-        }
524
-        if ($include_deleted) {
525
-            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
526
-        }
527
-        if ($limit) {
528
-            $query_params['limit'] = $limit;
529
-        }
530
-        /** @var EE_Datetime[] $result */
531
-        $result = $this->get_all($query_params);
532
-        $this->assume_values_already_prepared_by_model_object($old_assumption);
533
-        return $result;
534
-    }
535
-
536
-
537
-    /**
538
-     * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
539
-     * reason it doesn't exist, we consider the earliest event the most important)
540
-     *
541
-     * @param int $EVT_ID
542
-     * @return EE_Datetime
543
-     * @throws EE_Error
544
-     */
545
-    public function get_most_important_datetime_for_event($EVT_ID)
546
-    {
547
-        $results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
548
-        if ($results) {
549
-            return array_shift($results);
550
-        }
551
-        return null;
552
-    }
553
-
554
-
555
-    /**
556
-     * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
557
-     * grouped by month and year.
558
-     *
559
-     * @param  array  $where_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
560
-     * @param  string $evt_active_status A string representing the evt active status to filter the months by.
561
-     *                                   Can be:
562
-     *                                   - '' = no filter
563
-     *                                   - upcoming = Published events with at least one upcoming datetime.
564
-     *                                   - expired = Events with all datetimes expired.
565
-     *                                   - active = Events that are published and have at least one datetime that
566
-     *                                   starts before now and ends after now.
567
-     *                                   - inactive = Events that are either not published.
568
-     * @return EE_Base_Class[]
569
-     * @throws EE_Error
570
-     * @throws InvalidArgumentException
571
-     * @throws InvalidArgumentException
572
-     */
573
-    public function get_dtt_months_and_years($where_params, $evt_active_status = '')
574
-    {
575
-        $current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
576
-        $current_time_for_DTT_EVT_end   = $this->current_time_for_query('DTT_EVT_end');
577
-        switch ($evt_active_status) {
578
-            case 'upcoming':
579
-                $where_params['Event.status'] = 'publish';
580
-                // if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
581
-                if (isset($where_params['DTT_EVT_start'])) {
582
-                    $where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
583
-                }
584
-                $where_params['DTT_EVT_start'] = array('>', $current_time_for_DTT_EVT_start);
585
-                break;
586
-            case 'expired':
587
-                if (isset($where_params['Event.status'])) {
588
-                    unset($where_params['Event.status']);
589
-                }
590
-                // get events to exclude
591
-                $exclude_query[0] = array_merge(
592
-                    $where_params,
593
-                    array('DTT_EVT_end' => array('>', $current_time_for_DTT_EVT_end))
594
-                );
595
-                // first get all events that have datetimes where its not expired.
596
-                $event_ids = $this->_get_all_wpdb_results(
597
-                    $exclude_query,
598
-                    OBJECT_K,
599
-                    'Datetime.EVT_ID'
600
-                );
601
-                $event_ids = array_keys($event_ids);
602
-                if (isset($where_params['DTT_EVT_end'])) {
603
-                    $where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
604
-                }
605
-                $where_params['DTT_EVT_end']  = array('<', $current_time_for_DTT_EVT_end);
606
-                $where_params['Event.EVT_ID'] = array('NOT IN', $event_ids);
607
-                break;
608
-            case 'active':
609
-                $where_params['Event.status'] = 'publish';
610
-                if (isset($where_params['DTT_EVT_start'])) {
611
-                    $where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
612
-                }
613
-                if (isset($where_params['Datetime.DTT_EVT_end'])) {
614
-                    $where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
615
-                }
616
-                $where_params['DTT_EVT_start'] = array('<', $current_time_for_DTT_EVT_start);
617
-                $where_params['DTT_EVT_end']   = array('>', $current_time_for_DTT_EVT_end);
618
-                break;
619
-            case 'inactive':
620
-                if (isset($where_params['Event.status'])) {
621
-                    unset($where_params['Event.status']);
622
-                }
623
-                if (isset($where_params['OR'])) {
624
-                    $where_params['AND']['OR'] = $where_params['OR'];
625
-                }
626
-                if (isset($where_params['DTT_EVT_end'])) {
627
-                    $where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
628
-                    unset($where_params['DTT_EVT_end']);
629
-                }
630
-                if (isset($where_params['DTT_EVT_start'])) {
631
-                    $where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
632
-                    unset($where_params['DTT_EVT_start']);
633
-                }
634
-                $where_params['AND']['Event.status'] = array('!=', 'publish');
635
-                break;
636
-        }
637
-        $query_params[0]          = $where_params;
638
-        $query_params['group_by'] = array('dtt_year', 'dtt_month');
639
-        $query_params['order_by'] = array('DTT_EVT_start' => 'DESC');
640
-        $query_interval           = EEH_DTT_Helper::get_sql_query_interval_for_offset(
641
-            $this->get_timezone(),
642
-            'DTT_EVT_start'
643
-        );
644
-        $columns_to_select        = array(
645
-            'dtt_year'      => array('YEAR(' . $query_interval . ')', '%s'),
646
-            'dtt_month'     => array('MONTHNAME(' . $query_interval . ')', '%s'),
647
-            'dtt_month_num' => array('MONTH(' . $query_interval . ')', '%s'),
648
-        );
649
-        return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
650
-    }
651
-
652
-
653
-    /**
654
-     * Updates the DTT_sold attribute on each datetime (based on the registrations
655
-     * for the tickets for each datetime)
656
-     *
657
-     * @param EE_Base_Class[]|EE_Datetime[] $datetimes
658
-     * @throws EE_Error
659
-     */
660
-    public function update_sold($datetimes)
661
-    {
662
-        EE_Error::doing_it_wrong(
663
-            __FUNCTION__,
664
-            esc_html__(
665
-                'Please use \EEM_Ticket::update_tickets_sold() instead which will in turn correctly update both the Ticket AND Datetime counts.',
666
-                'event_espresso'
667
-            ),
668
-            '4.9.32.rc.005'
669
-        );
670
-        foreach ($datetimes as $datetime) {
671
-            $datetime->update_sold();
672
-        }
673
-    }
674
-
675
-
676
-    /**
677
-     *    Gets the total number of tickets available at a particular datetime
678
-     *    (does NOT take into account the datetime's spaces available)
679
-     *
680
-     * @param int   $DTT_ID
681
-     * @param array $query_params
682
-     * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
683
-     *             tickets attached to datetime then FALSE is returned.
684
-     */
685
-    public function sum_tickets_currently_available_at_datetime($DTT_ID, array $query_params = array())
686
-    {
687
-        $datetime = $this->get_one_by_ID($DTT_ID);
688
-        if ($datetime instanceof EE_Datetime) {
689
-            return $datetime->tickets_remaining($query_params);
690
-        }
691
-        return 0;
692
-    }
693
-
694
-
695
-    /**
696
-     * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
697
-     *
698
-     * @param  array $stati_to_include If included you can restrict the statuses we return counts for by including the
699
-     *                                 stati you want counts for as values in the array.  An empty array returns counts
700
-     *                                 for all valid stati.
701
-     * @param  array $query_params     If included can be used to refine the conditions for returning the count (i.e.
702
-     *                                 only for Datetimes connected to a specific event, or specific ticket.
703
-     * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
704
-     * @throws EE_Error
705
-     *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming
706
-     *                                 EE_Datetime::expired
707
-     */
708
-    public function get_datetime_counts_by_status(array $stati_to_include = array(), array $query_params = array())
709
-    {
710
-        // only accept where conditions for this query.
711
-        $_where            = isset($query_params[0]) ? $query_params[0] : array();
712
-        $status_query_args = array(
713
-            EE_Datetime::active   => array_merge(
714
-                $_where,
715
-                array('DTT_EVT_start' => array('<', time()), 'DTT_EVT_end' => array('>', time()))
716
-            ),
717
-            EE_Datetime::upcoming => array_merge(
718
-                $_where,
719
-                array('DTT_EVT_start' => array('>', time()))
720
-            ),
721
-            EE_Datetime::expired  => array_merge(
722
-                $_where,
723
-                array('DTT_EVT_end' => array('<', time()))
724
-            ),
725
-        );
726
-        if (! empty($stati_to_include)) {
727
-            foreach (array_keys($status_query_args) as $status) {
728
-                if (! in_array($status, $stati_to_include, true)) {
729
-                    unset($status_query_args[ $status ]);
730
-                }
731
-            }
732
-        }
733
-        // loop through and query counts for each stati.
734
-        $status_query_results = array();
735
-        foreach ($status_query_args as $status => $status_where_conditions) {
736
-            $status_query_results[ $status ] = EEM_Datetime::count(
737
-                array($status_where_conditions),
738
-                'DTT_ID',
739
-                true
740
-            );
741
-        }
742
-        return $status_query_results;
743
-    }
744
-
745
-
746
-    /**
747
-     * Returns the specific count for a given Datetime status matching any given query_params.
748
-     *
749
-     * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
750
-     * @param array  $query_params
751
-     * @return int
752
-     * @throws EE_Error
753
-     */
754
-    public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = array())
755
-    {
756
-        $count = $this->get_datetime_counts_by_status(array($status), $query_params);
757
-        return ! empty($count[ $status ]) ? $count[ $status ] : 0;
758
-    }
16
+	/**
17
+	 * @var EEM_Datetime $_instance
18
+	 */
19
+	protected static $_instance;
20
+
21
+
22
+	/**
23
+	 * private constructor to prevent direct creation
24
+	 *
25
+	 * @param string $timezone A string representing the timezone we want to set for returned Date Time Strings
26
+	 *                         (and any incoming timezone data that gets saved).
27
+	 *                         Note this just sends the timezone info to the date time model field objects.
28
+	 *                         Default is NULL
29
+	 *                         (and will be assumed using the set timezone in the 'timezone_string' wp option)
30
+	 * @throws EE_Error
31
+	 * @throws InvalidArgumentException
32
+	 * @throws InvalidArgumentException
33
+	 */
34
+	protected function __construct($timezone)
35
+	{
36
+		$this->singular_item           = esc_html__('Datetime', 'event_espresso');
37
+		$this->plural_item             = esc_html__('Datetimes', 'event_espresso');
38
+		$this->_tables                 = array(
39
+			'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
40
+		);
41
+		$this->_fields                 = array(
42
+			'Datetime' => array(
43
+				'DTT_ID'          => new EE_Primary_Key_Int_Field(
44
+					'DTT_ID',
45
+					esc_html__('Datetime ID', 'event_espresso')
46
+				),
47
+				'EVT_ID'          => new EE_Foreign_Key_Int_Field(
48
+					'EVT_ID',
49
+					esc_html__('Event ID', 'event_espresso'),
50
+					false,
51
+					0,
52
+					'Event'
53
+				),
54
+				'DTT_name'        => new EE_Plain_Text_Field(
55
+					'DTT_name',
56
+					esc_html__('Datetime Name', 'event_espresso'),
57
+					false,
58
+					''
59
+				),
60
+				'DTT_description' => new EE_Post_Content_Field(
61
+					'DTT_description',
62
+					esc_html__('Description for Datetime', 'event_espresso'),
63
+					false,
64
+					''
65
+				),
66
+				'DTT_EVT_start'   => new EE_Datetime_Field(
67
+					'DTT_EVT_start',
68
+					esc_html__('Start time/date of Event', 'event_espresso'),
69
+					false,
70
+					EE_Datetime_Field::now,
71
+					$timezone
72
+				),
73
+				'DTT_EVT_end'     => new EE_Datetime_Field(
74
+					'DTT_EVT_end',
75
+					esc_html__('End time/date of Event', 'event_espresso'),
76
+					false,
77
+					EE_Datetime_Field::now,
78
+					$timezone
79
+				),
80
+				'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
81
+					'DTT_reg_limit',
82
+					esc_html__('Registration Limit for this time', 'event_espresso'),
83
+					true,
84
+					EE_INF
85
+				),
86
+				'DTT_sold'        => new EE_Integer_Field(
87
+					'DTT_sold',
88
+					esc_html__('How many sales for this Datetime that have occurred', 'event_espresso'),
89
+					true,
90
+					0
91
+				),
92
+				'DTT_reserved'    => new EE_Integer_Field(
93
+					'DTT_reserved',
94
+					esc_html__('Quantity of tickets reserved, but not yet fully purchased', 'event_espresso'),
95
+					false,
96
+					0
97
+				),
98
+				'DTT_is_primary'  => new EE_Boolean_Field(
99
+					'DTT_is_primary',
100
+					esc_html__('Flag indicating datetime is primary one for event', 'event_espresso'),
101
+					false,
102
+					false
103
+				),
104
+				'DTT_order'       => new EE_Integer_Field(
105
+					'DTT_order',
106
+					esc_html__('The order in which the Datetime is displayed', 'event_espresso'),
107
+					false,
108
+					0
109
+				),
110
+				'DTT_parent'      => new EE_Integer_Field(
111
+					'DTT_parent',
112
+					esc_html__('Indicates what DTT_ID is the parent of this DTT_ID', 'event_espresso'),
113
+					true,
114
+					0
115
+				),
116
+				'DTT_deleted'     => new EE_Trashed_Flag_Field(
117
+					'DTT_deleted',
118
+					esc_html__('Flag indicating datetime is archived', 'event_espresso'),
119
+					false,
120
+					false
121
+				),
122
+			),
123
+		);
124
+		$this->_model_relations        = array(
125
+			'Ticket'  => new EE_HABTM_Relation('Datetime_Ticket'),
126
+			'Event'   => new EE_Belongs_To_Relation(),
127
+			'Checkin' => new EE_Has_Many_Relation(),
128
+			'Datetime_Ticket' => new EE_Has_Many_Relation(),
129
+		);
130
+		$path_to_event_model = 'Event';
131
+		$this->model_chain_to_password = $path_to_event_model;
132
+		$this->_model_chain_to_wp_user = $path_to_event_model;
133
+		// this model is generally available for reading
134
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Event_Related_Public(
135
+			$path_to_event_model
136
+		);
137
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
138
+			$path_to_event_model
139
+		);
140
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       = new EE_Restriction_Generator_Event_Related_Protected(
141
+			$path_to_event_model
142
+		);
143
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     = new EE_Restriction_Generator_Event_Related_Protected(
144
+			$path_to_event_model,
145
+			EEM_Base::caps_edit
146
+		);
147
+		parent::__construct($timezone);
148
+	}
149
+
150
+
151
+	/**
152
+	 * create new blank datetime
153
+	 *
154
+	 * @access public
155
+	 * @return EE_Datetime[] array on success, FALSE on fail
156
+	 * @throws EE_Error
157
+	 * @throws InvalidArgumentException
158
+	 * @throws InvalidDataTypeException
159
+	 * @throws ReflectionException
160
+	 * @throws InvalidInterfaceException
161
+	 */
162
+	public function create_new_blank_datetime()
163
+	{
164
+		// makes sure timezone is always set.
165
+		$timezone_string = $this->get_timezone();
166
+		/**
167
+		 * Filters the initial start date for the new datetime.
168
+		 * Any time included in this value will be overridden later so use additional filters to modify the time.
169
+		 *
170
+		 * @param int $start_date Unixtimestamp representing now + 30 days in seconds.
171
+		 * @return int unixtimestamp
172
+		 */
173
+		$start_date = apply_filters(
174
+			'FHEE__EEM_Datetime__create_new_blank_datetime__start_date',
175
+			$this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS
176
+		);
177
+		/**
178
+		 * Filters the initial end date for the new datetime.
179
+		 * Any time included in this value will be overridden later so use additional filters to modify the time.
180
+		 *
181
+		 * @param int $end_data Unixtimestamp representing now + 30 days in seconds.
182
+		 * @return int unixtimestamp
183
+		 */
184
+		$end_date = apply_filters(
185
+			'FHEE__EEM_Datetime__create_new_blank_datetime__end_date',
186
+			$this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS
187
+		);
188
+		$blank_datetime = EE_Datetime::new_instance(
189
+			array(
190
+				'DTT_EVT_start' => $start_date,
191
+				'DTT_EVT_end'   => $end_date,
192
+				'DTT_order'     => 1,
193
+				'DTT_reg_limit' => EE_INF,
194
+			),
195
+			$timezone_string
196
+		);
197
+		/**
198
+		 * Filters the initial start time and format for the new EE_Datetime instance.
199
+		 *
200
+		 * @param array $start_time An array having size 2.  First element is the time, second element is the time
201
+		 *                          format.
202
+		 * @return array
203
+		 */
204
+		$start_time = apply_filters(
205
+			'FHEE__EEM_Datetime__create_new_blank_datetime__start_time',
206
+			['8am', 'ga']
207
+		);
208
+		/**
209
+		 * Filters the initial end time and format for the new EE_Datetime instance.
210
+		 *
211
+		 * @param array $end_time An array having size 2.  First element is the time, second element is the time
212
+		 *                        format
213
+		 * @return array
214
+		 */
215
+		$end_time = apply_filters(
216
+			'FHEE__EEM_Datetime__create_new_blank_datetime__end_time',
217
+			['5pm', 'ga']
218
+		);
219
+		$this->validateStartAndEndTimeForBlankDate($start_time, $end_time);
220
+		$blank_datetime->set_start_time(
221
+			$this->convert_datetime_for_query(
222
+				'DTT_EVT_start',
223
+				$start_time[0],
224
+				$start_time[1],
225
+				$timezone_string
226
+			)
227
+		);
228
+		$blank_datetime->set_end_time(
229
+			$this->convert_datetime_for_query(
230
+				'DTT_EVT_end',
231
+				$end_time[0],
232
+				$end_time[1],
233
+				$timezone_string
234
+			)
235
+		);
236
+		return array($blank_datetime);
237
+	}
238
+
239
+
240
+	/**
241
+	 * Validates whether the start_time and end_time are in the expected format.
242
+	 * @param array $start_time
243
+	 * @param array $end_time
244
+	 * @throws InvalidArgumentException
245
+	 * @throws InvalidDataTypeException
246
+	 */
247
+	private function validateStartAndEndTimeForBlankDate($start_time, $end_time)
248
+	{
249
+		if (! is_array($start_time)) {
250
+			throw new InvalidDataTypeException('start_time', $start_time, 'array');
251
+		}
252
+		if (! is_array($end_time)) {
253
+			throw new InvalidDataTypeException('end_time', $end_time, 'array');
254
+		}
255
+		if (count($start_time) !== 2) {
256
+			throw new InvalidArgumentException(
257
+				sprintf(
258
+					'The variable %1$s is expected to be an array with two elements.  The first item in the '
259
+					. 'array should be a valid time string, the second item in the array should be a valid time format',
260
+					'$start_time'
261
+				)
262
+			);
263
+		}
264
+		if (count($end_time) !== 2) {
265
+			throw new InvalidArgumentException(
266
+				sprintf(
267
+					'The variable %1$s is expected to be an array with two elements.  The first item in the '
268
+					. 'array should be a valid time string, the second item in the array should be a valid time format',
269
+					'$end_time'
270
+				)
271
+			);
272
+		}
273
+	}
274
+
275
+
276
+	/**
277
+	 * get event start date from db
278
+	 *
279
+	 * @access public
280
+	 * @param  int $EVT_ID
281
+	 * @return EE_Datetime[] array on success, FALSE on fail
282
+	 * @throws EE_Error
283
+	 */
284
+	public function get_all_event_dates($EVT_ID = 0)
285
+	{
286
+		if (! $EVT_ID) { // on add_new_event event_id gets set to 0
287
+			return $this->create_new_blank_datetime();
288
+		}
289
+		$results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
290
+		if (empty($results)) {
291
+			return $this->create_new_blank_datetime();
292
+		}
293
+		return $results;
294
+	}
295
+
296
+
297
+	/**
298
+	 * get all datetimes attached to an event ordered by the DTT_order field
299
+	 *
300
+	 * @public
301
+	 * @param  int    $EVT_ID     event id
302
+	 * @param boolean $include_expired
303
+	 * @param boolean $include_deleted
304
+	 * @param  int    $limit      If included then limit the count of results by
305
+	 *                            the given number
306
+	 * @return EE_Datetime[]
307
+	 * @throws EE_Error
308
+	 */
309
+	public function get_datetimes_for_event_ordered_by_DTT_order(
310
+		$EVT_ID,
311
+		$include_expired = true,
312
+		$include_deleted = true,
313
+		$limit = null
314
+	) {
315
+		// sanitize EVT_ID
316
+		$EVT_ID         = absint($EVT_ID);
317
+		$old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
318
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
319
+		$where_params = array('Event.EVT_ID' => $EVT_ID);
320
+		$query_params = ! empty($limit)
321
+			? array(
322
+				$where_params,
323
+				'limit'                    => $limit,
324
+				'order_by'                 => array('DTT_order' => 'ASC'),
325
+				'default_where_conditions' => 'none',
326
+			)
327
+			: array(
328
+				$where_params,
329
+				'order_by'                 => array('DTT_order' => 'ASC'),
330
+				'default_where_conditions' => 'none',
331
+			);
332
+		if (! $include_expired) {
333
+			$query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
334
+		}
335
+		if ($include_deleted) {
336
+			$query_params[0]['DTT_deleted'] = array('IN', array(true, false));
337
+		}
338
+		/** @var EE_Datetime[] $result */
339
+		$result = $this->get_all($query_params);
340
+		$this->assume_values_already_prepared_by_model_object($old_assumption);
341
+		return $result;
342
+	}
343
+
344
+
345
+	/**
346
+	 * Gets the datetimes for the event (with the given limit), and orders them by "importance".
347
+	 * By importance, we mean that the primary datetimes are most important (DEPRECATED FOR NOW),
348
+	 * and then the earlier datetimes are the most important.
349
+	 * Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
350
+	 *
351
+	 * @param int $EVT_ID
352
+	 * @param int $limit
353
+	 * @return EE_Datetime[]|EE_Base_Class[]
354
+	 * @throws EE_Error
355
+	 */
356
+	public function get_datetimes_for_event_ordered_by_importance($EVT_ID = 0, $limit = null)
357
+	{
358
+		return $this->get_all(
359
+			array(
360
+				array('Event.EVT_ID' => $EVT_ID),
361
+				'limit'                    => $limit,
362
+				'order_by'                 => array('DTT_EVT_start' => 'ASC'),
363
+				'default_where_conditions' => 'none',
364
+			)
365
+		);
366
+	}
367
+
368
+
369
+	/**
370
+	 * @param int     $EVT_ID
371
+	 * @param boolean $include_expired
372
+	 * @param boolean $include_deleted
373
+	 * @return EE_Datetime
374
+	 * @throws EE_Error
375
+	 */
376
+	public function get_oldest_datetime_for_event($EVT_ID, $include_expired = false, $include_deleted = false)
377
+	{
378
+		$results = $this->get_datetimes_for_event_ordered_by_start_time(
379
+			$EVT_ID,
380
+			$include_expired,
381
+			$include_deleted,
382
+			1
383
+		);
384
+		if ($results) {
385
+			return array_shift($results);
386
+		}
387
+		return null;
388
+	}
389
+
390
+
391
+	/**
392
+	 * Gets the 'primary' datetime for an event.
393
+	 *
394
+	 * @param int  $EVT_ID
395
+	 * @param bool $try_to_exclude_expired
396
+	 * @param bool $try_to_exclude_deleted
397
+	 * @return \EE_Datetime
398
+	 * @throws EE_Error
399
+	 */
400
+	public function get_primary_datetime_for_event(
401
+		$EVT_ID,
402
+		$try_to_exclude_expired = true,
403
+		$try_to_exclude_deleted = true
404
+	) {
405
+		if ($try_to_exclude_expired) {
406
+			$non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
407
+			if ($non_expired) {
408
+				return $non_expired;
409
+			}
410
+		}
411
+		if ($try_to_exclude_deleted) {
412
+			$expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
413
+			if ($expired_even) {
414
+				return $expired_even;
415
+			}
416
+		}
417
+		return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
418
+	}
419
+
420
+
421
+	/**
422
+	 * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
423
+	 * only by start date
424
+	 *
425
+	 * @param int     $EVT_ID
426
+	 * @param boolean $include_expired
427
+	 * @param boolean $include_deleted
428
+	 * @param int     $limit
429
+	 * @return EE_Datetime[]
430
+	 * @throws EE_Error
431
+	 */
432
+	public function get_datetimes_for_event_ordered_by_start_time(
433
+		$EVT_ID,
434
+		$include_expired = true,
435
+		$include_deleted = true,
436
+		$limit = null
437
+	) {
438
+		// sanitize EVT_ID
439
+		$EVT_ID         = absint($EVT_ID);
440
+		$old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
441
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
442
+		$query_params = array(array('Event.EVT_ID' => $EVT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
443
+		if (! $include_expired) {
444
+			$query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
445
+		}
446
+		if ($include_deleted) {
447
+			$query_params[0]['DTT_deleted'] = array('IN', array(true, false));
448
+		}
449
+		if ($limit) {
450
+			$query_params['limit'] = $limit;
451
+		}
452
+		/** @var EE_Datetime[] $result */
453
+		$result = $this->get_all($query_params);
454
+		$this->assume_values_already_prepared_by_model_object($old_assumption);
455
+		return $result;
456
+	}
457
+
458
+
459
+	/**
460
+	 * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
461
+	 * only by start date
462
+	 *
463
+	 * @param int     $TKT_ID
464
+	 * @param boolean $include_expired
465
+	 * @param boolean $include_deleted
466
+	 * @param int     $limit
467
+	 * @return EE_Datetime[]
468
+	 * @throws EE_Error
469
+	 */
470
+	public function get_datetimes_for_ticket_ordered_by_start_time(
471
+		$TKT_ID,
472
+		$include_expired = true,
473
+		$include_deleted = true,
474
+		$limit = null
475
+	) {
476
+		// sanitize TKT_ID
477
+		$TKT_ID         = absint($TKT_ID);
478
+		$old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
479
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
480
+		$query_params = array(array('Ticket.TKT_ID' => $TKT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
481
+		if (! $include_expired) {
482
+			$query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
483
+		}
484
+		if ($include_deleted) {
485
+			$query_params[0]['DTT_deleted'] = array('IN', array(true, false));
486
+		}
487
+		if ($limit) {
488
+			$query_params['limit'] = $limit;
489
+		}
490
+		/** @var EE_Datetime[] $result */
491
+		$result = $this->get_all($query_params);
492
+		$this->assume_values_already_prepared_by_model_object($old_assumption);
493
+		return $result;
494
+	}
495
+
496
+
497
+	/**
498
+	 * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
499
+	 * datetimes.
500
+	 *
501
+	 * @param  int      $TKT_ID          ID of ticket to retrieve the datetimes for
502
+	 * @param  boolean  $include_expired whether to include expired datetimes or not
503
+	 * @param  boolean  $include_deleted whether to include trashed datetimes or not.
504
+	 * @param  int|null $limit           if null, no limit, if int then limit results by
505
+	 *                                   that number
506
+	 * @return EE_Datetime[]
507
+	 * @throws EE_Error
508
+	 */
509
+	public function get_datetimes_for_ticket_ordered_by_DTT_order(
510
+		$TKT_ID,
511
+		$include_expired = true,
512
+		$include_deleted = true,
513
+		$limit = null
514
+	) {
515
+		// sanitize id.
516
+		$TKT_ID         = absint($TKT_ID);
517
+		$old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
518
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
519
+		$where_params = array('Ticket.TKT_ID' => $TKT_ID);
520
+		$query_params = array($where_params, 'order_by' => array('DTT_order' => 'ASC'));
521
+		if (! $include_expired) {
522
+			$query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
523
+		}
524
+		if ($include_deleted) {
525
+			$query_params[0]['DTT_deleted'] = array('IN', array(true, false));
526
+		}
527
+		if ($limit) {
528
+			$query_params['limit'] = $limit;
529
+		}
530
+		/** @var EE_Datetime[] $result */
531
+		$result = $this->get_all($query_params);
532
+		$this->assume_values_already_prepared_by_model_object($old_assumption);
533
+		return $result;
534
+	}
535
+
536
+
537
+	/**
538
+	 * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
539
+	 * reason it doesn't exist, we consider the earliest event the most important)
540
+	 *
541
+	 * @param int $EVT_ID
542
+	 * @return EE_Datetime
543
+	 * @throws EE_Error
544
+	 */
545
+	public function get_most_important_datetime_for_event($EVT_ID)
546
+	{
547
+		$results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
548
+		if ($results) {
549
+			return array_shift($results);
550
+		}
551
+		return null;
552
+	}
553
+
554
+
555
+	/**
556
+	 * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
557
+	 * grouped by month and year.
558
+	 *
559
+	 * @param  array  $where_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
560
+	 * @param  string $evt_active_status A string representing the evt active status to filter the months by.
561
+	 *                                   Can be:
562
+	 *                                   - '' = no filter
563
+	 *                                   - upcoming = Published events with at least one upcoming datetime.
564
+	 *                                   - expired = Events with all datetimes expired.
565
+	 *                                   - active = Events that are published and have at least one datetime that
566
+	 *                                   starts before now and ends after now.
567
+	 *                                   - inactive = Events that are either not published.
568
+	 * @return EE_Base_Class[]
569
+	 * @throws EE_Error
570
+	 * @throws InvalidArgumentException
571
+	 * @throws InvalidArgumentException
572
+	 */
573
+	public function get_dtt_months_and_years($where_params, $evt_active_status = '')
574
+	{
575
+		$current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
576
+		$current_time_for_DTT_EVT_end   = $this->current_time_for_query('DTT_EVT_end');
577
+		switch ($evt_active_status) {
578
+			case 'upcoming':
579
+				$where_params['Event.status'] = 'publish';
580
+				// if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
581
+				if (isset($where_params['DTT_EVT_start'])) {
582
+					$where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
583
+				}
584
+				$where_params['DTT_EVT_start'] = array('>', $current_time_for_DTT_EVT_start);
585
+				break;
586
+			case 'expired':
587
+				if (isset($where_params['Event.status'])) {
588
+					unset($where_params['Event.status']);
589
+				}
590
+				// get events to exclude
591
+				$exclude_query[0] = array_merge(
592
+					$where_params,
593
+					array('DTT_EVT_end' => array('>', $current_time_for_DTT_EVT_end))
594
+				);
595
+				// first get all events that have datetimes where its not expired.
596
+				$event_ids = $this->_get_all_wpdb_results(
597
+					$exclude_query,
598
+					OBJECT_K,
599
+					'Datetime.EVT_ID'
600
+				);
601
+				$event_ids = array_keys($event_ids);
602
+				if (isset($where_params['DTT_EVT_end'])) {
603
+					$where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
604
+				}
605
+				$where_params['DTT_EVT_end']  = array('<', $current_time_for_DTT_EVT_end);
606
+				$where_params['Event.EVT_ID'] = array('NOT IN', $event_ids);
607
+				break;
608
+			case 'active':
609
+				$where_params['Event.status'] = 'publish';
610
+				if (isset($where_params['DTT_EVT_start'])) {
611
+					$where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
612
+				}
613
+				if (isset($where_params['Datetime.DTT_EVT_end'])) {
614
+					$where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
615
+				}
616
+				$where_params['DTT_EVT_start'] = array('<', $current_time_for_DTT_EVT_start);
617
+				$where_params['DTT_EVT_end']   = array('>', $current_time_for_DTT_EVT_end);
618
+				break;
619
+			case 'inactive':
620
+				if (isset($where_params['Event.status'])) {
621
+					unset($where_params['Event.status']);
622
+				}
623
+				if (isset($where_params['OR'])) {
624
+					$where_params['AND']['OR'] = $where_params['OR'];
625
+				}
626
+				if (isset($where_params['DTT_EVT_end'])) {
627
+					$where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
628
+					unset($where_params['DTT_EVT_end']);
629
+				}
630
+				if (isset($where_params['DTT_EVT_start'])) {
631
+					$where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
632
+					unset($where_params['DTT_EVT_start']);
633
+				}
634
+				$where_params['AND']['Event.status'] = array('!=', 'publish');
635
+				break;
636
+		}
637
+		$query_params[0]          = $where_params;
638
+		$query_params['group_by'] = array('dtt_year', 'dtt_month');
639
+		$query_params['order_by'] = array('DTT_EVT_start' => 'DESC');
640
+		$query_interval           = EEH_DTT_Helper::get_sql_query_interval_for_offset(
641
+			$this->get_timezone(),
642
+			'DTT_EVT_start'
643
+		);
644
+		$columns_to_select        = array(
645
+			'dtt_year'      => array('YEAR(' . $query_interval . ')', '%s'),
646
+			'dtt_month'     => array('MONTHNAME(' . $query_interval . ')', '%s'),
647
+			'dtt_month_num' => array('MONTH(' . $query_interval . ')', '%s'),
648
+		);
649
+		return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
650
+	}
651
+
652
+
653
+	/**
654
+	 * Updates the DTT_sold attribute on each datetime (based on the registrations
655
+	 * for the tickets for each datetime)
656
+	 *
657
+	 * @param EE_Base_Class[]|EE_Datetime[] $datetimes
658
+	 * @throws EE_Error
659
+	 */
660
+	public function update_sold($datetimes)
661
+	{
662
+		EE_Error::doing_it_wrong(
663
+			__FUNCTION__,
664
+			esc_html__(
665
+				'Please use \EEM_Ticket::update_tickets_sold() instead which will in turn correctly update both the Ticket AND Datetime counts.',
666
+				'event_espresso'
667
+			),
668
+			'4.9.32.rc.005'
669
+		);
670
+		foreach ($datetimes as $datetime) {
671
+			$datetime->update_sold();
672
+		}
673
+	}
674
+
675
+
676
+	/**
677
+	 *    Gets the total number of tickets available at a particular datetime
678
+	 *    (does NOT take into account the datetime's spaces available)
679
+	 *
680
+	 * @param int   $DTT_ID
681
+	 * @param array $query_params
682
+	 * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
683
+	 *             tickets attached to datetime then FALSE is returned.
684
+	 */
685
+	public function sum_tickets_currently_available_at_datetime($DTT_ID, array $query_params = array())
686
+	{
687
+		$datetime = $this->get_one_by_ID($DTT_ID);
688
+		if ($datetime instanceof EE_Datetime) {
689
+			return $datetime->tickets_remaining($query_params);
690
+		}
691
+		return 0;
692
+	}
693
+
694
+
695
+	/**
696
+	 * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
697
+	 *
698
+	 * @param  array $stati_to_include If included you can restrict the statuses we return counts for by including the
699
+	 *                                 stati you want counts for as values in the array.  An empty array returns counts
700
+	 *                                 for all valid stati.
701
+	 * @param  array $query_params     If included can be used to refine the conditions for returning the count (i.e.
702
+	 *                                 only for Datetimes connected to a specific event, or specific ticket.
703
+	 * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
704
+	 * @throws EE_Error
705
+	 *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming
706
+	 *                                 EE_Datetime::expired
707
+	 */
708
+	public function get_datetime_counts_by_status(array $stati_to_include = array(), array $query_params = array())
709
+	{
710
+		// only accept where conditions for this query.
711
+		$_where            = isset($query_params[0]) ? $query_params[0] : array();
712
+		$status_query_args = array(
713
+			EE_Datetime::active   => array_merge(
714
+				$_where,
715
+				array('DTT_EVT_start' => array('<', time()), 'DTT_EVT_end' => array('>', time()))
716
+			),
717
+			EE_Datetime::upcoming => array_merge(
718
+				$_where,
719
+				array('DTT_EVT_start' => array('>', time()))
720
+			),
721
+			EE_Datetime::expired  => array_merge(
722
+				$_where,
723
+				array('DTT_EVT_end' => array('<', time()))
724
+			),
725
+		);
726
+		if (! empty($stati_to_include)) {
727
+			foreach (array_keys($status_query_args) as $status) {
728
+				if (! in_array($status, $stati_to_include, true)) {
729
+					unset($status_query_args[ $status ]);
730
+				}
731
+			}
732
+		}
733
+		// loop through and query counts for each stati.
734
+		$status_query_results = array();
735
+		foreach ($status_query_args as $status => $status_where_conditions) {
736
+			$status_query_results[ $status ] = EEM_Datetime::count(
737
+				array($status_where_conditions),
738
+				'DTT_ID',
739
+				true
740
+			);
741
+		}
742
+		return $status_query_results;
743
+	}
744
+
745
+
746
+	/**
747
+	 * Returns the specific count for a given Datetime status matching any given query_params.
748
+	 *
749
+	 * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
750
+	 * @param array  $query_params
751
+	 * @return int
752
+	 * @throws EE_Error
753
+	 */
754
+	public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = array())
755
+	{
756
+		$count = $this->get_datetime_counts_by_status(array($status), $query_params);
757
+		return ! empty($count[ $status ]) ? $count[ $status ] : 0;
758
+	}
759 759
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
                 ),
122 122
             ),
123 123
         );
124
-        $this->_model_relations        = array(
124
+        $this->_model_relations = array(
125 125
             'Ticket'  => new EE_HABTM_Relation('Datetime_Ticket'),
126 126
             'Event'   => new EE_Belongs_To_Relation(),
127 127
             'Checkin' => new EE_Has_Many_Relation(),
@@ -131,16 +131,16 @@  discard block
 block discarded – undo
131 131
         $this->model_chain_to_password = $path_to_event_model;
132 132
         $this->_model_chain_to_wp_user = $path_to_event_model;
133 133
         // this model is generally available for reading
134
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       = new EE_Restriction_Generator_Event_Related_Public(
134
+        $this->_cap_restriction_generators[EEM_Base::caps_read]       = new EE_Restriction_Generator_Event_Related_Public(
135 135
             $path_to_event_model
136 136
         );
137
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] = new EE_Restriction_Generator_Event_Related_Protected(
137
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Event_Related_Protected(
138 138
             $path_to_event_model
139 139
         );
140
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       = new EE_Restriction_Generator_Event_Related_Protected(
140
+        $this->_cap_restriction_generators[EEM_Base::caps_edit]       = new EE_Restriction_Generator_Event_Related_Protected(
141 141
             $path_to_event_model
142 142
         );
143
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     = new EE_Restriction_Generator_Event_Related_Protected(
143
+        $this->_cap_restriction_generators[EEM_Base::caps_delete]     = new EE_Restriction_Generator_Event_Related_Protected(
144 144
             $path_to_event_model,
145 145
             EEM_Base::caps_edit
146 146
         );
@@ -246,10 +246,10 @@  discard block
 block discarded – undo
246 246
      */
247 247
     private function validateStartAndEndTimeForBlankDate($start_time, $end_time)
248 248
     {
249
-        if (! is_array($start_time)) {
249
+        if ( ! is_array($start_time)) {
250 250
             throw new InvalidDataTypeException('start_time', $start_time, 'array');
251 251
         }
252
-        if (! is_array($end_time)) {
252
+        if ( ! is_array($end_time)) {
253 253
             throw new InvalidDataTypeException('end_time', $end_time, 'array');
254 254
         }
255 255
         if (count($start_time) !== 2) {
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
      */
284 284
     public function get_all_event_dates($EVT_ID = 0)
285 285
     {
286
-        if (! $EVT_ID) { // on add_new_event event_id gets set to 0
286
+        if ( ! $EVT_ID) { // on add_new_event event_id gets set to 0
287 287
             return $this->create_new_blank_datetime();
288 288
         }
289 289
         $results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
                 'order_by'                 => array('DTT_order' => 'ASC'),
330 330
                 'default_where_conditions' => 'none',
331 331
             );
332
-        if (! $include_expired) {
332
+        if ( ! $include_expired) {
333 333
             $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
334 334
         }
335 335
         if ($include_deleted) {
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
         $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
441 441
         $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
442 442
         $query_params = array(array('Event.EVT_ID' => $EVT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
443
-        if (! $include_expired) {
443
+        if ( ! $include_expired) {
444 444
             $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
445 445
         }
446 446
         if ($include_deleted) {
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
         $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
479 479
         $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
480 480
         $query_params = array(array('Ticket.TKT_ID' => $TKT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
481
-        if (! $include_expired) {
481
+        if ( ! $include_expired) {
482 482
             $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
483 483
         }
484 484
         if ($include_deleted) {
@@ -518,7 +518,7 @@  discard block
 block discarded – undo
518 518
         $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
519 519
         $where_params = array('Ticket.TKT_ID' => $TKT_ID);
520 520
         $query_params = array($where_params, 'order_by' => array('DTT_order' => 'ASC'));
521
-        if (! $include_expired) {
521
+        if ( ! $include_expired) {
522 522
             $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
523 523
         }
524 524
         if ($include_deleted) {
@@ -641,10 +641,10 @@  discard block
 block discarded – undo
641 641
             $this->get_timezone(),
642 642
             'DTT_EVT_start'
643 643
         );
644
-        $columns_to_select        = array(
645
-            'dtt_year'      => array('YEAR(' . $query_interval . ')', '%s'),
646
-            'dtt_month'     => array('MONTHNAME(' . $query_interval . ')', '%s'),
647
-            'dtt_month_num' => array('MONTH(' . $query_interval . ')', '%s'),
644
+        $columns_to_select = array(
645
+            'dtt_year'      => array('YEAR('.$query_interval.')', '%s'),
646
+            'dtt_month'     => array('MONTHNAME('.$query_interval.')', '%s'),
647
+            'dtt_month_num' => array('MONTH('.$query_interval.')', '%s'),
648 648
         );
649 649
         return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
650 650
     }
@@ -723,17 +723,17 @@  discard block
 block discarded – undo
723 723
                 array('DTT_EVT_end' => array('<', time()))
724 724
             ),
725 725
         );
726
-        if (! empty($stati_to_include)) {
726
+        if ( ! empty($stati_to_include)) {
727 727
             foreach (array_keys($status_query_args) as $status) {
728
-                if (! in_array($status, $stati_to_include, true)) {
729
-                    unset($status_query_args[ $status ]);
728
+                if ( ! in_array($status, $stati_to_include, true)) {
729
+                    unset($status_query_args[$status]);
730 730
                 }
731 731
             }
732 732
         }
733 733
         // loop through and query counts for each stati.
734 734
         $status_query_results = array();
735 735
         foreach ($status_query_args as $status => $status_where_conditions) {
736
-            $status_query_results[ $status ] = EEM_Datetime::count(
736
+            $status_query_results[$status] = EEM_Datetime::count(
737 737
                 array($status_where_conditions),
738 738
                 'DTT_ID',
739 739
                 true
@@ -754,6 +754,6 @@  discard block
 block discarded – undo
754 754
     public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = array())
755 755
     {
756 756
         $count = $this->get_datetime_counts_by_status(array($status), $query_params);
757
-        return ! empty($count[ $status ]) ? $count[ $status ] : 0;
757
+        return ! empty($count[$status]) ? $count[$status] : 0;
758 758
     }
759 759
 }
Please login to merge, or discard this patch.
public/Espresso_Arabica_2014/content-espresso_events-datetimes.php 1 patch
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -1,15 +1,15 @@
 block discarded – undo
1 1
 <?php
2 2
 //echo '<br/><h6 style="color:#2EA2CC;">'. __FILE__ . ' &nbsp; <span style="font-weight:normal;color:#E76700"> Line #: ' . __LINE__ . '</span></h6>';
3 3
 
4
-if ( is_single() || ( is_archive() && espresso_display_datetimes_in_event_list() ) ) :
4
+if (is_single() || (is_archive() && espresso_display_datetimes_in_event_list())) :
5 5
 global $post;
6
-do_action( 'AHEE_event_details_before_event_date', $post );
6
+do_action('AHEE_event_details_before_event_date', $post);
7 7
 ?>
8 8
 	<div class="event-datetimes">
9
-		<?php espresso_list_of_event_dates( $post->ID );?>
9
+		<?php espresso_list_of_event_dates($post->ID); ?>
10 10
 	</div>
11 11
 	<!-- .event-datetimes -->
12 12
 <?php
13
-do_action( 'AHEE_event_details_after_event_date', $post );
13
+do_action('AHEE_event_details_after_event_date', $post);
14 14
 endif;
15 15
 ?>
16 16
\ No newline at end of file
Please login to merge, or discard this patch.
admin_pages/registrations/Registrations_Admin_Page.core.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1247,7 +1247,7 @@
 block discarded – undo
1247 1247
     /**
1248 1248
      * Sets up the limit for the registrations query.
1249 1249
      *
1250
-     * @param $per_page
1250
+     * @param integer $per_page
1251 1251
      * @return array
1252 1252
      */
1253 1253
     protected function _get_limit($per_page)
Please login to merge, or discard this patch.
Indentation   +3823 added lines, -3823 removed lines patch added patch discarded remove patch
@@ -19,2396 +19,2396 @@  discard block
 block discarded – undo
19 19
 class Registrations_Admin_Page extends EE_Admin_Page_CPT
20 20
 {
21 21
 
22
-    /**
23
-     * @var EE_Registration
24
-     */
25
-    private $_registration;
26
-
27
-    /**
28
-     * @var EE_Event
29
-     */
30
-    private $_reg_event;
31
-
32
-    /**
33
-     * @var EE_Session
34
-     */
35
-    private $_session;
36
-
37
-    private static $_reg_status;
38
-
39
-    /**
40
-     * Form for displaying the custom questions for this registration.
41
-     * This gets used a few times throughout the request so its best to cache it
42
-     *
43
-     * @var EE_Registration_Custom_Questions_Form
44
-     */
45
-    protected $_reg_custom_questions_form = null;
46
-
47
-
48
-    /**
49
-     *        constructor
50
-     *
51
-     * @Constructor
52
-     * @access public
53
-     * @param bool $routing
54
-     * @return Registrations_Admin_Page
55
-     */
56
-    public function __construct($routing = true)
57
-    {
58
-        parent::__construct($routing);
59
-        add_action('wp_loaded', array($this, 'wp_loaded'));
60
-    }
61
-
62
-
63
-    public function wp_loaded()
64
-    {
65
-        // when adding a new registration...
66
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
67
-            EE_System::do_not_cache();
68
-            if (! isset($this->_req_data['processing_registration'])
69
-                || absint($this->_req_data['processing_registration']) !== 1
70
-            ) {
71
-                // and it's NOT the attendee information reg step
72
-                // force cookie expiration by setting time to last week
73
-                setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
74
-                // and update the global
75
-                $_COOKIE['ee_registration_added'] = 0;
76
-            }
77
-        }
78
-    }
79
-
80
-
81
-    protected function _init_page_props()
82
-    {
83
-        $this->page_slug = REG_PG_SLUG;
84
-        $this->_admin_base_url = REG_ADMIN_URL;
85
-        $this->_admin_base_path = REG_ADMIN;
86
-        $this->page_label = esc_html__('Registrations', 'event_espresso');
87
-        $this->_cpt_routes = array(
88
-            'add_new_attendee' => 'espresso_attendees',
89
-            'edit_attendee'    => 'espresso_attendees',
90
-            'insert_attendee'  => 'espresso_attendees',
91
-            'update_attendee'  => 'espresso_attendees',
92
-        );
93
-        $this->_cpt_model_names = array(
94
-            'add_new_attendee' => 'EEM_Attendee',
95
-            'edit_attendee'    => 'EEM_Attendee',
96
-        );
97
-        $this->_cpt_edit_routes = array(
98
-            'espresso_attendees' => 'edit_attendee',
99
-        );
100
-        $this->_pagenow_map = array(
101
-            'add_new_attendee' => 'post-new.php',
102
-            'edit_attendee'    => 'post.php',
103
-            'trash'            => 'post.php',
104
-        );
105
-        add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
106
-        // add filters so that the comment urls don't take users to a confusing 404 page
107
-        add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
108
-    }
109
-
110
-
111
-    public function clear_comment_link($link, $comment, $args)
112
-    {
113
-        // gotta make sure this only happens on this route
114
-        $post_type = get_post_type($comment->comment_post_ID);
115
-        if ($post_type === 'espresso_attendees') {
116
-            return '#commentsdiv';
117
-        }
118
-        return $link;
119
-    }
120
-
121
-
122
-    protected function _ajax_hooks()
123
-    {
124
-        // todo: all hooks for registrations ajax goes in here
125
-        add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
126
-    }
127
-
128
-
129
-    protected function _define_page_props()
130
-    {
131
-        $this->_admin_page_title = $this->page_label;
132
-        $this->_labels = array(
133
-            'buttons'                      => array(
134
-                'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
135
-                'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
136
-                'edit'                => esc_html__('Edit Contact', 'event_espresso'),
137
-                'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
138
-                'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
139
-                'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
140
-                'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
141
-                'contact_list_export' => esc_html__("Export Data", "event_espresso"),
142
-            ),
143
-            'publishbox'                   => array(
144
-                'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
145
-                'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
146
-            ),
147
-            'hide_add_button_on_cpt_route' => array(
148
-                'edit_attendee' => true,
149
-            ),
150
-        );
151
-    }
152
-
153
-
154
-    /**
155
-     *        grab url requests and route them
156
-     *
157
-     * @access private
158
-     * @return void
159
-     */
160
-    public function _set_page_routes()
161
-    {
162
-        $this->_get_registration_status_array();
163
-        $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
164
-            ? $this->_req_data['_REG_ID'] : 0;
165
-        $reg_id = empty($reg_id) && ! empty($this->_req_data['reg_status_change_form']['REG_ID'])
166
-            ? $this->_req_data['reg_status_change_form']['REG_ID']
167
-            : $reg_id;
168
-        $att_id = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
169
-            ? $this->_req_data['ATT_ID'] : 0;
170
-        $att_id = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
171
-            ? $this->_req_data['post']
172
-            : $att_id;
173
-        $this->_page_routes = array(
174
-            'default'                             => array(
175
-                'func'       => '_registrations_overview_list_table',
176
-                'capability' => 'ee_read_registrations',
177
-            ),
178
-            'view_registration'                   => array(
179
-                'func'       => '_registration_details',
180
-                'capability' => 'ee_read_registration',
181
-                'obj_id'     => $reg_id,
182
-            ),
183
-            'edit_registration'                   => array(
184
-                'func'               => '_update_attendee_registration_form',
185
-                'noheader'           => true,
186
-                'headers_sent_route' => 'view_registration',
187
-                'capability'         => 'ee_edit_registration',
188
-                'obj_id'             => $reg_id,
189
-                '_REG_ID'            => $reg_id,
190
-            ),
191
-            'trash_registrations'                 => array(
192
-                'func'       => '_trash_or_restore_registrations',
193
-                'args'       => array('trash' => true),
194
-                'noheader'   => true,
195
-                'capability' => 'ee_delete_registrations',
196
-            ),
197
-            'restore_registrations'               => array(
198
-                'func'       => '_trash_or_restore_registrations',
199
-                'args'       => array('trash' => false),
200
-                'noheader'   => true,
201
-                'capability' => 'ee_delete_registrations',
202
-            ),
203
-            'delete_registrations'                => array(
204
-                'func'       => '_delete_registrations',
205
-                'noheader'   => true,
206
-                'capability' => 'ee_delete_registrations',
207
-            ),
208
-            'new_registration'                    => array(
209
-                'func'       => 'new_registration',
210
-                'capability' => 'ee_edit_registrations',
211
-            ),
212
-            'process_reg_step'                    => array(
213
-                'func'       => 'process_reg_step',
214
-                'noheader'   => true,
215
-                'capability' => 'ee_edit_registrations',
216
-            ),
217
-            'redirect_to_txn'                     => array(
218
-                'func'       => 'redirect_to_txn',
219
-                'noheader'   => true,
220
-                'capability' => 'ee_edit_registrations',
221
-            ),
222
-            'change_reg_status'                   => array(
223
-                'func'       => '_change_reg_status',
224
-                'noheader'   => true,
225
-                'capability' => 'ee_edit_registration',
226
-                'obj_id'     => $reg_id,
227
-            ),
228
-            'approve_registration'                => array(
229
-                'func'       => 'approve_registration',
230
-                'noheader'   => true,
231
-                'capability' => 'ee_edit_registration',
232
-                'obj_id'     => $reg_id,
233
-            ),
234
-            'approve_and_notify_registration'     => array(
235
-                'func'       => 'approve_registration',
236
-                'noheader'   => true,
237
-                'args'       => array(true),
238
-                'capability' => 'ee_edit_registration',
239
-                'obj_id'     => $reg_id,
240
-            ),
241
-            'approve_registrations'               => array(
242
-                'func'       => 'bulk_action_on_registrations',
243
-                'noheader'   => true,
244
-                'capability' => 'ee_edit_registrations',
245
-                'args'       => array('approve'),
246
-            ),
247
-            'approve_and_notify_registrations'    => array(
248
-                'func'       => 'bulk_action_on_registrations',
249
-                'noheader'   => true,
250
-                'capability' => 'ee_edit_registrations',
251
-                'args'       => array('approve', true),
252
-            ),
253
-            'decline_registration'                => array(
254
-                'func'       => 'decline_registration',
255
-                'noheader'   => true,
256
-                'capability' => 'ee_edit_registration',
257
-                'obj_id'     => $reg_id,
258
-            ),
259
-            'decline_and_notify_registration'     => array(
260
-                'func'       => 'decline_registration',
261
-                'noheader'   => true,
262
-                'args'       => array(true),
263
-                'capability' => 'ee_edit_registration',
264
-                'obj_id'     => $reg_id,
265
-            ),
266
-            'decline_registrations'               => array(
267
-                'func'       => 'bulk_action_on_registrations',
268
-                'noheader'   => true,
269
-                'capability' => 'ee_edit_registrations',
270
-                'args'       => array('decline'),
271
-            ),
272
-            'decline_and_notify_registrations'    => array(
273
-                'func'       => 'bulk_action_on_registrations',
274
-                'noheader'   => true,
275
-                'capability' => 'ee_edit_registrations',
276
-                'args'       => array('decline', true),
277
-            ),
278
-            'pending_registration'                => array(
279
-                'func'       => 'pending_registration',
280
-                'noheader'   => true,
281
-                'capability' => 'ee_edit_registration',
282
-                'obj_id'     => $reg_id,
283
-            ),
284
-            'pending_and_notify_registration'     => array(
285
-                'func'       => 'pending_registration',
286
-                'noheader'   => true,
287
-                'args'       => array(true),
288
-                'capability' => 'ee_edit_registration',
289
-                'obj_id'     => $reg_id,
290
-            ),
291
-            'pending_registrations'               => array(
292
-                'func'       => 'bulk_action_on_registrations',
293
-                'noheader'   => true,
294
-                'capability' => 'ee_edit_registrations',
295
-                'args'       => array('pending'),
296
-            ),
297
-            'pending_and_notify_registrations'    => array(
298
-                'func'       => 'bulk_action_on_registrations',
299
-                'noheader'   => true,
300
-                'capability' => 'ee_edit_registrations',
301
-                'args'       => array('pending', true),
302
-            ),
303
-            'no_approve_registration'             => array(
304
-                'func'       => 'not_approve_registration',
305
-                'noheader'   => true,
306
-                'capability' => 'ee_edit_registration',
307
-                'obj_id'     => $reg_id,
308
-            ),
309
-            'no_approve_and_notify_registration'  => array(
310
-                'func'       => 'not_approve_registration',
311
-                'noheader'   => true,
312
-                'args'       => array(true),
313
-                'capability' => 'ee_edit_registration',
314
-                'obj_id'     => $reg_id,
315
-            ),
316
-            'no_approve_registrations'            => array(
317
-                'func'       => 'bulk_action_on_registrations',
318
-                'noheader'   => true,
319
-                'capability' => 'ee_edit_registrations',
320
-                'args'       => array('not_approve'),
321
-            ),
322
-            'no_approve_and_notify_registrations' => array(
323
-                'func'       => 'bulk_action_on_registrations',
324
-                'noheader'   => true,
325
-                'capability' => 'ee_edit_registrations',
326
-                'args'       => array('not_approve', true),
327
-            ),
328
-            'cancel_registration'                 => array(
329
-                'func'       => 'cancel_registration',
330
-                'noheader'   => true,
331
-                'capability' => 'ee_edit_registration',
332
-                'obj_id'     => $reg_id,
333
-            ),
334
-            'cancel_and_notify_registration'      => array(
335
-                'func'       => 'cancel_registration',
336
-                'noheader'   => true,
337
-                'args'       => array(true),
338
-                'capability' => 'ee_edit_registration',
339
-                'obj_id'     => $reg_id,
340
-            ),
341
-            'cancel_registrations'                => array(
342
-                'func'       => 'bulk_action_on_registrations',
343
-                'noheader'   => true,
344
-                'capability' => 'ee_edit_registrations',
345
-                'args'       => array('cancel'),
346
-            ),
347
-            'cancel_and_notify_registrations'     => array(
348
-                'func'       => 'bulk_action_on_registrations',
349
-                'noheader'   => true,
350
-                'capability' => 'ee_edit_registrations',
351
-                'args'       => array('cancel', true),
352
-            ),
353
-            'wait_list_registration'              => array(
354
-                'func'       => 'wait_list_registration',
355
-                'noheader'   => true,
356
-                'capability' => 'ee_edit_registration',
357
-                'obj_id'     => $reg_id,
358
-            ),
359
-            'wait_list_and_notify_registration'   => array(
360
-                'func'       => 'wait_list_registration',
361
-                'noheader'   => true,
362
-                'args'       => array(true),
363
-                'capability' => 'ee_edit_registration',
364
-                'obj_id'     => $reg_id,
365
-            ),
366
-            'contact_list'                        => array(
367
-                'func'       => '_attendee_contact_list_table',
368
-                'capability' => 'ee_read_contacts',
369
-            ),
370
-            'add_new_attendee'                    => array(
371
-                'func' => '_create_new_cpt_item',
372
-                'args' => array(
373
-                    'new_attendee' => true,
374
-                    'capability'   => 'ee_edit_contacts',
375
-                ),
376
-            ),
377
-            'edit_attendee'                       => array(
378
-                'func'       => '_edit_cpt_item',
379
-                'capability' => 'ee_edit_contacts',
380
-                'obj_id'     => $att_id,
381
-            ),
382
-            'duplicate_attendee'                  => array(
383
-                'func'       => '_duplicate_attendee',
384
-                'noheader'   => true,
385
-                'capability' => 'ee_edit_contacts',
386
-                'obj_id'     => $att_id,
387
-            ),
388
-            'insert_attendee'                     => array(
389
-                'func'       => '_insert_or_update_attendee',
390
-                'args'       => array(
391
-                    'new_attendee' => true,
392
-                ),
393
-                'noheader'   => true,
394
-                'capability' => 'ee_edit_contacts',
395
-            ),
396
-            'update_attendee'                     => array(
397
-                'func'       => '_insert_or_update_attendee',
398
-                'args'       => array(
399
-                    'new_attendee' => false,
400
-                ),
401
-                'noheader'   => true,
402
-                'capability' => 'ee_edit_contacts',
403
-                'obj_id'     => $att_id,
404
-            ),
405
-            'trash_attendees'                     => array(
406
-                'func'       => '_trash_or_restore_attendees',
407
-                'args'       => array(
408
-                    'trash' => 'true',
409
-                ),
410
-                'noheader'   => true,
411
-                'capability' => 'ee_delete_contacts',
412
-            ),
413
-            'trash_attendee'                      => array(
414
-                'func'       => '_trash_or_restore_attendees',
415
-                'args'       => array(
416
-                    'trash' => true,
417
-                ),
418
-                'noheader'   => true,
419
-                'capability' => 'ee_delete_contacts',
420
-                'obj_id'     => $att_id,
421
-            ),
422
-            'restore_attendees'                   => array(
423
-                'func'       => '_trash_or_restore_attendees',
424
-                'args'       => array(
425
-                    'trash' => false,
426
-                ),
427
-                'noheader'   => true,
428
-                'capability' => 'ee_delete_contacts',
429
-                'obj_id'     => $att_id,
430
-            ),
431
-            'resend_registration'                 => array(
432
-                'func'       => '_resend_registration',
433
-                'noheader'   => true,
434
-                'capability' => 'ee_send_message',
435
-            ),
436
-            'registrations_report'                => array(
437
-                'func'       => '_registrations_report',
438
-                'noheader'   => true,
439
-                'capability' => 'ee_read_registrations',
440
-            ),
441
-            'contact_list_export'                 => array(
442
-                'func'       => '_contact_list_export',
443
-                'noheader'   => true,
444
-                'capability' => 'export',
445
-            ),
446
-            'contact_list_report'                 => array(
447
-                'func'       => '_contact_list_report',
448
-                'noheader'   => true,
449
-                'capability' => 'ee_read_contacts',
450
-            ),
451
-        );
452
-    }
453
-
454
-
455
-    protected function _set_page_config()
456
-    {
457
-        $this->_page_config = array(
458
-            'default'           => array(
459
-                'nav'           => array(
460
-                    'label' => esc_html__('Overview', 'event_espresso'),
461
-                    'order' => 5,
462
-                ),
463
-                'help_tabs'     => array(
464
-                    'registrations_overview_help_tab'                       => array(
465
-                        'title'    => esc_html__('Registrations Overview', 'event_espresso'),
466
-                        'filename' => 'registrations_overview',
467
-                    ),
468
-                    'registrations_overview_table_column_headings_help_tab' => array(
469
-                        'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
470
-                        'filename' => 'registrations_overview_table_column_headings',
471
-                    ),
472
-                    'registrations_overview_filters_help_tab'               => array(
473
-                        'title'    => esc_html__('Registration Filters', 'event_espresso'),
474
-                        'filename' => 'registrations_overview_filters',
475
-                    ),
476
-                    'registrations_overview_views_help_tab'                 => array(
477
-                        'title'    => esc_html__('Registration Views', 'event_espresso'),
478
-                        'filename' => 'registrations_overview_views',
479
-                    ),
480
-                    'registrations_regoverview_other_help_tab'              => array(
481
-                        'title'    => esc_html__('Registrations Other', 'event_espresso'),
482
-                        'filename' => 'registrations_overview_other',
483
-                    ),
484
-                ),
485
-                'help_tour'     => array('Registration_Overview_Help_Tour'),
486
-                'qtips'         => array('Registration_List_Table_Tips'),
487
-                'list_table'    => 'EE_Registrations_List_Table',
488
-                'require_nonce' => false,
489
-            ),
490
-            'view_registration' => array(
491
-                'nav'           => array(
492
-                    'label'      => esc_html__('REG Details', 'event_espresso'),
493
-                    'order'      => 15,
494
-                    'url'        => isset($this->_req_data['_REG_ID'])
495
-                        ? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
496
-                        : $this->_admin_base_url,
497
-                    'persistent' => false,
498
-                ),
499
-                'help_tabs'     => array(
500
-                    'registrations_details_help_tab'                    => array(
501
-                        'title'    => esc_html__('Registration Details', 'event_espresso'),
502
-                        'filename' => 'registrations_details',
503
-                    ),
504
-                    'registrations_details_table_help_tab'              => array(
505
-                        'title'    => esc_html__('Registration Details Table', 'event_espresso'),
506
-                        'filename' => 'registrations_details_table',
507
-                    ),
508
-                    'registrations_details_form_answers_help_tab'       => array(
509
-                        'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
510
-                        'filename' => 'registrations_details_form_answers',
511
-                    ),
512
-                    'registrations_details_registrant_details_help_tab' => array(
513
-                        'title'    => esc_html__('Contact Details', 'event_espresso'),
514
-                        'filename' => 'registrations_details_registrant_details',
515
-                    ),
516
-                ),
517
-                'help_tour'     => array('Registration_Details_Help_Tour'),
518
-                'metaboxes'     => array_merge(
519
-                    $this->_default_espresso_metaboxes,
520
-                    array('_registration_details_metaboxes')
521
-                ),
522
-                'require_nonce' => false,
523
-            ),
524
-            'new_registration'  => array(
525
-                'nav'           => array(
526
-                    'label'      => esc_html__('Add New Registration', 'event_espresso'),
527
-                    'url'        => '#',
528
-                    'order'      => 15,
529
-                    'persistent' => false,
530
-                ),
531
-                'metaboxes'     => $this->_default_espresso_metaboxes,
532
-                'labels'        => array(
533
-                    'publishbox' => esc_html__('Save Registration', 'event_espresso'),
534
-                ),
535
-                'require_nonce' => false,
536
-            ),
537
-            'add_new_attendee'  => array(
538
-                'nav'           => array(
539
-                    'label'      => esc_html__('Add Contact', 'event_espresso'),
540
-                    'order'      => 15,
541
-                    'persistent' => false,
542
-                ),
543
-                'metaboxes'     => array_merge(
544
-                    $this->_default_espresso_metaboxes,
545
-                    array('_publish_post_box', 'attendee_editor_metaboxes')
546
-                ),
547
-                'require_nonce' => false,
548
-            ),
549
-            'edit_attendee'     => array(
550
-                'nav'           => array(
551
-                    'label'      => esc_html__('Edit Contact', 'event_espresso'),
552
-                    'order'      => 15,
553
-                    'persistent' => false,
554
-                    'url'        => isset($this->_req_data['ATT_ID'])
555
-                        ? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
556
-                        : $this->_admin_base_url,
557
-                ),
558
-                'metaboxes'     => array('attendee_editor_metaboxes'),
559
-                'require_nonce' => false,
560
-            ),
561
-            'contact_list'      => array(
562
-                'nav'           => array(
563
-                    'label' => esc_html__('Contact List', 'event_espresso'),
564
-                    'order' => 20,
565
-                ),
566
-                'list_table'    => 'EE_Attendee_Contact_List_Table',
567
-                'help_tabs'     => array(
568
-                    'registrations_contact_list_help_tab'                       => array(
569
-                        'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
570
-                        'filename' => 'registrations_contact_list',
571
-                    ),
572
-                    'registrations_contact-list_table_column_headings_help_tab' => array(
573
-                        'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
574
-                        'filename' => 'registrations_contact_list_table_column_headings',
575
-                    ),
576
-                    'registrations_contact_list_views_help_tab'                 => array(
577
-                        'title'    => esc_html__('Contact List Views', 'event_espresso'),
578
-                        'filename' => 'registrations_contact_list_views',
579
-                    ),
580
-                    'registrations_contact_list_other_help_tab'                 => array(
581
-                        'title'    => esc_html__('Contact List Other', 'event_espresso'),
582
-                        'filename' => 'registrations_contact_list_other',
583
-                    ),
584
-                ),
585
-                'help_tour'     => array('Contact_List_Help_Tour'),
586
-                'metaboxes'     => array(),
587
-                'require_nonce' => false,
588
-            ),
589
-            // override default cpt routes
590
-            'create_new'        => '',
591
-            'edit'              => '',
592
-        );
593
-    }
594
-
595
-
596
-    /**
597
-     * The below methods aren't used by this class currently
598
-     */
599
-    protected function _add_screen_options()
600
-    {
601
-    }
602
-
603
-
604
-    protected function _add_feature_pointers()
605
-    {
606
-    }
607
-
608
-
609
-    public function admin_init()
610
-    {
611
-        EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
612
-            'click "Update Registration Questions" to save your changes',
613
-            'event_espresso'
614
-        );
615
-    }
616
-
617
-
618
-    public function admin_notices()
619
-    {
620
-    }
621
-
622
-
623
-    public function admin_footer_scripts()
624
-    {
625
-    }
626
-
627
-
628
-    /**
629
-     *        get list of registration statuses
630
-     *
631
-     * @access private
632
-     * @return void
633
-     * @throws EE_Error
634
-     */
635
-    private function _get_registration_status_array()
636
-    {
637
-        self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
638
-    }
639
-
640
-
641
-    protected function _add_screen_options_default()
642
-    {
643
-        $this->_per_page_screen_option();
644
-    }
645
-
646
-
647
-    protected function _add_screen_options_contact_list()
648
-    {
649
-        $page_title = $this->_admin_page_title;
650
-        $this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
651
-        $this->_per_page_screen_option();
652
-        $this->_admin_page_title = $page_title;
653
-    }
654
-
655
-
656
-    public function load_scripts_styles()
657
-    {
658
-        // style
659
-        wp_register_style(
660
-            'espresso_reg',
661
-            REG_ASSETS_URL . 'espresso_registrations_admin.css',
662
-            array('ee-admin-css'),
663
-            EVENT_ESPRESSO_VERSION
664
-        );
665
-        wp_enqueue_style('espresso_reg');
666
-        // script
667
-        wp_register_script(
668
-            'espresso_reg',
669
-            REG_ASSETS_URL . 'espresso_registrations_admin.js',
670
-            array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
671
-            EVENT_ESPRESSO_VERSION,
672
-            true
673
-        );
674
-        wp_enqueue_script('espresso_reg');
675
-    }
676
-
677
-
678
-    public function load_scripts_styles_edit_attendee()
679
-    {
680
-        // stuff to only show up on our attendee edit details page.
681
-        $attendee_details_translations = array(
682
-            'att_publish_text' => sprintf(
683
-                esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
684
-                $this->_cpt_model_obj->get_datetime('ATT_created')
685
-            ),
686
-        );
687
-        wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
688
-        wp_enqueue_script('jquery-validate');
689
-    }
690
-
691
-
692
-    public function load_scripts_styles_view_registration()
693
-    {
694
-        // styles
695
-        wp_enqueue_style('espresso-ui-theme');
696
-        // scripts
697
-        $this->_get_reg_custom_questions_form($this->_registration->ID());
698
-        $this->_reg_custom_questions_form->wp_enqueue_scripts(true);
699
-    }
700
-
701
-
702
-    public function load_scripts_styles_contact_list()
703
-    {
704
-        wp_dequeue_style('espresso_reg');
705
-        wp_register_style(
706
-            'espresso_att',
707
-            REG_ASSETS_URL . 'espresso_attendees_admin.css',
708
-            array('ee-admin-css'),
709
-            EVENT_ESPRESSO_VERSION
710
-        );
711
-        wp_enqueue_style('espresso_att');
712
-    }
713
-
714
-
715
-    public function load_scripts_styles_new_registration()
716
-    {
717
-        wp_register_script(
718
-            'ee-spco-for-admin',
719
-            REG_ASSETS_URL . 'spco_for_admin.js',
720
-            array('underscore', 'jquery'),
721
-            EVENT_ESPRESSO_VERSION,
722
-            true
723
-        );
724
-        wp_enqueue_script('ee-spco-for-admin');
725
-        add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
726
-        EE_Form_Section_Proper::wp_enqueue_scripts();
727
-        EED_Ticket_Selector::load_tckt_slctr_assets();
728
-        EE_Datepicker_Input::enqueue_styles_and_scripts();
729
-    }
730
-
731
-
732
-    public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
733
-    {
734
-        add_filter('FHEE_load_EE_messages', '__return_true');
735
-    }
736
-
737
-
738
-    public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
739
-    {
740
-        add_filter('FHEE_load_EE_messages', '__return_true');
741
-    }
742
-
743
-
744
-    protected function _set_list_table_views_default()
745
-    {
746
-        // for notification related bulk actions we need to make sure only active messengers have an option.
747
-        EED_Messages::set_autoloaders();
748
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
749
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
750
-        $active_mts = $message_resource_manager->list_of_active_message_types();
751
-        // key= bulk_action_slug, value= message type.
752
-        $match_array = array(
753
-            'approve_registrations'    => 'registration',
754
-            'decline_registrations'    => 'declined_registration',
755
-            'pending_registrations'    => 'pending_approval',
756
-            'no_approve_registrations' => 'not_approved_registration',
757
-            'cancel_registrations'     => 'cancelled_registration',
758
-        );
759
-        $can_send = EE_Registry::instance()->CAP->current_user_can(
760
-            'ee_send_message',
761
-            'batch_send_messages'
762
-        );
763
-        /** setup reg status bulk actions **/
764
-        $def_reg_status_actions['approve_registrations'] = esc_html__('Approve Registrations', 'event_espresso');
765
-        if ($can_send && in_array($match_array['approve_registrations'], $active_mts, true)) {
766
-            $def_reg_status_actions['approve_and_notify_registrations'] = esc_html__(
767
-                'Approve and Notify Registrations',
768
-                'event_espresso'
769
-            );
770
-        }
771
-        $def_reg_status_actions['decline_registrations'] = esc_html__('Decline Registrations', 'event_espresso');
772
-        if ($can_send && in_array($match_array['decline_registrations'], $active_mts, true)) {
773
-            $def_reg_status_actions['decline_and_notify_registrations'] = esc_html__(
774
-                'Decline and Notify Registrations',
775
-                'event_espresso'
776
-            );
777
-        }
778
-        $def_reg_status_actions['pending_registrations'] = esc_html__(
779
-            'Set Registrations to Pending Payment',
780
-            'event_espresso'
781
-        );
782
-        if ($can_send && in_array($match_array['pending_registrations'], $active_mts, true)) {
783
-            $def_reg_status_actions['pending_and_notify_registrations'] = esc_html__(
784
-                'Set Registrations to Pending Payment and Notify',
785
-                'event_espresso'
786
-            );
787
-        }
788
-        $def_reg_status_actions['no_approve_registrations'] = esc_html__(
789
-            'Set Registrations to Not Approved',
790
-            'event_espresso'
791
-        );
792
-        if ($can_send && in_array($match_array['no_approve_registrations'], $active_mts, true)) {
793
-            $def_reg_status_actions['no_approve_and_notify_registrations'] = esc_html__(
794
-                'Set Registrations to Not Approved and Notify',
795
-                'event_espresso'
796
-            );
797
-        }
798
-        $def_reg_status_actions['cancel_registrations'] = esc_html__('Cancel Registrations', 'event_espresso');
799
-        if ($can_send && in_array($match_array['cancel_registrations'], $active_mts, true)) {
800
-            $def_reg_status_actions['cancel_and_notify_registrations'] = esc_html__(
801
-                'Cancel Registrations and Notify',
802
-                'event_espresso'
803
-            );
804
-        }
805
-        $def_reg_status_actions = apply_filters(
806
-            'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
807
-            $def_reg_status_actions,
808
-            $active_mts,
809
-            $can_send
810
-        );
811
-
812
-        $this->_views = array(
813
-            'all'   => array(
814
-                'slug'        => 'all',
815
-                'label'       => esc_html__('View All Registrations', 'event_espresso'),
816
-                'count'       => 0,
817
-                'bulk_action' => array_merge(
818
-                    $def_reg_status_actions,
819
-                    array(
820
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
821
-                    )
822
-                ),
823
-            ),
824
-            'month' => array(
825
-                'slug'        => 'month',
826
-                'label'       => esc_html__('This Month', 'event_espresso'),
827
-                'count'       => 0,
828
-                'bulk_action' => array_merge(
829
-                    $def_reg_status_actions,
830
-                    array(
831
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
832
-                    )
833
-                ),
834
-            ),
835
-            'today' => array(
836
-                'slug'        => 'today',
837
-                'label'       => sprintf(
838
-                    esc_html__('Today - %s', 'event_espresso'),
839
-                    date('M d, Y', current_time('timestamp'))
840
-                ),
841
-                'count'       => 0,
842
-                'bulk_action' => array_merge(
843
-                    $def_reg_status_actions,
844
-                    array(
845
-                        'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
846
-                    )
847
-                ),
848
-            ),
849
-        );
850
-        if (EE_Registry::instance()->CAP->current_user_can(
851
-            'ee_delete_registrations',
852
-            'espresso_registrations_delete_registration'
853
-        )) {
854
-            $this->_views['incomplete'] = array(
855
-                'slug'        => 'incomplete',
856
-                'label'       => esc_html__('Incomplete', 'event_espresso'),
857
-                'count'       => 0,
858
-                'bulk_action' => array(
859
-                    'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
860
-                ),
861
-            );
862
-            $this->_views['trash'] = array(
863
-                'slug'        => 'trash',
864
-                'label'       => esc_html__('Trash', 'event_espresso'),
865
-                'count'       => 0,
866
-                'bulk_action' => array(
867
-                    'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
868
-                    'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
869
-                ),
870
-            );
871
-        }
872
-    }
873
-
874
-
875
-    protected function _set_list_table_views_contact_list()
876
-    {
877
-        $this->_views = array(
878
-            'in_use' => array(
879
-                'slug'        => 'in_use',
880
-                'label'       => esc_html__('In Use', 'event_espresso'),
881
-                'count'       => 0,
882
-                'bulk_action' => array(
883
-                    'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
884
-                ),
885
-            ),
886
-        );
887
-        if (EE_Registry::instance()->CAP->current_user_can(
888
-            'ee_delete_contacts',
889
-            'espresso_registrations_trash_attendees'
890
-        )
891
-        ) {
892
-            $this->_views['trash'] = array(
893
-                'slug'        => 'trash',
894
-                'label'       => esc_html__('Trash', 'event_espresso'),
895
-                'count'       => 0,
896
-                'bulk_action' => array(
897
-                    'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
898
-                ),
899
-            );
900
-        }
901
-    }
902
-
903
-
904
-    protected function _registration_legend_items()
905
-    {
906
-        $fc_items = array(
907
-            'star-icon'        => array(
908
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
909
-                'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
910
-            ),
911
-            'view_details'     => array(
912
-                'class' => 'dashicons dashicons-clipboard',
913
-                'desc'  => esc_html__('View Registration Details', 'event_espresso'),
914
-            ),
915
-            'edit_attendee'    => array(
916
-                'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
917
-                'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
918
-            ),
919
-            'view_transaction' => array(
920
-                'class' => 'dashicons dashicons-cart',
921
-                'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
922
-            ),
923
-            'view_invoice'     => array(
924
-                'class' => 'dashicons dashicons-media-spreadsheet',
925
-                'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
926
-            ),
927
-        );
928
-        if (EE_Registry::instance()->CAP->current_user_can(
929
-            'ee_send_message',
930
-            'espresso_registrations_resend_registration'
931
-        )) {
932
-            $fc_items['resend_registration'] = array(
933
-                'class' => 'dashicons dashicons-email-alt',
934
-                'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
935
-            );
936
-        } else {
937
-            $fc_items['blank'] = array('class' => 'blank', 'desc' => '');
938
-        }
939
-        if (EE_Registry::instance()->CAP->current_user_can(
940
-            'ee_read_global_messages',
941
-            'view_filtered_messages'
942
-        )) {
943
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
944
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
945
-                $fc_items['view_related_messages'] = array(
946
-                    'class' => $related_for_icon['css_class'],
947
-                    'desc'  => $related_for_icon['label'],
948
-                );
949
-            }
950
-        }
951
-        $sc_items = array(
952
-            'approved_status'   => array(
953
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
954
-                'desc'  => EEH_Template::pretty_status(
955
-                    EEM_Registration::status_id_approved,
956
-                    false,
957
-                    'sentence'
958
-                ),
959
-            ),
960
-            'pending_status'    => array(
961
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
962
-                'desc'  => EEH_Template::pretty_status(
963
-                    EEM_Registration::status_id_pending_payment,
964
-                    false,
965
-                    'sentence'
966
-                ),
967
-            ),
968
-            'wait_list'         => array(
969
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
970
-                'desc'  => EEH_Template::pretty_status(
971
-                    EEM_Registration::status_id_wait_list,
972
-                    false,
973
-                    'sentence'
974
-                ),
975
-            ),
976
-            'incomplete_status' => array(
977
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
978
-                'desc'  => EEH_Template::pretty_status(
979
-                    EEM_Registration::status_id_incomplete,
980
-                    false,
981
-                    'sentence'
982
-                ),
983
-            ),
984
-            'not_approved'      => array(
985
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
986
-                'desc'  => EEH_Template::pretty_status(
987
-                    EEM_Registration::status_id_not_approved,
988
-                    false,
989
-                    'sentence'
990
-                ),
991
-            ),
992
-            'declined_status'   => array(
993
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
994
-                'desc'  => EEH_Template::pretty_status(
995
-                    EEM_Registration::status_id_declined,
996
-                    false,
997
-                    'sentence'
998
-                ),
999
-            ),
1000
-            'cancelled_status'  => array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1002
-                'desc'  => EEH_Template::pretty_status(
1003
-                    EEM_Registration::status_id_cancelled,
1004
-                    false,
1005
-                    'sentence'
1006
-                ),
1007
-            ),
1008
-        );
1009
-        return array_merge($fc_items, $sc_items);
1010
-    }
1011
-
1012
-
1013
-
1014
-    /***************************************        REGISTRATION OVERVIEW        **************************************/
1015
-    /**
1016
-     * @throws \EE_Error
1017
-     */
1018
-    protected function _registrations_overview_list_table()
1019
-    {
1020
-        $this->_template_args['admin_page_header'] = '';
1021
-        $EVT_ID = ! empty($this->_req_data['event_id'])
1022
-            ? absint($this->_req_data['event_id'])
1023
-            : 0;
1024
-        $ATT_ID = ! empty($this->_req_data['ATT_ID'])
1025
-            ? absint($this->_req_data['ATT_ID'])
1026
-            : 0;
1027
-        if ($ATT_ID) {
1028
-            $attendee = EEM_Attendee::instance()->get_one_by_ID($ATT_ID);
1029
-            if ($attendee instanceof EE_Attendee) {
1030
-                $this->_template_args['admin_page_header'] = sprintf(
1031
-                    esc_html__(
1032
-                        '%1$s Viewing registrations for %2$s%3$s',
1033
-                        'event_espresso'
1034
-                    ),
1035
-                    '<h3 style="line-height:1.5em;">',
1036
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
1037
-                        array(
1038
-                            'action' => 'edit_attendee',
1039
-                            'post'   => $ATT_ID,
1040
-                        ),
1041
-                        REG_ADMIN_URL
1042
-                    ) . '">' . $attendee->full_name() . '</a>',
1043
-                    '</h3>'
1044
-                );
1045
-            }
1046
-        }
1047
-        if ($EVT_ID) {
1048
-            if (EE_Registry::instance()->CAP->current_user_can(
1049
-                'ee_edit_registrations',
1050
-                'espresso_registrations_new_registration',
1051
-                $EVT_ID
1052
-            )) {
1053
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1054
-                    'new_registration',
1055
-                    'add-registrant',
1056
-                    array('event_id' => $EVT_ID),
1057
-                    'add-new-h2'
1058
-                );
1059
-            }
1060
-            $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
1061
-            if ($event instanceof EE_Event) {
1062
-                $this->_template_args['admin_page_header'] = sprintf(
1063
-                    esc_html__(
1064
-                        '%s Viewing registrations for the event: %s%s',
1065
-                        'event_espresso'
1066
-                    ),
1067
-                    '<h3 style="line-height:1.5em;">',
1068
-                    '<br /><a href="'
1069
-                    . EE_Admin_Page::add_query_args_and_nonce(
1070
-                        array(
1071
-                            'action' => 'edit',
1072
-                            'post'   => $event->ID(),
1073
-                        ),
1074
-                        EVENTS_ADMIN_URL
1075
-                    )
1076
-                    . '">&nbsp;'
1077
-                    . $event->get('EVT_name')
1078
-                    . '&nbsp;</a>&nbsp;',
1079
-                    '</h3>'
1080
-                );
1081
-            }
1082
-            $DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
1083
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1084
-            if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
1085
-                $this->_template_args['admin_page_header'] = substr(
1086
-                    $this->_template_args['admin_page_header'],
1087
-                    0,
1088
-                    -5
1089
-                );
1090
-                $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1091
-                $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1092
-                $this->_template_args['admin_page_header'] .= $datetime->name();
1093
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1094
-                $this->_template_args['admin_page_header'] .= '</span></h3>';
1095
-            }
1096
-        }
1097
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
1098
-        $this->display_admin_list_table_page_with_no_sidebar();
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * This sets the _registration property for the registration details screen
1104
-     *
1105
-     * @access private
1106
-     * @return bool
1107
-     * @throws EE_Error
1108
-     * @throws InvalidArgumentException
1109
-     * @throws InvalidDataTypeException
1110
-     * @throws InvalidInterfaceException
1111
-     */
1112
-    private function _set_registration_object()
1113
-    {
1114
-        // get out if we've already set the object
1115
-        if ($this->_registration instanceof EE_Registration) {
1116
-            return true;
1117
-        }
1118
-        $REG = EEM_Registration::instance();
1119
-        $REG_ID = (! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1120
-        if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1121
-            return true;
1122
-        } else {
1123
-            $error_msg = sprintf(
1124
-                esc_html__(
1125
-                    'An error occurred and the details for Registration ID #%s could not be retrieved.',
1126
-                    'event_espresso'
1127
-                ),
1128
-                $REG_ID
1129
-            );
1130
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1131
-            $this->_registration = null;
1132
-            return false;
1133
-        }
1134
-    }
1135
-
1136
-
1137
-    /**
1138
-     * Used to retrieve registrations for the list table.
1139
-     *
1140
-     * @param int  $per_page
1141
-     * @param bool $count
1142
-     * @param bool $this_month
1143
-     * @param bool $today
1144
-     * @return EE_Registration[]|int
1145
-     * @throws EE_Error
1146
-     * @throws InvalidArgumentException
1147
-     * @throws InvalidDataTypeException
1148
-     * @throws InvalidInterfaceException
1149
-     */
1150
-    public function get_registrations(
1151
-        $per_page = 10,
1152
-        $count = false,
1153
-        $this_month = false,
1154
-        $today = false
1155
-    ) {
1156
-        if ($this_month) {
1157
-            $this->_req_data['status'] = 'month';
1158
-        }
1159
-        if ($today) {
1160
-            $this->_req_data['status'] = 'today';
1161
-        }
1162
-        $query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1163
-        /**
1164
-         * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1165
-         *
1166
-         * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1167
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1168
-         *                             or if you have the development copy of EE you can view this at the path:
1169
-         *                             /docs/G--Model-System/model-query-params.md
1170
-         */
1171
-        $query_params['group_by'] = '';
1172
-
1173
-        return $count
1174
-            ? EEM_Registration::instance()->count($query_params)
1175
-            /** @type EE_Registration[] */
1176
-            : EEM_Registration::instance()->get_all($query_params);
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * Retrieves the query parameters to be used by the Registration model for getting registrations.
1182
-     * Note: this listens to values on the request for some of the query parameters.
1183
-     *
1184
-     * @param array $request
1185
-     * @param int   $per_page
1186
-     * @param bool  $count
1187
-     * @return array
1188
-     * @throws EE_Error
1189
-     */
1190
-    protected function _get_registration_query_parameters(
1191
-        $request = array(),
1192
-        $per_page = 10,
1193
-        $count = false
1194
-    ) {
1195
-
1196
-        $query_params = array(
1197
-            0                          => $this->_get_where_conditions_for_registrations_query(
1198
-                $request
1199
-            ),
1200
-            'caps'                     => EEM_Registration::caps_read_admin,
1201
-            'default_where_conditions' => 'this_model_only',
1202
-        );
1203
-        if (! $count) {
1204
-            $query_params = array_merge(
1205
-                $query_params,
1206
-                $this->_get_orderby_for_registrations_query(),
1207
-                $this->_get_limit($per_page)
1208
-            );
1209
-        }
1210
-
1211
-        return $query_params;
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * This will add ATT_ID to the provided $where array for EE model query parameters.
1217
-     *
1218
-     * @param array $request usually the same as $this->_req_data but not necessarily
1219
-     * @return array
1220
-     */
1221
-    protected function addAttendeeIdToWhereConditions(array $request)
1222
-    {
1223
-        $where = array();
1224
-        if (! empty($request['ATT_ID'])) {
1225
-            $where['ATT_ID'] = absint($request['ATT_ID']);
1226
-        }
1227
-        return $where;
1228
-    }
1229
-
1230
-
1231
-    /**
1232
-     * This will add EVT_ID to the provided $where array for EE model query parameters.
1233
-     *
1234
-     * @param array $request usually the same as $this->_req_data but not necessarily
1235
-     * @return array
1236
-     */
1237
-    protected function _add_event_id_to_where_conditions(array $request)
1238
-    {
1239
-        $where = array();
1240
-        if (! empty($request['event_id'])) {
1241
-            $where['EVT_ID'] = absint($request['event_id']);
1242
-        }
1243
-        return $where;
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Adds category ID if it exists in the request to the where conditions for the registrations query.
1249
-     *
1250
-     * @param array $request usually the same as $this->_req_data but not necessarily
1251
-     * @return array
1252
-     */
1253
-    protected function _add_category_id_to_where_conditions(array $request)
1254
-    {
1255
-        $where = array();
1256
-        if (! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
1257
-            $where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1258
-        }
1259
-        return $where;
1260
-    }
1261
-
1262
-
1263
-    /**
1264
-     * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1265
-     *
1266
-     * @param array $request usually the same as $this->_req_data but not necessarily
1267
-     * @return array
1268
-     */
1269
-    protected function _add_datetime_id_to_where_conditions(array $request)
1270
-    {
1271
-        $where = array();
1272
-        if (! empty($request['datetime_id'])) {
1273
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1274
-        }
1275
-        if (! empty($request['DTT_ID'])) {
1276
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1277
-        }
1278
-        return $where;
1279
-    }
1280
-
1281
-
1282
-    /**
1283
-     * Adds the correct registration status to the where conditions for the registrations query.
1284
-     *
1285
-     * @param array $request usually the same as $this->_req_data but not necessarily
1286
-     * @return array
1287
-     */
1288
-    protected function _add_registration_status_to_where_conditions(array $request)
1289
-    {
1290
-        $where = array();
1291
-        $view = EEH_Array::is_set($request, 'status', '');
1292
-        $registration_status = ! empty($request['_reg_status'])
1293
-            ? sanitize_text_field($request['_reg_status'])
1294
-            : '';
1295
-
1296
-        /*
22
+	/**
23
+	 * @var EE_Registration
24
+	 */
25
+	private $_registration;
26
+
27
+	/**
28
+	 * @var EE_Event
29
+	 */
30
+	private $_reg_event;
31
+
32
+	/**
33
+	 * @var EE_Session
34
+	 */
35
+	private $_session;
36
+
37
+	private static $_reg_status;
38
+
39
+	/**
40
+	 * Form for displaying the custom questions for this registration.
41
+	 * This gets used a few times throughout the request so its best to cache it
42
+	 *
43
+	 * @var EE_Registration_Custom_Questions_Form
44
+	 */
45
+	protected $_reg_custom_questions_form = null;
46
+
47
+
48
+	/**
49
+	 *        constructor
50
+	 *
51
+	 * @Constructor
52
+	 * @access public
53
+	 * @param bool $routing
54
+	 * @return Registrations_Admin_Page
55
+	 */
56
+	public function __construct($routing = true)
57
+	{
58
+		parent::__construct($routing);
59
+		add_action('wp_loaded', array($this, 'wp_loaded'));
60
+	}
61
+
62
+
63
+	public function wp_loaded()
64
+	{
65
+		// when adding a new registration...
66
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
67
+			EE_System::do_not_cache();
68
+			if (! isset($this->_req_data['processing_registration'])
69
+				|| absint($this->_req_data['processing_registration']) !== 1
70
+			) {
71
+				// and it's NOT the attendee information reg step
72
+				// force cookie expiration by setting time to last week
73
+				setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
74
+				// and update the global
75
+				$_COOKIE['ee_registration_added'] = 0;
76
+			}
77
+		}
78
+	}
79
+
80
+
81
+	protected function _init_page_props()
82
+	{
83
+		$this->page_slug = REG_PG_SLUG;
84
+		$this->_admin_base_url = REG_ADMIN_URL;
85
+		$this->_admin_base_path = REG_ADMIN;
86
+		$this->page_label = esc_html__('Registrations', 'event_espresso');
87
+		$this->_cpt_routes = array(
88
+			'add_new_attendee' => 'espresso_attendees',
89
+			'edit_attendee'    => 'espresso_attendees',
90
+			'insert_attendee'  => 'espresso_attendees',
91
+			'update_attendee'  => 'espresso_attendees',
92
+		);
93
+		$this->_cpt_model_names = array(
94
+			'add_new_attendee' => 'EEM_Attendee',
95
+			'edit_attendee'    => 'EEM_Attendee',
96
+		);
97
+		$this->_cpt_edit_routes = array(
98
+			'espresso_attendees' => 'edit_attendee',
99
+		);
100
+		$this->_pagenow_map = array(
101
+			'add_new_attendee' => 'post-new.php',
102
+			'edit_attendee'    => 'post.php',
103
+			'trash'            => 'post.php',
104
+		);
105
+		add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
106
+		// add filters so that the comment urls don't take users to a confusing 404 page
107
+		add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
108
+	}
109
+
110
+
111
+	public function clear_comment_link($link, $comment, $args)
112
+	{
113
+		// gotta make sure this only happens on this route
114
+		$post_type = get_post_type($comment->comment_post_ID);
115
+		if ($post_type === 'espresso_attendees') {
116
+			return '#commentsdiv';
117
+		}
118
+		return $link;
119
+	}
120
+
121
+
122
+	protected function _ajax_hooks()
123
+	{
124
+		// todo: all hooks for registrations ajax goes in here
125
+		add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
126
+	}
127
+
128
+
129
+	protected function _define_page_props()
130
+	{
131
+		$this->_admin_page_title = $this->page_label;
132
+		$this->_labels = array(
133
+			'buttons'                      => array(
134
+				'add-registrant'      => esc_html__('Add New Registration', 'event_espresso'),
135
+				'add-attendee'        => esc_html__('Add Contact', 'event_espresso'),
136
+				'edit'                => esc_html__('Edit Contact', 'event_espresso'),
137
+				'report'              => esc_html__("Event Registrations CSV Report", "event_espresso"),
138
+				'report_all'          => esc_html__('All Registrations CSV Report', 'event_espresso'),
139
+				'report_filtered'     => esc_html__('Filtered CSV Report', 'event_espresso'),
140
+				'contact_list_report' => esc_html__('Contact List Report', 'event_espresso'),
141
+				'contact_list_export' => esc_html__("Export Data", "event_espresso"),
142
+			),
143
+			'publishbox'                   => array(
144
+				'add_new_attendee' => esc_html__("Add Contact Record", 'event_espresso'),
145
+				'edit_attendee'    => esc_html__("Update Contact Record", 'event_espresso'),
146
+			),
147
+			'hide_add_button_on_cpt_route' => array(
148
+				'edit_attendee' => true,
149
+			),
150
+		);
151
+	}
152
+
153
+
154
+	/**
155
+	 *        grab url requests and route them
156
+	 *
157
+	 * @access private
158
+	 * @return void
159
+	 */
160
+	public function _set_page_routes()
161
+	{
162
+		$this->_get_registration_status_array();
163
+		$reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
164
+			? $this->_req_data['_REG_ID'] : 0;
165
+		$reg_id = empty($reg_id) && ! empty($this->_req_data['reg_status_change_form']['REG_ID'])
166
+			? $this->_req_data['reg_status_change_form']['REG_ID']
167
+			: $reg_id;
168
+		$att_id = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
169
+			? $this->_req_data['ATT_ID'] : 0;
170
+		$att_id = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post'])
171
+			? $this->_req_data['post']
172
+			: $att_id;
173
+		$this->_page_routes = array(
174
+			'default'                             => array(
175
+				'func'       => '_registrations_overview_list_table',
176
+				'capability' => 'ee_read_registrations',
177
+			),
178
+			'view_registration'                   => array(
179
+				'func'       => '_registration_details',
180
+				'capability' => 'ee_read_registration',
181
+				'obj_id'     => $reg_id,
182
+			),
183
+			'edit_registration'                   => array(
184
+				'func'               => '_update_attendee_registration_form',
185
+				'noheader'           => true,
186
+				'headers_sent_route' => 'view_registration',
187
+				'capability'         => 'ee_edit_registration',
188
+				'obj_id'             => $reg_id,
189
+				'_REG_ID'            => $reg_id,
190
+			),
191
+			'trash_registrations'                 => array(
192
+				'func'       => '_trash_or_restore_registrations',
193
+				'args'       => array('trash' => true),
194
+				'noheader'   => true,
195
+				'capability' => 'ee_delete_registrations',
196
+			),
197
+			'restore_registrations'               => array(
198
+				'func'       => '_trash_or_restore_registrations',
199
+				'args'       => array('trash' => false),
200
+				'noheader'   => true,
201
+				'capability' => 'ee_delete_registrations',
202
+			),
203
+			'delete_registrations'                => array(
204
+				'func'       => '_delete_registrations',
205
+				'noheader'   => true,
206
+				'capability' => 'ee_delete_registrations',
207
+			),
208
+			'new_registration'                    => array(
209
+				'func'       => 'new_registration',
210
+				'capability' => 'ee_edit_registrations',
211
+			),
212
+			'process_reg_step'                    => array(
213
+				'func'       => 'process_reg_step',
214
+				'noheader'   => true,
215
+				'capability' => 'ee_edit_registrations',
216
+			),
217
+			'redirect_to_txn'                     => array(
218
+				'func'       => 'redirect_to_txn',
219
+				'noheader'   => true,
220
+				'capability' => 'ee_edit_registrations',
221
+			),
222
+			'change_reg_status'                   => array(
223
+				'func'       => '_change_reg_status',
224
+				'noheader'   => true,
225
+				'capability' => 'ee_edit_registration',
226
+				'obj_id'     => $reg_id,
227
+			),
228
+			'approve_registration'                => array(
229
+				'func'       => 'approve_registration',
230
+				'noheader'   => true,
231
+				'capability' => 'ee_edit_registration',
232
+				'obj_id'     => $reg_id,
233
+			),
234
+			'approve_and_notify_registration'     => array(
235
+				'func'       => 'approve_registration',
236
+				'noheader'   => true,
237
+				'args'       => array(true),
238
+				'capability' => 'ee_edit_registration',
239
+				'obj_id'     => $reg_id,
240
+			),
241
+			'approve_registrations'               => array(
242
+				'func'       => 'bulk_action_on_registrations',
243
+				'noheader'   => true,
244
+				'capability' => 'ee_edit_registrations',
245
+				'args'       => array('approve'),
246
+			),
247
+			'approve_and_notify_registrations'    => array(
248
+				'func'       => 'bulk_action_on_registrations',
249
+				'noheader'   => true,
250
+				'capability' => 'ee_edit_registrations',
251
+				'args'       => array('approve', true),
252
+			),
253
+			'decline_registration'                => array(
254
+				'func'       => 'decline_registration',
255
+				'noheader'   => true,
256
+				'capability' => 'ee_edit_registration',
257
+				'obj_id'     => $reg_id,
258
+			),
259
+			'decline_and_notify_registration'     => array(
260
+				'func'       => 'decline_registration',
261
+				'noheader'   => true,
262
+				'args'       => array(true),
263
+				'capability' => 'ee_edit_registration',
264
+				'obj_id'     => $reg_id,
265
+			),
266
+			'decline_registrations'               => array(
267
+				'func'       => 'bulk_action_on_registrations',
268
+				'noheader'   => true,
269
+				'capability' => 'ee_edit_registrations',
270
+				'args'       => array('decline'),
271
+			),
272
+			'decline_and_notify_registrations'    => array(
273
+				'func'       => 'bulk_action_on_registrations',
274
+				'noheader'   => true,
275
+				'capability' => 'ee_edit_registrations',
276
+				'args'       => array('decline', true),
277
+			),
278
+			'pending_registration'                => array(
279
+				'func'       => 'pending_registration',
280
+				'noheader'   => true,
281
+				'capability' => 'ee_edit_registration',
282
+				'obj_id'     => $reg_id,
283
+			),
284
+			'pending_and_notify_registration'     => array(
285
+				'func'       => 'pending_registration',
286
+				'noheader'   => true,
287
+				'args'       => array(true),
288
+				'capability' => 'ee_edit_registration',
289
+				'obj_id'     => $reg_id,
290
+			),
291
+			'pending_registrations'               => array(
292
+				'func'       => 'bulk_action_on_registrations',
293
+				'noheader'   => true,
294
+				'capability' => 'ee_edit_registrations',
295
+				'args'       => array('pending'),
296
+			),
297
+			'pending_and_notify_registrations'    => array(
298
+				'func'       => 'bulk_action_on_registrations',
299
+				'noheader'   => true,
300
+				'capability' => 'ee_edit_registrations',
301
+				'args'       => array('pending', true),
302
+			),
303
+			'no_approve_registration'             => array(
304
+				'func'       => 'not_approve_registration',
305
+				'noheader'   => true,
306
+				'capability' => 'ee_edit_registration',
307
+				'obj_id'     => $reg_id,
308
+			),
309
+			'no_approve_and_notify_registration'  => array(
310
+				'func'       => 'not_approve_registration',
311
+				'noheader'   => true,
312
+				'args'       => array(true),
313
+				'capability' => 'ee_edit_registration',
314
+				'obj_id'     => $reg_id,
315
+			),
316
+			'no_approve_registrations'            => array(
317
+				'func'       => 'bulk_action_on_registrations',
318
+				'noheader'   => true,
319
+				'capability' => 'ee_edit_registrations',
320
+				'args'       => array('not_approve'),
321
+			),
322
+			'no_approve_and_notify_registrations' => array(
323
+				'func'       => 'bulk_action_on_registrations',
324
+				'noheader'   => true,
325
+				'capability' => 'ee_edit_registrations',
326
+				'args'       => array('not_approve', true),
327
+			),
328
+			'cancel_registration'                 => array(
329
+				'func'       => 'cancel_registration',
330
+				'noheader'   => true,
331
+				'capability' => 'ee_edit_registration',
332
+				'obj_id'     => $reg_id,
333
+			),
334
+			'cancel_and_notify_registration'      => array(
335
+				'func'       => 'cancel_registration',
336
+				'noheader'   => true,
337
+				'args'       => array(true),
338
+				'capability' => 'ee_edit_registration',
339
+				'obj_id'     => $reg_id,
340
+			),
341
+			'cancel_registrations'                => array(
342
+				'func'       => 'bulk_action_on_registrations',
343
+				'noheader'   => true,
344
+				'capability' => 'ee_edit_registrations',
345
+				'args'       => array('cancel'),
346
+			),
347
+			'cancel_and_notify_registrations'     => array(
348
+				'func'       => 'bulk_action_on_registrations',
349
+				'noheader'   => true,
350
+				'capability' => 'ee_edit_registrations',
351
+				'args'       => array('cancel', true),
352
+			),
353
+			'wait_list_registration'              => array(
354
+				'func'       => 'wait_list_registration',
355
+				'noheader'   => true,
356
+				'capability' => 'ee_edit_registration',
357
+				'obj_id'     => $reg_id,
358
+			),
359
+			'wait_list_and_notify_registration'   => array(
360
+				'func'       => 'wait_list_registration',
361
+				'noheader'   => true,
362
+				'args'       => array(true),
363
+				'capability' => 'ee_edit_registration',
364
+				'obj_id'     => $reg_id,
365
+			),
366
+			'contact_list'                        => array(
367
+				'func'       => '_attendee_contact_list_table',
368
+				'capability' => 'ee_read_contacts',
369
+			),
370
+			'add_new_attendee'                    => array(
371
+				'func' => '_create_new_cpt_item',
372
+				'args' => array(
373
+					'new_attendee' => true,
374
+					'capability'   => 'ee_edit_contacts',
375
+				),
376
+			),
377
+			'edit_attendee'                       => array(
378
+				'func'       => '_edit_cpt_item',
379
+				'capability' => 'ee_edit_contacts',
380
+				'obj_id'     => $att_id,
381
+			),
382
+			'duplicate_attendee'                  => array(
383
+				'func'       => '_duplicate_attendee',
384
+				'noheader'   => true,
385
+				'capability' => 'ee_edit_contacts',
386
+				'obj_id'     => $att_id,
387
+			),
388
+			'insert_attendee'                     => array(
389
+				'func'       => '_insert_or_update_attendee',
390
+				'args'       => array(
391
+					'new_attendee' => true,
392
+				),
393
+				'noheader'   => true,
394
+				'capability' => 'ee_edit_contacts',
395
+			),
396
+			'update_attendee'                     => array(
397
+				'func'       => '_insert_or_update_attendee',
398
+				'args'       => array(
399
+					'new_attendee' => false,
400
+				),
401
+				'noheader'   => true,
402
+				'capability' => 'ee_edit_contacts',
403
+				'obj_id'     => $att_id,
404
+			),
405
+			'trash_attendees'                     => array(
406
+				'func'       => '_trash_or_restore_attendees',
407
+				'args'       => array(
408
+					'trash' => 'true',
409
+				),
410
+				'noheader'   => true,
411
+				'capability' => 'ee_delete_contacts',
412
+			),
413
+			'trash_attendee'                      => array(
414
+				'func'       => '_trash_or_restore_attendees',
415
+				'args'       => array(
416
+					'trash' => true,
417
+				),
418
+				'noheader'   => true,
419
+				'capability' => 'ee_delete_contacts',
420
+				'obj_id'     => $att_id,
421
+			),
422
+			'restore_attendees'                   => array(
423
+				'func'       => '_trash_or_restore_attendees',
424
+				'args'       => array(
425
+					'trash' => false,
426
+				),
427
+				'noheader'   => true,
428
+				'capability' => 'ee_delete_contacts',
429
+				'obj_id'     => $att_id,
430
+			),
431
+			'resend_registration'                 => array(
432
+				'func'       => '_resend_registration',
433
+				'noheader'   => true,
434
+				'capability' => 'ee_send_message',
435
+			),
436
+			'registrations_report'                => array(
437
+				'func'       => '_registrations_report',
438
+				'noheader'   => true,
439
+				'capability' => 'ee_read_registrations',
440
+			),
441
+			'contact_list_export'                 => array(
442
+				'func'       => '_contact_list_export',
443
+				'noheader'   => true,
444
+				'capability' => 'export',
445
+			),
446
+			'contact_list_report'                 => array(
447
+				'func'       => '_contact_list_report',
448
+				'noheader'   => true,
449
+				'capability' => 'ee_read_contacts',
450
+			),
451
+		);
452
+	}
453
+
454
+
455
+	protected function _set_page_config()
456
+	{
457
+		$this->_page_config = array(
458
+			'default'           => array(
459
+				'nav'           => array(
460
+					'label' => esc_html__('Overview', 'event_espresso'),
461
+					'order' => 5,
462
+				),
463
+				'help_tabs'     => array(
464
+					'registrations_overview_help_tab'                       => array(
465
+						'title'    => esc_html__('Registrations Overview', 'event_espresso'),
466
+						'filename' => 'registrations_overview',
467
+					),
468
+					'registrations_overview_table_column_headings_help_tab' => array(
469
+						'title'    => esc_html__('Registrations Table Column Headings', 'event_espresso'),
470
+						'filename' => 'registrations_overview_table_column_headings',
471
+					),
472
+					'registrations_overview_filters_help_tab'               => array(
473
+						'title'    => esc_html__('Registration Filters', 'event_espresso'),
474
+						'filename' => 'registrations_overview_filters',
475
+					),
476
+					'registrations_overview_views_help_tab'                 => array(
477
+						'title'    => esc_html__('Registration Views', 'event_espresso'),
478
+						'filename' => 'registrations_overview_views',
479
+					),
480
+					'registrations_regoverview_other_help_tab'              => array(
481
+						'title'    => esc_html__('Registrations Other', 'event_espresso'),
482
+						'filename' => 'registrations_overview_other',
483
+					),
484
+				),
485
+				'help_tour'     => array('Registration_Overview_Help_Tour'),
486
+				'qtips'         => array('Registration_List_Table_Tips'),
487
+				'list_table'    => 'EE_Registrations_List_Table',
488
+				'require_nonce' => false,
489
+			),
490
+			'view_registration' => array(
491
+				'nav'           => array(
492
+					'label'      => esc_html__('REG Details', 'event_espresso'),
493
+					'order'      => 15,
494
+					'url'        => isset($this->_req_data['_REG_ID'])
495
+						? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
496
+						: $this->_admin_base_url,
497
+					'persistent' => false,
498
+				),
499
+				'help_tabs'     => array(
500
+					'registrations_details_help_tab'                    => array(
501
+						'title'    => esc_html__('Registration Details', 'event_espresso'),
502
+						'filename' => 'registrations_details',
503
+					),
504
+					'registrations_details_table_help_tab'              => array(
505
+						'title'    => esc_html__('Registration Details Table', 'event_espresso'),
506
+						'filename' => 'registrations_details_table',
507
+					),
508
+					'registrations_details_form_answers_help_tab'       => array(
509
+						'title'    => esc_html__('Registration Form Answers', 'event_espresso'),
510
+						'filename' => 'registrations_details_form_answers',
511
+					),
512
+					'registrations_details_registrant_details_help_tab' => array(
513
+						'title'    => esc_html__('Contact Details', 'event_espresso'),
514
+						'filename' => 'registrations_details_registrant_details',
515
+					),
516
+				),
517
+				'help_tour'     => array('Registration_Details_Help_Tour'),
518
+				'metaboxes'     => array_merge(
519
+					$this->_default_espresso_metaboxes,
520
+					array('_registration_details_metaboxes')
521
+				),
522
+				'require_nonce' => false,
523
+			),
524
+			'new_registration'  => array(
525
+				'nav'           => array(
526
+					'label'      => esc_html__('Add New Registration', 'event_espresso'),
527
+					'url'        => '#',
528
+					'order'      => 15,
529
+					'persistent' => false,
530
+				),
531
+				'metaboxes'     => $this->_default_espresso_metaboxes,
532
+				'labels'        => array(
533
+					'publishbox' => esc_html__('Save Registration', 'event_espresso'),
534
+				),
535
+				'require_nonce' => false,
536
+			),
537
+			'add_new_attendee'  => array(
538
+				'nav'           => array(
539
+					'label'      => esc_html__('Add Contact', 'event_espresso'),
540
+					'order'      => 15,
541
+					'persistent' => false,
542
+				),
543
+				'metaboxes'     => array_merge(
544
+					$this->_default_espresso_metaboxes,
545
+					array('_publish_post_box', 'attendee_editor_metaboxes')
546
+				),
547
+				'require_nonce' => false,
548
+			),
549
+			'edit_attendee'     => array(
550
+				'nav'           => array(
551
+					'label'      => esc_html__('Edit Contact', 'event_espresso'),
552
+					'order'      => 15,
553
+					'persistent' => false,
554
+					'url'        => isset($this->_req_data['ATT_ID'])
555
+						? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
556
+						: $this->_admin_base_url,
557
+				),
558
+				'metaboxes'     => array('attendee_editor_metaboxes'),
559
+				'require_nonce' => false,
560
+			),
561
+			'contact_list'      => array(
562
+				'nav'           => array(
563
+					'label' => esc_html__('Contact List', 'event_espresso'),
564
+					'order' => 20,
565
+				),
566
+				'list_table'    => 'EE_Attendee_Contact_List_Table',
567
+				'help_tabs'     => array(
568
+					'registrations_contact_list_help_tab'                       => array(
569
+						'title'    => esc_html__('Registrations Contact List', 'event_espresso'),
570
+						'filename' => 'registrations_contact_list',
571
+					),
572
+					'registrations_contact-list_table_column_headings_help_tab' => array(
573
+						'title'    => esc_html__('Contact List Table Column Headings', 'event_espresso'),
574
+						'filename' => 'registrations_contact_list_table_column_headings',
575
+					),
576
+					'registrations_contact_list_views_help_tab'                 => array(
577
+						'title'    => esc_html__('Contact List Views', 'event_espresso'),
578
+						'filename' => 'registrations_contact_list_views',
579
+					),
580
+					'registrations_contact_list_other_help_tab'                 => array(
581
+						'title'    => esc_html__('Contact List Other', 'event_espresso'),
582
+						'filename' => 'registrations_contact_list_other',
583
+					),
584
+				),
585
+				'help_tour'     => array('Contact_List_Help_Tour'),
586
+				'metaboxes'     => array(),
587
+				'require_nonce' => false,
588
+			),
589
+			// override default cpt routes
590
+			'create_new'        => '',
591
+			'edit'              => '',
592
+		);
593
+	}
594
+
595
+
596
+	/**
597
+	 * The below methods aren't used by this class currently
598
+	 */
599
+	protected function _add_screen_options()
600
+	{
601
+	}
602
+
603
+
604
+	protected function _add_feature_pointers()
605
+	{
606
+	}
607
+
608
+
609
+	public function admin_init()
610
+	{
611
+		EE_Registry::$i18n_js_strings['update_att_qstns'] = esc_html__(
612
+			'click "Update Registration Questions" to save your changes',
613
+			'event_espresso'
614
+		);
615
+	}
616
+
617
+
618
+	public function admin_notices()
619
+	{
620
+	}
621
+
622
+
623
+	public function admin_footer_scripts()
624
+	{
625
+	}
626
+
627
+
628
+	/**
629
+	 *        get list of registration statuses
630
+	 *
631
+	 * @access private
632
+	 * @return void
633
+	 * @throws EE_Error
634
+	 */
635
+	private function _get_registration_status_array()
636
+	{
637
+		self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
638
+	}
639
+
640
+
641
+	protected function _add_screen_options_default()
642
+	{
643
+		$this->_per_page_screen_option();
644
+	}
645
+
646
+
647
+	protected function _add_screen_options_contact_list()
648
+	{
649
+		$page_title = $this->_admin_page_title;
650
+		$this->_admin_page_title = esc_html__("Contacts", 'event_espresso');
651
+		$this->_per_page_screen_option();
652
+		$this->_admin_page_title = $page_title;
653
+	}
654
+
655
+
656
+	public function load_scripts_styles()
657
+	{
658
+		// style
659
+		wp_register_style(
660
+			'espresso_reg',
661
+			REG_ASSETS_URL . 'espresso_registrations_admin.css',
662
+			array('ee-admin-css'),
663
+			EVENT_ESPRESSO_VERSION
664
+		);
665
+		wp_enqueue_style('espresso_reg');
666
+		// script
667
+		wp_register_script(
668
+			'espresso_reg',
669
+			REG_ASSETS_URL . 'espresso_registrations_admin.js',
670
+			array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
671
+			EVENT_ESPRESSO_VERSION,
672
+			true
673
+		);
674
+		wp_enqueue_script('espresso_reg');
675
+	}
676
+
677
+
678
+	public function load_scripts_styles_edit_attendee()
679
+	{
680
+		// stuff to only show up on our attendee edit details page.
681
+		$attendee_details_translations = array(
682
+			'att_publish_text' => sprintf(
683
+				esc_html__('Created on: <b>%1$s</b>', 'event_espresso'),
684
+				$this->_cpt_model_obj->get_datetime('ATT_created')
685
+			),
686
+		);
687
+		wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
688
+		wp_enqueue_script('jquery-validate');
689
+	}
690
+
691
+
692
+	public function load_scripts_styles_view_registration()
693
+	{
694
+		// styles
695
+		wp_enqueue_style('espresso-ui-theme');
696
+		// scripts
697
+		$this->_get_reg_custom_questions_form($this->_registration->ID());
698
+		$this->_reg_custom_questions_form->wp_enqueue_scripts(true);
699
+	}
700
+
701
+
702
+	public function load_scripts_styles_contact_list()
703
+	{
704
+		wp_dequeue_style('espresso_reg');
705
+		wp_register_style(
706
+			'espresso_att',
707
+			REG_ASSETS_URL . 'espresso_attendees_admin.css',
708
+			array('ee-admin-css'),
709
+			EVENT_ESPRESSO_VERSION
710
+		);
711
+		wp_enqueue_style('espresso_att');
712
+	}
713
+
714
+
715
+	public function load_scripts_styles_new_registration()
716
+	{
717
+		wp_register_script(
718
+			'ee-spco-for-admin',
719
+			REG_ASSETS_URL . 'spco_for_admin.js',
720
+			array('underscore', 'jquery'),
721
+			EVENT_ESPRESSO_VERSION,
722
+			true
723
+		);
724
+		wp_enqueue_script('ee-spco-for-admin');
725
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
726
+		EE_Form_Section_Proper::wp_enqueue_scripts();
727
+		EED_Ticket_Selector::load_tckt_slctr_assets();
728
+		EE_Datepicker_Input::enqueue_styles_and_scripts();
729
+	}
730
+
731
+
732
+	public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
733
+	{
734
+		add_filter('FHEE_load_EE_messages', '__return_true');
735
+	}
736
+
737
+
738
+	public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
739
+	{
740
+		add_filter('FHEE_load_EE_messages', '__return_true');
741
+	}
742
+
743
+
744
+	protected function _set_list_table_views_default()
745
+	{
746
+		// for notification related bulk actions we need to make sure only active messengers have an option.
747
+		EED_Messages::set_autoloaders();
748
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
749
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
750
+		$active_mts = $message_resource_manager->list_of_active_message_types();
751
+		// key= bulk_action_slug, value= message type.
752
+		$match_array = array(
753
+			'approve_registrations'    => 'registration',
754
+			'decline_registrations'    => 'declined_registration',
755
+			'pending_registrations'    => 'pending_approval',
756
+			'no_approve_registrations' => 'not_approved_registration',
757
+			'cancel_registrations'     => 'cancelled_registration',
758
+		);
759
+		$can_send = EE_Registry::instance()->CAP->current_user_can(
760
+			'ee_send_message',
761
+			'batch_send_messages'
762
+		);
763
+		/** setup reg status bulk actions **/
764
+		$def_reg_status_actions['approve_registrations'] = esc_html__('Approve Registrations', 'event_espresso');
765
+		if ($can_send && in_array($match_array['approve_registrations'], $active_mts, true)) {
766
+			$def_reg_status_actions['approve_and_notify_registrations'] = esc_html__(
767
+				'Approve and Notify Registrations',
768
+				'event_espresso'
769
+			);
770
+		}
771
+		$def_reg_status_actions['decline_registrations'] = esc_html__('Decline Registrations', 'event_espresso');
772
+		if ($can_send && in_array($match_array['decline_registrations'], $active_mts, true)) {
773
+			$def_reg_status_actions['decline_and_notify_registrations'] = esc_html__(
774
+				'Decline and Notify Registrations',
775
+				'event_espresso'
776
+			);
777
+		}
778
+		$def_reg_status_actions['pending_registrations'] = esc_html__(
779
+			'Set Registrations to Pending Payment',
780
+			'event_espresso'
781
+		);
782
+		if ($can_send && in_array($match_array['pending_registrations'], $active_mts, true)) {
783
+			$def_reg_status_actions['pending_and_notify_registrations'] = esc_html__(
784
+				'Set Registrations to Pending Payment and Notify',
785
+				'event_espresso'
786
+			);
787
+		}
788
+		$def_reg_status_actions['no_approve_registrations'] = esc_html__(
789
+			'Set Registrations to Not Approved',
790
+			'event_espresso'
791
+		);
792
+		if ($can_send && in_array($match_array['no_approve_registrations'], $active_mts, true)) {
793
+			$def_reg_status_actions['no_approve_and_notify_registrations'] = esc_html__(
794
+				'Set Registrations to Not Approved and Notify',
795
+				'event_espresso'
796
+			);
797
+		}
798
+		$def_reg_status_actions['cancel_registrations'] = esc_html__('Cancel Registrations', 'event_espresso');
799
+		if ($can_send && in_array($match_array['cancel_registrations'], $active_mts, true)) {
800
+			$def_reg_status_actions['cancel_and_notify_registrations'] = esc_html__(
801
+				'Cancel Registrations and Notify',
802
+				'event_espresso'
803
+			);
804
+		}
805
+		$def_reg_status_actions = apply_filters(
806
+			'FHEE__Registrations_Admin_Page___set_list_table_views_default__def_reg_status_actions_array',
807
+			$def_reg_status_actions,
808
+			$active_mts,
809
+			$can_send
810
+		);
811
+
812
+		$this->_views = array(
813
+			'all'   => array(
814
+				'slug'        => 'all',
815
+				'label'       => esc_html__('View All Registrations', 'event_espresso'),
816
+				'count'       => 0,
817
+				'bulk_action' => array_merge(
818
+					$def_reg_status_actions,
819
+					array(
820
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
821
+					)
822
+				),
823
+			),
824
+			'month' => array(
825
+				'slug'        => 'month',
826
+				'label'       => esc_html__('This Month', 'event_espresso'),
827
+				'count'       => 0,
828
+				'bulk_action' => array_merge(
829
+					$def_reg_status_actions,
830
+					array(
831
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
832
+					)
833
+				),
834
+			),
835
+			'today' => array(
836
+				'slug'        => 'today',
837
+				'label'       => sprintf(
838
+					esc_html__('Today - %s', 'event_espresso'),
839
+					date('M d, Y', current_time('timestamp'))
840
+				),
841
+				'count'       => 0,
842
+				'bulk_action' => array_merge(
843
+					$def_reg_status_actions,
844
+					array(
845
+						'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
846
+					)
847
+				),
848
+			),
849
+		);
850
+		if (EE_Registry::instance()->CAP->current_user_can(
851
+			'ee_delete_registrations',
852
+			'espresso_registrations_delete_registration'
853
+		)) {
854
+			$this->_views['incomplete'] = array(
855
+				'slug'        => 'incomplete',
856
+				'label'       => esc_html__('Incomplete', 'event_espresso'),
857
+				'count'       => 0,
858
+				'bulk_action' => array(
859
+					'trash_registrations' => esc_html__('Trash Registrations', 'event_espresso'),
860
+				),
861
+			);
862
+			$this->_views['trash'] = array(
863
+				'slug'        => 'trash',
864
+				'label'       => esc_html__('Trash', 'event_espresso'),
865
+				'count'       => 0,
866
+				'bulk_action' => array(
867
+					'restore_registrations' => esc_html__('Restore Registrations', 'event_espresso'),
868
+					'delete_registrations'  => esc_html__('Delete Registrations Permanently', 'event_espresso'),
869
+				),
870
+			);
871
+		}
872
+	}
873
+
874
+
875
+	protected function _set_list_table_views_contact_list()
876
+	{
877
+		$this->_views = array(
878
+			'in_use' => array(
879
+				'slug'        => 'in_use',
880
+				'label'       => esc_html__('In Use', 'event_espresso'),
881
+				'count'       => 0,
882
+				'bulk_action' => array(
883
+					'trash_attendees' => esc_html__('Move to Trash', 'event_espresso'),
884
+				),
885
+			),
886
+		);
887
+		if (EE_Registry::instance()->CAP->current_user_can(
888
+			'ee_delete_contacts',
889
+			'espresso_registrations_trash_attendees'
890
+		)
891
+		) {
892
+			$this->_views['trash'] = array(
893
+				'slug'        => 'trash',
894
+				'label'       => esc_html__('Trash', 'event_espresso'),
895
+				'count'       => 0,
896
+				'bulk_action' => array(
897
+					'restore_attendees' => esc_html__('Restore from Trash', 'event_espresso'),
898
+				),
899
+			);
900
+		}
901
+	}
902
+
903
+
904
+	protected function _registration_legend_items()
905
+	{
906
+		$fc_items = array(
907
+			'star-icon'        => array(
908
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
909
+				'desc'  => esc_html__('This is the Primary Registrant', 'event_espresso'),
910
+			),
911
+			'view_details'     => array(
912
+				'class' => 'dashicons dashicons-clipboard',
913
+				'desc'  => esc_html__('View Registration Details', 'event_espresso'),
914
+			),
915
+			'edit_attendee'    => array(
916
+				'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
917
+				'desc'  => esc_html__('Edit Contact Details', 'event_espresso'),
918
+			),
919
+			'view_transaction' => array(
920
+				'class' => 'dashicons dashicons-cart',
921
+				'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
922
+			),
923
+			'view_invoice'     => array(
924
+				'class' => 'dashicons dashicons-media-spreadsheet',
925
+				'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
926
+			),
927
+		);
928
+		if (EE_Registry::instance()->CAP->current_user_can(
929
+			'ee_send_message',
930
+			'espresso_registrations_resend_registration'
931
+		)) {
932
+			$fc_items['resend_registration'] = array(
933
+				'class' => 'dashicons dashicons-email-alt',
934
+				'desc'  => esc_html__('Resend Registration Details', 'event_espresso'),
935
+			);
936
+		} else {
937
+			$fc_items['blank'] = array('class' => 'blank', 'desc' => '');
938
+		}
939
+		if (EE_Registry::instance()->CAP->current_user_can(
940
+			'ee_read_global_messages',
941
+			'view_filtered_messages'
942
+		)) {
943
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
944
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
945
+				$fc_items['view_related_messages'] = array(
946
+					'class' => $related_for_icon['css_class'],
947
+					'desc'  => $related_for_icon['label'],
948
+				);
949
+			}
950
+		}
951
+		$sc_items = array(
952
+			'approved_status'   => array(
953
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
954
+				'desc'  => EEH_Template::pretty_status(
955
+					EEM_Registration::status_id_approved,
956
+					false,
957
+					'sentence'
958
+				),
959
+			),
960
+			'pending_status'    => array(
961
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
962
+				'desc'  => EEH_Template::pretty_status(
963
+					EEM_Registration::status_id_pending_payment,
964
+					false,
965
+					'sentence'
966
+				),
967
+			),
968
+			'wait_list'         => array(
969
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
970
+				'desc'  => EEH_Template::pretty_status(
971
+					EEM_Registration::status_id_wait_list,
972
+					false,
973
+					'sentence'
974
+				),
975
+			),
976
+			'incomplete_status' => array(
977
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
978
+				'desc'  => EEH_Template::pretty_status(
979
+					EEM_Registration::status_id_incomplete,
980
+					false,
981
+					'sentence'
982
+				),
983
+			),
984
+			'not_approved'      => array(
985
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
986
+				'desc'  => EEH_Template::pretty_status(
987
+					EEM_Registration::status_id_not_approved,
988
+					false,
989
+					'sentence'
990
+				),
991
+			),
992
+			'declined_status'   => array(
993
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
994
+				'desc'  => EEH_Template::pretty_status(
995
+					EEM_Registration::status_id_declined,
996
+					false,
997
+					'sentence'
998
+				),
999
+			),
1000
+			'cancelled_status'  => array(
1001
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1002
+				'desc'  => EEH_Template::pretty_status(
1003
+					EEM_Registration::status_id_cancelled,
1004
+					false,
1005
+					'sentence'
1006
+				),
1007
+			),
1008
+		);
1009
+		return array_merge($fc_items, $sc_items);
1010
+	}
1011
+
1012
+
1013
+
1014
+	/***************************************        REGISTRATION OVERVIEW        **************************************/
1015
+	/**
1016
+	 * @throws \EE_Error
1017
+	 */
1018
+	protected function _registrations_overview_list_table()
1019
+	{
1020
+		$this->_template_args['admin_page_header'] = '';
1021
+		$EVT_ID = ! empty($this->_req_data['event_id'])
1022
+			? absint($this->_req_data['event_id'])
1023
+			: 0;
1024
+		$ATT_ID = ! empty($this->_req_data['ATT_ID'])
1025
+			? absint($this->_req_data['ATT_ID'])
1026
+			: 0;
1027
+		if ($ATT_ID) {
1028
+			$attendee = EEM_Attendee::instance()->get_one_by_ID($ATT_ID);
1029
+			if ($attendee instanceof EE_Attendee) {
1030
+				$this->_template_args['admin_page_header'] = sprintf(
1031
+					esc_html__(
1032
+						'%1$s Viewing registrations for %2$s%3$s',
1033
+						'event_espresso'
1034
+					),
1035
+					'<h3 style="line-height:1.5em;">',
1036
+					'<a href="' . EE_Admin_Page::add_query_args_and_nonce(
1037
+						array(
1038
+							'action' => 'edit_attendee',
1039
+							'post'   => $ATT_ID,
1040
+						),
1041
+						REG_ADMIN_URL
1042
+					) . '">' . $attendee->full_name() . '</a>',
1043
+					'</h3>'
1044
+				);
1045
+			}
1046
+		}
1047
+		if ($EVT_ID) {
1048
+			if (EE_Registry::instance()->CAP->current_user_can(
1049
+				'ee_edit_registrations',
1050
+				'espresso_registrations_new_registration',
1051
+				$EVT_ID
1052
+			)) {
1053
+				$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1054
+					'new_registration',
1055
+					'add-registrant',
1056
+					array('event_id' => $EVT_ID),
1057
+					'add-new-h2'
1058
+				);
1059
+			}
1060
+			$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
1061
+			if ($event instanceof EE_Event) {
1062
+				$this->_template_args['admin_page_header'] = sprintf(
1063
+					esc_html__(
1064
+						'%s Viewing registrations for the event: %s%s',
1065
+						'event_espresso'
1066
+					),
1067
+					'<h3 style="line-height:1.5em;">',
1068
+					'<br /><a href="'
1069
+					. EE_Admin_Page::add_query_args_and_nonce(
1070
+						array(
1071
+							'action' => 'edit',
1072
+							'post'   => $event->ID(),
1073
+						),
1074
+						EVENTS_ADMIN_URL
1075
+					)
1076
+					. '">&nbsp;'
1077
+					. $event->get('EVT_name')
1078
+					. '&nbsp;</a>&nbsp;',
1079
+					'</h3>'
1080
+				);
1081
+			}
1082
+			$DTT_ID = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
1083
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1084
+			if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
1085
+				$this->_template_args['admin_page_header'] = substr(
1086
+					$this->_template_args['admin_page_header'],
1087
+					0,
1088
+					-5
1089
+				);
1090
+				$this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1091
+				$this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1092
+				$this->_template_args['admin_page_header'] .= $datetime->name();
1093
+				$this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1094
+				$this->_template_args['admin_page_header'] .= '</span></h3>';
1095
+			}
1096
+		}
1097
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
1098
+		$this->display_admin_list_table_page_with_no_sidebar();
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * This sets the _registration property for the registration details screen
1104
+	 *
1105
+	 * @access private
1106
+	 * @return bool
1107
+	 * @throws EE_Error
1108
+	 * @throws InvalidArgumentException
1109
+	 * @throws InvalidDataTypeException
1110
+	 * @throws InvalidInterfaceException
1111
+	 */
1112
+	private function _set_registration_object()
1113
+	{
1114
+		// get out if we've already set the object
1115
+		if ($this->_registration instanceof EE_Registration) {
1116
+			return true;
1117
+		}
1118
+		$REG = EEM_Registration::instance();
1119
+		$REG_ID = (! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1120
+		if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1121
+			return true;
1122
+		} else {
1123
+			$error_msg = sprintf(
1124
+				esc_html__(
1125
+					'An error occurred and the details for Registration ID #%s could not be retrieved.',
1126
+					'event_espresso'
1127
+				),
1128
+				$REG_ID
1129
+			);
1130
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
1131
+			$this->_registration = null;
1132
+			return false;
1133
+		}
1134
+	}
1135
+
1136
+
1137
+	/**
1138
+	 * Used to retrieve registrations for the list table.
1139
+	 *
1140
+	 * @param int  $per_page
1141
+	 * @param bool $count
1142
+	 * @param bool $this_month
1143
+	 * @param bool $today
1144
+	 * @return EE_Registration[]|int
1145
+	 * @throws EE_Error
1146
+	 * @throws InvalidArgumentException
1147
+	 * @throws InvalidDataTypeException
1148
+	 * @throws InvalidInterfaceException
1149
+	 */
1150
+	public function get_registrations(
1151
+		$per_page = 10,
1152
+		$count = false,
1153
+		$this_month = false,
1154
+		$today = false
1155
+	) {
1156
+		if ($this_month) {
1157
+			$this->_req_data['status'] = 'month';
1158
+		}
1159
+		if ($today) {
1160
+			$this->_req_data['status'] = 'today';
1161
+		}
1162
+		$query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
1163
+		/**
1164
+		 * Override the default groupby added by EEM_Base so that sorts with multiple order bys work as expected
1165
+		 *
1166
+		 * @link https://events.codebasehq.com/projects/event-espresso/tickets/10093
1167
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1168
+		 *                             or if you have the development copy of EE you can view this at the path:
1169
+		 *                             /docs/G--Model-System/model-query-params.md
1170
+		 */
1171
+		$query_params['group_by'] = '';
1172
+
1173
+		return $count
1174
+			? EEM_Registration::instance()->count($query_params)
1175
+			/** @type EE_Registration[] */
1176
+			: EEM_Registration::instance()->get_all($query_params);
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * Retrieves the query parameters to be used by the Registration model for getting registrations.
1182
+	 * Note: this listens to values on the request for some of the query parameters.
1183
+	 *
1184
+	 * @param array $request
1185
+	 * @param int   $per_page
1186
+	 * @param bool  $count
1187
+	 * @return array
1188
+	 * @throws EE_Error
1189
+	 */
1190
+	protected function _get_registration_query_parameters(
1191
+		$request = array(),
1192
+		$per_page = 10,
1193
+		$count = false
1194
+	) {
1195
+
1196
+		$query_params = array(
1197
+			0                          => $this->_get_where_conditions_for_registrations_query(
1198
+				$request
1199
+			),
1200
+			'caps'                     => EEM_Registration::caps_read_admin,
1201
+			'default_where_conditions' => 'this_model_only',
1202
+		);
1203
+		if (! $count) {
1204
+			$query_params = array_merge(
1205
+				$query_params,
1206
+				$this->_get_orderby_for_registrations_query(),
1207
+				$this->_get_limit($per_page)
1208
+			);
1209
+		}
1210
+
1211
+		return $query_params;
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * This will add ATT_ID to the provided $where array for EE model query parameters.
1217
+	 *
1218
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1219
+	 * @return array
1220
+	 */
1221
+	protected function addAttendeeIdToWhereConditions(array $request)
1222
+	{
1223
+		$where = array();
1224
+		if (! empty($request['ATT_ID'])) {
1225
+			$where['ATT_ID'] = absint($request['ATT_ID']);
1226
+		}
1227
+		return $where;
1228
+	}
1229
+
1230
+
1231
+	/**
1232
+	 * This will add EVT_ID to the provided $where array for EE model query parameters.
1233
+	 *
1234
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1235
+	 * @return array
1236
+	 */
1237
+	protected function _add_event_id_to_where_conditions(array $request)
1238
+	{
1239
+		$where = array();
1240
+		if (! empty($request['event_id'])) {
1241
+			$where['EVT_ID'] = absint($request['event_id']);
1242
+		}
1243
+		return $where;
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Adds category ID if it exists in the request to the where conditions for the registrations query.
1249
+	 *
1250
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1251
+	 * @return array
1252
+	 */
1253
+	protected function _add_category_id_to_where_conditions(array $request)
1254
+	{
1255
+		$where = array();
1256
+		if (! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
1257
+			$where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1258
+		}
1259
+		return $where;
1260
+	}
1261
+
1262
+
1263
+	/**
1264
+	 * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1265
+	 *
1266
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1267
+	 * @return array
1268
+	 */
1269
+	protected function _add_datetime_id_to_where_conditions(array $request)
1270
+	{
1271
+		$where = array();
1272
+		if (! empty($request['datetime_id'])) {
1273
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1274
+		}
1275
+		if (! empty($request['DTT_ID'])) {
1276
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1277
+		}
1278
+		return $where;
1279
+	}
1280
+
1281
+
1282
+	/**
1283
+	 * Adds the correct registration status to the where conditions for the registrations query.
1284
+	 *
1285
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1286
+	 * @return array
1287
+	 */
1288
+	protected function _add_registration_status_to_where_conditions(array $request)
1289
+	{
1290
+		$where = array();
1291
+		$view = EEH_Array::is_set($request, 'status', '');
1292
+		$registration_status = ! empty($request['_reg_status'])
1293
+			? sanitize_text_field($request['_reg_status'])
1294
+			: '';
1295
+
1296
+		/*
1297 1297
          * If filtering by registration status, then we show registrations matching that status.
1298 1298
          * If not filtering by specified status, then we show all registrations excluding incomplete registrations
1299 1299
          * UNLESS viewing trashed registrations.
1300 1300
          */
1301
-        if (! empty($registration_status)) {
1302
-            $where['STS_ID'] = $registration_status;
1303
-        } else {
1304
-            // make sure we exclude incomplete registrations, but only if not trashed.
1305
-            if ($view === 'trash') {
1306
-                $where['REG_deleted'] = true;
1307
-            } elseif ($view === 'incomplete') {
1308
-                $where['STS_ID'] = EEM_Registration::status_id_incomplete;
1309
-            } else {
1310
-                $where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1311
-            }
1312
-        }
1313
-        return $where;
1314
-    }
1315
-
1316
-
1317
-    /**
1318
-     * Adds any provided date restraints to the where conditions for the registrations query.
1319
-     *
1320
-     * @param array $request usually the same as $this->_req_data but not necessarily
1321
-     * @return array
1322
-     * @throws EE_Error
1323
-     * @throws InvalidArgumentException
1324
-     * @throws InvalidDataTypeException
1325
-     * @throws InvalidInterfaceException
1326
-     */
1327
-    protected function _add_date_to_where_conditions(array $request)
1328
-    {
1329
-        $where = array();
1330
-        $view = EEH_Array::is_set($request, 'status', '');
1331
-        $month_range = ! empty($request['month_range'])
1332
-            ? sanitize_text_field($request['month_range'])
1333
-            : '';
1334
-        $retrieve_for_today = $view === 'today';
1335
-        $retrieve_for_this_month = $view === 'month';
1336
-
1337
-        if ($retrieve_for_today) {
1338
-            $now = date('Y-m-d', current_time('timestamp'));
1339
-            $where['REG_date'] = array(
1340
-                'BETWEEN',
1341
-                array(
1342
-                    EEM_Registration::instance()->convert_datetime_for_query(
1343
-                        'REG_date',
1344
-                        $now . ' 00:00:00',
1345
-                        'Y-m-d H:i:s'
1346
-                    ),
1347
-                    EEM_Registration::instance()->convert_datetime_for_query(
1348
-                        'REG_date',
1349
-                        $now . ' 23:59:59',
1350
-                        'Y-m-d H:i:s'
1351
-                    ),
1352
-                ),
1353
-            );
1354
-        } elseif ($retrieve_for_this_month) {
1355
-            $current_year_and_month = date('Y-m', current_time('timestamp'));
1356
-            $days_this_month = date('t', current_time('timestamp'));
1357
-            $where['REG_date'] = array(
1358
-                'BETWEEN',
1359
-                array(
1360
-                    EEM_Registration::instance()->convert_datetime_for_query(
1361
-                        'REG_date',
1362
-                        $current_year_and_month . '-01 00:00:00',
1363
-                        'Y-m-d H:i:s'
1364
-                    ),
1365
-                    EEM_Registration::instance()->convert_datetime_for_query(
1366
-                        'REG_date',
1367
-                        $current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1368
-                        'Y-m-d H:i:s'
1369
-                    ),
1370
-                ),
1371
-            );
1372
-        } elseif ($month_range) {
1373
-            $pieces = explode(' ', $month_range, 3);
1374
-            $month_requested = ! empty($pieces[0])
1375
-                ? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1376
-                : '';
1377
-            $year_requested = ! empty($pieces[1])
1378
-                ? $pieces[1]
1379
-                : '';
1380
-            // if there is not a month or year then we can't go further
1381
-            if ($month_requested && $year_requested) {
1382
-                $days_in_month = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1383
-                $where['REG_date'] = array(
1384
-                    'BETWEEN',
1385
-                    array(
1386
-                        EEM_Registration::instance()->convert_datetime_for_query(
1387
-                            'REG_date',
1388
-                            $year_requested . '-' . $month_requested . '-01 00:00:00',
1389
-                            'Y-m-d H:i:s'
1390
-                        ),
1391
-                        EEM_Registration::instance()->convert_datetime_for_query(
1392
-                            'REG_date',
1393
-                            $year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1394
-                            'Y-m-d H:i:s'
1395
-                        ),
1396
-                    ),
1397
-                );
1398
-            }
1399
-        }
1400
-        return $where;
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * Adds any provided search restraints to the where conditions for the registrations query
1406
-     *
1407
-     * @param array $request usually the same as $this->_req_data but not necessarily
1408
-     * @return array
1409
-     */
1410
-    protected function _add_search_to_where_conditions(array $request)
1411
-    {
1412
-        $where = array();
1413
-        if (! empty($request['s'])) {
1414
-            $search_string = '%' . sanitize_text_field($request['s']) . '%';
1415
-            $where['OR*search_conditions'] = array(
1416
-                'Event.EVT_name'                          => array('LIKE', $search_string),
1417
-                'Event.EVT_desc'                          => array('LIKE', $search_string),
1418
-                'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1419
-                'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1420
-                'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1421
-                'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1422
-                'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1423
-                'Attendee.ATT_email'                      => array('LIKE', $search_string),
1424
-                'Attendee.ATT_address'                    => array('LIKE', $search_string),
1425
-                'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1426
-                'Attendee.ATT_city'                       => array('LIKE', $search_string),
1427
-                'REG_final_price'                         => array('LIKE', $search_string),
1428
-                'REG_code'                                => array('LIKE', $search_string),
1429
-                'REG_count'                               => array('LIKE', $search_string),
1430
-                'REG_group_size'                          => array('LIKE', $search_string),
1431
-                'Ticket.TKT_name'                         => array('LIKE', $search_string),
1432
-                'Ticket.TKT_description'                  => array('LIKE', $search_string),
1433
-                'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1434
-            );
1435
-        }
1436
-        return $where;
1437
-    }
1438
-
1439
-
1440
-    /**
1441
-     * Sets up the where conditions for the registrations query.
1442
-     *
1443
-     * @param array $request
1444
-     * @return array
1445
-     * @throws EE_Error
1446
-     */
1447
-    protected function _get_where_conditions_for_registrations_query($request)
1448
-    {
1449
-        return apply_filters(
1450
-            'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1451
-            array_merge(
1452
-                $this->addAttendeeIdToWhereConditions($request),
1453
-                $this->_add_event_id_to_where_conditions($request),
1454
-                $this->_add_category_id_to_where_conditions($request),
1455
-                $this->_add_datetime_id_to_where_conditions($request),
1456
-                $this->_add_registration_status_to_where_conditions($request),
1457
-                $this->_add_date_to_where_conditions($request),
1458
-                $this->_add_search_to_where_conditions($request)
1459
-            ),
1460
-            $request
1461
-        );
1462
-    }
1463
-
1464
-
1465
-    /**
1466
-     * Sets up the orderby for the registrations query.
1467
-     *
1468
-     * @return array
1469
-     */
1470
-    protected function _get_orderby_for_registrations_query()
1471
-    {
1472
-        $orderby_field = ! empty($this->_req_data['orderby'])
1473
-            ? sanitize_text_field($this->_req_data['orderby'])
1474
-            : '_REG_date';
1475
-        switch ($orderby_field) {
1476
-            case '_REG_ID':
1477
-                $orderby = array('REG_ID');
1478
-                break;
1479
-            case '_Reg_status':
1480
-                $orderby = array('STS_ID');
1481
-                break;
1482
-            case 'ATT_fname':
1483
-                $orderby = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1484
-                break;
1485
-            case 'ATT_lname':
1486
-                $orderby = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1487
-                break;
1488
-            case 'event_name':
1489
-                $orderby = array('Event.EVT_name');
1490
-                break;
1491
-            case 'DTT_EVT_start':
1492
-                $orderby = array('Event.Datetime.DTT_EVT_start');
1493
-                break;
1494
-            case '_REG_date':
1495
-                $orderby = array('REG_date');
1496
-                break;
1497
-            default:
1498
-                $orderby = array($orderby_field);
1499
-                break;
1500
-        }
1501
-
1502
-        // order
1503
-        $order = ! empty($this->_req_data['order'])
1504
-            ? sanitize_text_field($this->_req_data['order'])
1505
-            : 'DESC';
1506
-        $orderby = array_combine(
1507
-            $orderby,
1508
-            array_fill(0, count($orderby), $order)
1509
-        );
1510
-        // because there are many registrations with the same date, define
1511
-        // a secondary way to order them, otherwise MySQL seems to be a bit random
1512
-        if (empty($orderby['REG_ID'])) {
1513
-            $orderby['REG_ID'] = $order;
1514
-        }
1515
-
1516
-        $orderby = apply_filters(
1517
-            'FHEE__Registrations_Admin_Page___get_orderby_for_registrations_query',
1518
-            $orderby,
1519
-            $this->_req_data
1520
-        );
1521
-
1522
-        return array('order_by' => $orderby);
1523
-    }
1524
-
1525
-
1526
-    /**
1527
-     * Sets up the limit for the registrations query.
1528
-     *
1529
-     * @param $per_page
1530
-     * @return array
1531
-     */
1532
-    protected function _get_limit($per_page)
1533
-    {
1534
-        $current_page = ! empty($this->_req_data['paged'])
1535
-            ? absint($this->_req_data['paged'])
1536
-            : 1;
1537
-        $per_page = ! empty($this->_req_data['perpage'])
1538
-            ? $this->_req_data['perpage']
1539
-            : $per_page;
1540
-
1541
-        // -1 means return all results so get out if that's set.
1542
-        if ((int) $per_page === -1) {
1543
-            return array();
1544
-        }
1545
-        $per_page = absint($per_page);
1546
-        $offset = ($current_page - 1) * $per_page;
1547
-        return array('limit' => array($offset, $per_page));
1548
-    }
1549
-
1550
-
1551
-    public function get_registration_status_array()
1552
-    {
1553
-        return self::$_reg_status;
1554
-    }
1555
-
1556
-
1557
-
1558
-
1559
-    /***************************************        REGISTRATION DETAILS        ***************************************/
1560
-    /**
1561
-     *        generates HTML for the View Registration Details Admin page
1562
-     *
1563
-     * @access protected
1564
-     * @return void
1565
-     * @throws DomainException
1566
-     * @throws EE_Error
1567
-     * @throws InvalidArgumentException
1568
-     * @throws InvalidDataTypeException
1569
-     * @throws InvalidInterfaceException
1570
-     * @throws EntityNotFoundException
1571
-     */
1572
-    protected function _registration_details()
1573
-    {
1574
-        $this->_template_args = array();
1575
-        $this->_set_registration_object();
1576
-        if (is_object($this->_registration)) {
1577
-            $transaction = $this->_registration->transaction()
1578
-                ? $this->_registration->transaction()
1579
-                : EE_Transaction::new_instance();
1580
-            $this->_session = $transaction->session_data();
1581
-            $event_id = $this->_registration->event_ID();
1582
-            $this->_template_args['reg_nmbr']['value'] = $this->_registration->ID();
1583
-            $this->_template_args['reg_nmbr']['label'] = esc_html__('Registration Number', 'event_espresso');
1584
-            $this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1585
-            $this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1586
-            $this->_template_args['grand_total'] = $transaction->total();
1587
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1588
-            // link back to overview
1589
-            $this->_template_args['reg_overview_url'] = REG_ADMIN_URL;
1590
-            $this->_template_args['registration'] = $this->_registration;
1591
-            $this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1592
-                array(
1593
-                    'action'   => 'default',
1594
-                    'event_id' => $event_id,
1595
-                ),
1596
-                REG_ADMIN_URL
1597
-            );
1598
-            $this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(
1599
-                array(
1600
-                    'action' => 'default',
1601
-                    'EVT_ID' => $event_id,
1602
-                    'page'   => 'espresso_transactions',
1603
-                ),
1604
-                admin_url('admin.php')
1605
-            );
1606
-            $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
1607
-                array(
1608
-                    'page'   => 'espresso_events',
1609
-                    'action' => 'edit',
1610
-                    'post'   => $event_id,
1611
-                ),
1612
-                admin_url('admin.php')
1613
-            );
1614
-            // next and previous links
1615
-            $next_reg = $this->_registration->next(
1616
-                null,
1617
-                array(),
1618
-                'REG_ID'
1619
-            );
1620
-            $this->_template_args['next_registration'] = $next_reg
1621
-                ? $this->_next_link(
1622
-                    EE_Admin_Page::add_query_args_and_nonce(
1623
-                        array(
1624
-                            'action'  => 'view_registration',
1625
-                            '_REG_ID' => $next_reg['REG_ID'],
1626
-                        ),
1627
-                        REG_ADMIN_URL
1628
-                    ),
1629
-                    'dashicons dashicons-arrow-right ee-icon-size-22'
1630
-                )
1631
-                : '';
1632
-            $previous_reg = $this->_registration->previous(
1633
-                null,
1634
-                array(),
1635
-                'REG_ID'
1636
-            );
1637
-            $this->_template_args['previous_registration'] = $previous_reg
1638
-                ? $this->_previous_link(
1639
-                    EE_Admin_Page::add_query_args_and_nonce(
1640
-                        array(
1641
-                            'action'  => 'view_registration',
1642
-                            '_REG_ID' => $previous_reg['REG_ID'],
1643
-                        ),
1644
-                        REG_ADMIN_URL
1645
-                    ),
1646
-                    'dashicons dashicons-arrow-left ee-icon-size-22'
1647
-                )
1648
-                : '';
1649
-            // grab header
1650
-            $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1651
-            $this->_template_args['REG_ID'] = $this->_registration->ID();
1652
-            $this->_template_args['admin_page_header'] = EEH_Template::display_template(
1653
-                $template_path,
1654
-                $this->_template_args,
1655
-                true
1656
-            );
1657
-        } else {
1658
-            $this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1659
-        }
1660
-        // the details template wrapper
1661
-        $this->display_admin_page_with_sidebar();
1662
-    }
1663
-
1664
-
1665
-    protected function _registration_details_metaboxes()
1666
-    {
1667
-        do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1668
-        $this->_set_registration_object();
1669
-        $attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1670
-        add_meta_box(
1671
-            'edit-reg-status-mbox',
1672
-            esc_html__('Registration Status', 'event_espresso'),
1673
-            array($this, 'set_reg_status_buttons_metabox'),
1674
-            $this->wp_page_slug,
1675
-            'normal',
1676
-            'high'
1677
-        );
1678
-        add_meta_box(
1679
-            'edit-reg-details-mbox',
1680
-            esc_html__('Registration Details', 'event_espresso'),
1681
-            array($this, '_reg_details_meta_box'),
1682
-            $this->wp_page_slug,
1683
-            'normal',
1684
-            'high'
1685
-        );
1686
-        if ($attendee instanceof EE_Attendee
1687
-            && EE_Registry::instance()->CAP->current_user_can(
1688
-                'ee_read_registration',
1689
-                'edit-reg-questions-mbox',
1690
-                $this->_registration->ID()
1691
-            )
1692
-        ) {
1693
-            add_meta_box(
1694
-                'edit-reg-questions-mbox',
1695
-                esc_html__('Registration Form Answers', 'event_espresso'),
1696
-                array($this, '_reg_questions_meta_box'),
1697
-                $this->wp_page_slug,
1698
-                'normal',
1699
-                'high'
1700
-            );
1701
-        }
1702
-        add_meta_box(
1703
-            'edit-reg-registrant-mbox',
1704
-            esc_html__('Contact Details', 'event_espresso'),
1705
-            array($this, '_reg_registrant_side_meta_box'),
1706
-            $this->wp_page_slug,
1707
-            'side',
1708
-            'high'
1709
-        );
1710
-        if ($this->_registration->group_size() > 1) {
1711
-            add_meta_box(
1712
-                'edit-reg-attendees-mbox',
1713
-                esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1714
-                array($this, '_reg_attendees_meta_box'),
1715
-                $this->wp_page_slug,
1716
-                'normal',
1717
-                'high'
1718
-            );
1719
-        }
1720
-    }
1721
-
1722
-
1723
-    /**
1724
-     * set_reg_status_buttons_metabox
1725
-     *
1726
-     * @access protected
1727
-     * @return string
1728
-     * @throws \EE_Error
1729
-     */
1730
-    public function set_reg_status_buttons_metabox()
1731
-    {
1732
-        $this->_set_registration_object();
1733
-        $change_reg_status_form = $this->_generate_reg_status_change_form();
1734
-        echo $change_reg_status_form->form_open(
1735
-            self::add_query_args_and_nonce(
1736
-                array(
1737
-                    'action' => 'change_reg_status',
1738
-                ),
1739
-                REG_ADMIN_URL
1740
-            )
1741
-        );
1742
-        echo $change_reg_status_form->get_html();
1743
-        echo $change_reg_status_form->form_close();
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     * @return EE_Form_Section_Proper
1749
-     * @throws EE_Error
1750
-     * @throws InvalidArgumentException
1751
-     * @throws InvalidDataTypeException
1752
-     * @throws InvalidInterfaceException
1753
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1754
-     */
1755
-    protected function _generate_reg_status_change_form()
1756
-    {
1757
-        $reg_status_change_form_array = array(
1758
-            'name'            => 'reg_status_change_form',
1759
-            'html_id'         => 'reg-status-change-form',
1760
-            'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1761
-            'subsections'     => array(
1762
-                'return'             => new EE_Hidden_Input(
1763
-                    array(
1764
-                        'name'    => 'return',
1765
-                        'default' => 'view_registration',
1766
-                    )
1767
-                ),
1768
-                'REG_ID'             => new EE_Hidden_Input(
1769
-                    array(
1770
-                        'name'    => 'REG_ID',
1771
-                        'default' => $this->_registration->ID(),
1772
-                    )
1773
-                ),
1774
-                'current_status'     => new EE_Form_Section_HTML(
1775
-                    EEH_HTML::tr(
1776
-                        EEH_HTML::th(
1777
-                            EEH_HTML::label(
1778
-                                EEH_HTML::strong(
1779
-                                    esc_html__('Current Registration Status', 'event_espresso')
1780
-                                )
1781
-                            )
1782
-                        )
1783
-                        . EEH_HTML::td(
1784
-                            EEH_HTML::strong(
1785
-                                $this->_registration->pretty_status(),
1786
-                                '',
1787
-                                'status-' . $this->_registration->status_ID(),
1788
-                                'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1789
-                            )
1790
-                        )
1791
-                    )
1792
-                )
1793
-            )
1794
-        );
1795
-        if (EE_Registry::instance()->CAP->current_user_can(
1796
-            'ee_edit_registration',
1797
-            'toggle_registration_status',
1798
-            $this->_registration->ID()
1799
-        )) {
1800
-            $reg_status_change_form_array['subsections']['reg_status'] = new EE_Select_Input(
1801
-                $this->_get_reg_statuses(),
1802
-                array(
1803
-                    'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1804
-                    'default'         => $this->_registration->status_ID(),
1805
-                )
1806
-            );
1807
-            $reg_status_change_form_array['subsections']['send_notifications'] = new EE_Yes_No_Input(
1808
-                array(
1809
-                    'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1810
-                    'default'         => false,
1811
-                    'html_help_text'  => esc_html__(
1812
-                        'If set to "Yes", then the related messages will be sent to the registrant.',
1813
-                        'event_espresso'
1814
-                    )
1815
-                )
1816
-            );
1817
-            $reg_status_change_form_array['subsections']['submit'] = new EE_Submit_Input(
1818
-                array(
1819
-                    'html_class'      => 'button-primary',
1820
-                    'html_label_text' => '&nbsp;',
1821
-                    'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1822
-                )
1823
-            );
1824
-        }
1825
-        return new EE_Form_Section_Proper($reg_status_change_form_array);
1826
-    }
1827
-
1828
-
1829
-    /**
1830
-     * Returns an array of all the buttons for the various statuses and switch status actions
1831
-     *
1832
-     * @return array
1833
-     * @throws EE_Error
1834
-     * @throws InvalidArgumentException
1835
-     * @throws InvalidDataTypeException
1836
-     * @throws InvalidInterfaceException
1837
-     * @throws EntityNotFoundException
1838
-     */
1839
-    protected function _get_reg_statuses()
1840
-    {
1841
-        $reg_status_array = EEM_Registration::instance()->reg_status_array();
1842
-        unset($reg_status_array[ EEM_Registration::status_id_incomplete ]);
1843
-        // get current reg status
1844
-        $current_status = $this->_registration->status_ID();
1845
-        // is registration for free event? This will determine whether to display the pending payment option
1846
-        if ($current_status !== EEM_Registration::status_id_pending_payment
1847
-            && EEH_Money::compare_floats($this->_registration->ticket()->price(), 0.00)
1848
-        ) {
1849
-            unset($reg_status_array[ EEM_Registration::status_id_pending_payment ]);
1850
-        }
1851
-        return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1852
-    }
1853
-
1854
-
1855
-    /**
1856
-     * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1857
-     *
1858
-     * @param bool $status REG status given for changing registrations to.
1859
-     * @param bool $notify Whether to send messages notifications or not.
1860
-     * @return array (array with reg_id(s) updated and whether update was successful.
1861
-     * @throws EE_Error
1862
-     * @throws InvalidArgumentException
1863
-     * @throws InvalidDataTypeException
1864
-     * @throws InvalidInterfaceException
1865
-     * @throws ReflectionException
1866
-     * @throws RuntimeException
1867
-     * @throws EntityNotFoundException
1868
-     */
1869
-    protected function _set_registration_status_from_request($status = false, $notify = false)
1870
-    {
1871
-        if (isset($this->_req_data['reg_status_change_form'])) {
1872
-            $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1873
-                ? (array) $this->_req_data['reg_status_change_form']['REG_ID']
1874
-                : array();
1875
-        } else {
1876
-            $REG_IDs = isset($this->_req_data['_REG_ID'])
1877
-                ? (array) $this->_req_data['_REG_ID']
1878
-                : array();
1879
-        }
1880
-        // sanitize $REG_IDs
1881
-        $REG_IDs = array_map('absint', $REG_IDs);
1882
-        // and remove empty entries
1883
-        $REG_IDs = array_filter($REG_IDs);
1884
-
1885
-        $result = $this->_set_registration_status($REG_IDs, $status, $notify);
1886
-
1887
-        /**
1888
-         * Set and filter $_req_data['_REG_ID'] for any potential future messages notifications.
1889
-         * Currently this value is used downstream by the _process_resend_registration method.
1890
-         *
1891
-         * @param int|array                $registration_ids The registration ids that have had their status changed successfully.
1892
-         * @param bool                     $status           The status registrations were changed to.
1893
-         * @param bool                     $success          If the status was changed successfully for all registrations.
1894
-         * @param Registrations_Admin_Page $admin_page_object
1895
-         */
1896
-        $this->_req_data['_REG_ID'] = apply_filters(
1897
-            'FHEE__Registrations_Admin_Page___set_registration_status_from_request__REG_IDs',
1898
-            $result['REG_ID'],
1899
-            $status,
1900
-            $result['success'],
1901
-            $this
1902
-        );
1903
-
1904
-        // notify?
1905
-        if ($notify
1906
-            && $result['success']
1907
-            && ! empty($this->_req_data['_REG_ID'])
1908
-            && EE_Registry::instance()->CAP->current_user_can(
1909
-                'ee_send_message',
1910
-                'espresso_registrations_resend_registration'
1911
-            )
1912
-        ) {
1913
-            $this->_process_resend_registration();
1914
-        }
1915
-        return $result;
1916
-    }
1917
-
1918
-
1919
-    /**
1920
-     * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1921
-     * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1922
-     *
1923
-     * @param array  $REG_IDs
1924
-     * @param string $status
1925
-     * @param bool   $notify  Used to indicate whether notification was requested or not.  This determines the context
1926
-     *                        slug sent with setting the registration status.
1927
-     * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1928
-     * @throws EE_Error
1929
-     * @throws InvalidArgumentException
1930
-     * @throws InvalidDataTypeException
1931
-     * @throws InvalidInterfaceException
1932
-     * @throws ReflectionException
1933
-     * @throws RuntimeException
1934
-     * @throws EntityNotFoundException
1935
-     */
1936
-    protected function _set_registration_status($REG_IDs = array(), $status = '', $notify = false)
1937
-    {
1938
-        $success = false;
1939
-        // typecast $REG_IDs
1940
-        $REG_IDs = (array) $REG_IDs;
1941
-        if (! empty($REG_IDs)) {
1942
-            $success = true;
1943
-            // set default status if none is passed
1944
-            $status = $status ? $status : EEM_Registration::status_id_pending_payment;
1945
-            $status_context = $notify
1946
-                ? Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN_NOTIFY
1947
-                : Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN;
1948
-            // loop through REG_ID's and change status
1949
-            foreach ($REG_IDs as $REG_ID) {
1950
-                $registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1951
-                if ($registration instanceof EE_Registration) {
1952
-                    $registration->set_status(
1953
-                        $status,
1954
-                        false,
1955
-                        new Context(
1956
-                            $status_context,
1957
-                            esc_html__(
1958
-                                'Manually triggered status change on a Registration Admin Page route.',
1959
-                                'event_espresso'
1960
-                            )
1961
-                        )
1962
-                    );
1963
-                    $result = $registration->save();
1964
-                    // verifying explicit fails because update *may* just return 0 for 0 rows affected
1965
-                    $success = $result !== false ? $success : false;
1966
-                }
1967
-            }
1968
-        }
1969
-
1970
-        // return $success and processed registrations
1971
-        return array('REG_ID' => $REG_IDs, 'success' => $success);
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     * Common logic for setting up success message and redirecting to appropriate route
1977
-     *
1978
-     * @param  string $STS_ID status id for the registration changed to
1979
-     * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1980
-     * @return void
1981
-     * @throws EE_Error
1982
-     */
1983
-    protected function _reg_status_change_return($STS_ID, $notify = false)
1984
-    {
1985
-        $result = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1986
-            : array('success' => false);
1987
-        $success = isset($result['success']) && $result['success'];
1988
-        // setup success message
1989
-        if ($success) {
1990
-            if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1991
-                $msg = sprintf(
1992
-                    esc_html__('Registration status has been set to %s', 'event_espresso'),
1993
-                    EEH_Template::pretty_status($STS_ID, false, 'lower')
1994
-                );
1995
-            } else {
1996
-                $msg = sprintf(
1997
-                    esc_html__('Registrations have been set to %s.', 'event_espresso'),
1998
-                    EEH_Template::pretty_status($STS_ID, false, 'lower')
1999
-                );
2000
-            }
2001
-            EE_Error::add_success($msg);
2002
-        } else {
2003
-            EE_Error::add_error(
2004
-                esc_html__(
2005
-                    'Something went wrong, and the status was not changed',
2006
-                    'event_espresso'
2007
-                ),
2008
-                __FILE__,
2009
-                __LINE__,
2010
-                __FUNCTION__
2011
-            );
2012
-        }
2013
-        if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
2014
-            $route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
2015
-        } else {
2016
-            $route = array('action' => 'default');
2017
-        }
2018
-        $route = $this->mergeExistingRequestParamsWithRedirectArgs($route);
2019
-        $this->_redirect_after_action($success, '', '', $route, true);
2020
-    }
2021
-
2022
-
2023
-    /**
2024
-     * incoming reg status change from reg details page.
2025
-     *
2026
-     * @return void
2027
-     */
2028
-    protected function _change_reg_status()
2029
-    {
2030
-        $this->_req_data['return'] = 'view_registration';
2031
-        // set notify based on whether the send notifications toggle is set or not
2032
-        $notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
2033
-        // $notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
2034
-        $this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
2035
-            ? $this->_req_data['reg_status_change_form']['reg_status'] : '';
2036
-        switch ($this->_req_data['reg_status_change_form']['reg_status']) {
2037
-            case EEM_Registration::status_id_approved:
2038
-            case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'):
2039
-                $this->approve_registration($notify);
2040
-                break;
2041
-            case EEM_Registration::status_id_pending_payment:
2042
-            case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'):
2043
-                $this->pending_registration($notify);
2044
-                break;
2045
-            case EEM_Registration::status_id_not_approved:
2046
-            case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'):
2047
-                $this->not_approve_registration($notify);
2048
-                break;
2049
-            case EEM_Registration::status_id_declined:
2050
-            case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'):
2051
-                $this->decline_registration($notify);
2052
-                break;
2053
-            case EEM_Registration::status_id_cancelled:
2054
-            case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'):
2055
-                $this->cancel_registration($notify);
2056
-                break;
2057
-            case EEM_Registration::status_id_wait_list:
2058
-            case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'):
2059
-                $this->wait_list_registration($notify);
2060
-                break;
2061
-            case EEM_Registration::status_id_incomplete:
2062
-            default:
2063
-                $result['success'] = false;
2064
-                unset($this->_req_data['return']);
2065
-                $this->_reg_status_change_return('', false);
2066
-                break;
2067
-        }
2068
-    }
2069
-
2070
-
2071
-    /**
2072
-     * Callback for bulk action routes.
2073
-     * Note: although we could just register the singular route callbacks for each bulk action route as well, this
2074
-     * method was chosen so there is one central place all the registration status bulk actions are going through.
2075
-     * Potentially, this provides an easier place to locate logic that is specific to these bulk actions (as opposed to
2076
-     * when an action is happening on just a single registration).
2077
-     *
2078
-     * @param      $action
2079
-     * @param bool $notify
2080
-     */
2081
-    protected function bulk_action_on_registrations($action, $notify = false)
2082
-    {
2083
-        do_action(
2084
-            'AHEE__Registrations_Admin_Page__bulk_action_on_registrations__before_execution',
2085
-            $this,
2086
-            $action,
2087
-            $notify
2088
-        );
2089
-        $method = $action . '_registration';
2090
-        if (method_exists($this, $method)) {
2091
-            $this->$method($notify);
2092
-        }
2093
-    }
2094
-
2095
-
2096
-    /**
2097
-     * approve_registration
2098
-     *
2099
-     * @access protected
2100
-     * @param bool $notify whether or not to notify the registrant about their approval.
2101
-     * @return void
2102
-     */
2103
-    protected function approve_registration($notify = false)
2104
-    {
2105
-        $this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
2106
-    }
2107
-
2108
-
2109
-    /**
2110
-     *        decline_registration
2111
-     *
2112
-     * @access protected
2113
-     * @param bool $notify whether or not to notify the registrant about their status change.
2114
-     * @return void
2115
-     */
2116
-    protected function decline_registration($notify = false)
2117
-    {
2118
-        $this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
2119
-    }
2120
-
2121
-
2122
-    /**
2123
-     *        cancel_registration
2124
-     *
2125
-     * @access protected
2126
-     * @param bool $notify whether or not to notify the registrant about their status change.
2127
-     * @return void
2128
-     */
2129
-    protected function cancel_registration($notify = false)
2130
-    {
2131
-        $this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
2132
-    }
2133
-
2134
-
2135
-    /**
2136
-     *        not_approve_registration
2137
-     *
2138
-     * @access protected
2139
-     * @param bool $notify whether or not to notify the registrant about their status change.
2140
-     * @return void
2141
-     */
2142
-    protected function not_approve_registration($notify = false)
2143
-    {
2144
-        $this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
2145
-    }
2146
-
2147
-
2148
-    /**
2149
-     *        decline_registration
2150
-     *
2151
-     * @access protected
2152
-     * @param bool $notify whether or not to notify the registrant about their status change.
2153
-     * @return void
2154
-     */
2155
-    protected function pending_registration($notify = false)
2156
-    {
2157
-        $this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
2158
-    }
2159
-
2160
-
2161
-    /**
2162
-     * waitlist_registration
2163
-     *
2164
-     * @access protected
2165
-     * @param bool $notify whether or not to notify the registrant about their status change.
2166
-     * @return void
2167
-     */
2168
-    protected function wait_list_registration($notify = false)
2169
-    {
2170
-        $this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
2171
-    }
2172
-
2173
-
2174
-    /**
2175
-     *        generates HTML for the Registration main meta box
2176
-     *
2177
-     * @access public
2178
-     * @return void
2179
-     * @throws DomainException
2180
-     * @throws EE_Error
2181
-     * @throws InvalidArgumentException
2182
-     * @throws InvalidDataTypeException
2183
-     * @throws InvalidInterfaceException
2184
-     * @throws ReflectionException
2185
-     * @throws EntityNotFoundException
2186
-     */
2187
-    public function _reg_details_meta_box()
2188
-    {
2189
-        EEH_Autoloader::register_line_item_display_autoloaders();
2190
-        EEH_Autoloader::register_line_item_filter_autoloaders();
2191
-        EE_Registry::instance()->load_helper('Line_Item');
2192
-        $transaction = $this->_registration->transaction() ? $this->_registration->transaction()
2193
-            : EE_Transaction::new_instance();
2194
-        $this->_session = $transaction->session_data();
2195
-        $filters = new EE_Line_Item_Filter_Collection();
2196
-        // $filters->add( new EE_Non_Zero_Line_Item_Filter() );
2197
-        $filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
2198
-        $line_item_filter_processor = new EE_Line_Item_Filter_Processor(
2199
-            $filters,
2200
-            $transaction->total_line_item()
2201
-        );
2202
-        $filtered_line_item_tree = $line_item_filter_processor->process();
2203
-        $line_item_display = new EE_Line_Item_Display(
2204
-            'reg_admin_table',
2205
-            'EE_Admin_Table_Registration_Line_Item_Display_Strategy'
2206
-        );
2207
-        $this->_template_args['line_item_table'] = $line_item_display->display_line_item(
2208
-            $filtered_line_item_tree,
2209
-            array('EE_Registration' => $this->_registration)
2210
-        );
2211
-        $attendee = $this->_registration->attendee();
2212
-        if (EE_Registry::instance()->CAP->current_user_can(
2213
-            'ee_read_transaction',
2214
-            'espresso_transactions_view_transaction'
2215
-        )) {
2216
-            $this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
2217
-                EE_Admin_Page::add_query_args_and_nonce(
2218
-                    array(
2219
-                        'action' => 'view_transaction',
2220
-                        'TXN_ID' => $transaction->ID(),
2221
-                    ),
2222
-                    TXN_ADMIN_URL
2223
-                ),
2224
-                esc_html__(' View Transaction', 'event_espresso'),
2225
-                'button secondary-button right',
2226
-                'dashicons dashicons-cart'
2227
-            );
2228
-        } else {
2229
-            $this->_template_args['view_transaction_button'] = '';
2230
-        }
2231
-        if ($attendee instanceof EE_Attendee
2232
-            && EE_Registry::instance()->CAP->current_user_can(
2233
-                'ee_send_message',
2234
-                'espresso_registrations_resend_registration'
2235
-            )
2236
-        ) {
2237
-            $this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
2238
-                EE_Admin_Page::add_query_args_and_nonce(
2239
-                    array(
2240
-                        'action'      => 'resend_registration',
2241
-                        '_REG_ID'     => $this->_registration->ID(),
2242
-                        'redirect_to' => 'view_registration',
2243
-                    ),
2244
-                    REG_ADMIN_URL
2245
-                ),
2246
-                esc_html__(' Resend Registration', 'event_espresso'),
2247
-                'button secondary-button right',
2248
-                'dashicons dashicons-email-alt'
2249
-            );
2250
-        } else {
2251
-            $this->_template_args['resend_registration_button'] = '';
2252
-        }
2253
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2254
-        $payment = $transaction->get_first_related('Payment');
2255
-        $payment = ! $payment instanceof EE_Payment
2256
-            ? EE_Payment::new_instance()
2257
-            : $payment;
2258
-        $payment_method = $payment->get_first_related('Payment_Method');
2259
-        $payment_method = ! $payment_method instanceof EE_Payment_Method
2260
-            ? EE_Payment_Method::new_instance()
2261
-            : $payment_method;
2262
-        $reg_details = array(
2263
-            'payment_method'       => $payment_method->name(),
2264
-            'response_msg'         => $payment->gateway_response(),
2265
-            'registration_id'      => $this->_registration->get('REG_code'),
2266
-            'registration_session' => $this->_registration->session_ID(),
2267
-            'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2268
-            'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2269
-        );
2270
-        if (isset($reg_details['registration_id'])) {
2271
-            $this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2272
-            $this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2273
-                'Registration ID',
2274
-                'event_espresso'
2275
-            );
2276
-            $this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2277
-        }
2278
-        if (isset($reg_details['payment_method'])) {
2279
-            $this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2280
-            $this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2281
-                'Most Recent Payment Method',
2282
-                'event_espresso'
2283
-            );
2284
-            $this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2285
-            $this->_template_args['reg_details']['response_msg']['value'] = $reg_details['response_msg'];
2286
-            $this->_template_args['reg_details']['response_msg']['label'] = esc_html__(
2287
-                'Payment method response',
2288
-                'event_espresso'
2289
-            );
2290
-            $this->_template_args['reg_details']['response_msg']['class'] = 'regular-text';
2291
-        }
2292
-        $this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2293
-        $this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2294
-            'Registration Session',
2295
-            'event_espresso'
2296
-        );
2297
-        $this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2298
-        $this->_template_args['reg_details']['ip_address']['value'] = $reg_details['ip_address'];
2299
-        $this->_template_args['reg_details']['ip_address']['label'] = esc_html__(
2300
-            'Registration placed from IP',
2301
-            'event_espresso'
2302
-        );
2303
-        $this->_template_args['reg_details']['ip_address']['class'] = 'regular-text';
2304
-        $this->_template_args['reg_details']['user_agent']['value'] = $reg_details['user_agent'];
2305
-        $this->_template_args['reg_details']['user_agent']['label'] = esc_html__(
2306
-            'Registrant User Agent',
2307
-            'event_espresso'
2308
-        );
2309
-        $this->_template_args['reg_details']['user_agent']['class'] = 'large-text';
2310
-        $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
2311
-            array(
2312
-                'action'   => 'default',
2313
-                'event_id' => $this->_registration->event_ID(),
2314
-            ),
2315
-            REG_ADMIN_URL
2316
-        );
2317
-        $this->_template_args['REG_ID'] = $this->_registration->ID();
2318
-        $this->_template_args['event_id'] = $this->_registration->event_ID();
2319
-        $template_path =
2320
-            REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2321
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2322
-    }
2323
-
2324
-
2325
-    /**
2326
-     * generates HTML for the Registration Questions meta box.
2327
-     * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2328
-     * otherwise uses new forms system
2329
-     *
2330
-     * @access public
2331
-     * @return void
2332
-     * @throws DomainException
2333
-     * @throws EE_Error
2334
-     */
2335
-    public function _reg_questions_meta_box()
2336
-    {
2337
-        // allow someone to override this method entirely
2338
-        if (apply_filters(
2339
-            'FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default',
2340
-            true,
2341
-            $this,
2342
-            $this->_registration
2343
-        )) {
2344
-            $form = $this->_get_reg_custom_questions_form(
2345
-                $this->_registration->ID()
2346
-            );
2347
-            $this->_template_args['att_questions'] = count($form->subforms()) > 0
2348
-                ? $form->get_html_and_js()
2349
-                : '';
2350
-            $this->_template_args['reg_questions_form_action'] = 'edit_registration';
2351
-            $this->_template_args['REG_ID'] = $this->_registration->ID();
2352
-            $template_path =
2353
-                REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2354
-            echo EEH_Template::display_template($template_path, $this->_template_args, true);
2355
-        }
2356
-    }
2357
-
2358
-
2359
-    /**
2360
-     * form_before_question_group
2361
-     *
2362
-     * @deprecated    as of 4.8.32.rc.000
2363
-     * @access        public
2364
-     * @param        string $output
2365
-     * @return        string
2366
-     */
2367
-    public function form_before_question_group($output)
2368
-    {
2369
-        EE_Error::doing_it_wrong(
2370
-            __CLASS__ . '::' . __FUNCTION__,
2371
-            esc_html__(
2372
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2373
-                'event_espresso'
2374
-            ),
2375
-            '4.8.32.rc.000'
2376
-        );
2377
-        return '
1301
+		if (! empty($registration_status)) {
1302
+			$where['STS_ID'] = $registration_status;
1303
+		} else {
1304
+			// make sure we exclude incomplete registrations, but only if not trashed.
1305
+			if ($view === 'trash') {
1306
+				$where['REG_deleted'] = true;
1307
+			} elseif ($view === 'incomplete') {
1308
+				$where['STS_ID'] = EEM_Registration::status_id_incomplete;
1309
+			} else {
1310
+				$where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1311
+			}
1312
+		}
1313
+		return $where;
1314
+	}
1315
+
1316
+
1317
+	/**
1318
+	 * Adds any provided date restraints to the where conditions for the registrations query.
1319
+	 *
1320
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1321
+	 * @return array
1322
+	 * @throws EE_Error
1323
+	 * @throws InvalidArgumentException
1324
+	 * @throws InvalidDataTypeException
1325
+	 * @throws InvalidInterfaceException
1326
+	 */
1327
+	protected function _add_date_to_where_conditions(array $request)
1328
+	{
1329
+		$where = array();
1330
+		$view = EEH_Array::is_set($request, 'status', '');
1331
+		$month_range = ! empty($request['month_range'])
1332
+			? sanitize_text_field($request['month_range'])
1333
+			: '';
1334
+		$retrieve_for_today = $view === 'today';
1335
+		$retrieve_for_this_month = $view === 'month';
1336
+
1337
+		if ($retrieve_for_today) {
1338
+			$now = date('Y-m-d', current_time('timestamp'));
1339
+			$where['REG_date'] = array(
1340
+				'BETWEEN',
1341
+				array(
1342
+					EEM_Registration::instance()->convert_datetime_for_query(
1343
+						'REG_date',
1344
+						$now . ' 00:00:00',
1345
+						'Y-m-d H:i:s'
1346
+					),
1347
+					EEM_Registration::instance()->convert_datetime_for_query(
1348
+						'REG_date',
1349
+						$now . ' 23:59:59',
1350
+						'Y-m-d H:i:s'
1351
+					),
1352
+				),
1353
+			);
1354
+		} elseif ($retrieve_for_this_month) {
1355
+			$current_year_and_month = date('Y-m', current_time('timestamp'));
1356
+			$days_this_month = date('t', current_time('timestamp'));
1357
+			$where['REG_date'] = array(
1358
+				'BETWEEN',
1359
+				array(
1360
+					EEM_Registration::instance()->convert_datetime_for_query(
1361
+						'REG_date',
1362
+						$current_year_and_month . '-01 00:00:00',
1363
+						'Y-m-d H:i:s'
1364
+					),
1365
+					EEM_Registration::instance()->convert_datetime_for_query(
1366
+						'REG_date',
1367
+						$current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1368
+						'Y-m-d H:i:s'
1369
+					),
1370
+				),
1371
+			);
1372
+		} elseif ($month_range) {
1373
+			$pieces = explode(' ', $month_range, 3);
1374
+			$month_requested = ! empty($pieces[0])
1375
+				? date('m', \EEH_DTT_Helper::first_of_month_timestamp($pieces[0]))
1376
+				: '';
1377
+			$year_requested = ! empty($pieces[1])
1378
+				? $pieces[1]
1379
+				: '';
1380
+			// if there is not a month or year then we can't go further
1381
+			if ($month_requested && $year_requested) {
1382
+				$days_in_month = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1383
+				$where['REG_date'] = array(
1384
+					'BETWEEN',
1385
+					array(
1386
+						EEM_Registration::instance()->convert_datetime_for_query(
1387
+							'REG_date',
1388
+							$year_requested . '-' . $month_requested . '-01 00:00:00',
1389
+							'Y-m-d H:i:s'
1390
+						),
1391
+						EEM_Registration::instance()->convert_datetime_for_query(
1392
+							'REG_date',
1393
+							$year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1394
+							'Y-m-d H:i:s'
1395
+						),
1396
+					),
1397
+				);
1398
+			}
1399
+		}
1400
+		return $where;
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * Adds any provided search restraints to the where conditions for the registrations query
1406
+	 *
1407
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1408
+	 * @return array
1409
+	 */
1410
+	protected function _add_search_to_where_conditions(array $request)
1411
+	{
1412
+		$where = array();
1413
+		if (! empty($request['s'])) {
1414
+			$search_string = '%' . sanitize_text_field($request['s']) . '%';
1415
+			$where['OR*search_conditions'] = array(
1416
+				'Event.EVT_name'                          => array('LIKE', $search_string),
1417
+				'Event.EVT_desc'                          => array('LIKE', $search_string),
1418
+				'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1419
+				'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1420
+				'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1421
+				'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1422
+				'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1423
+				'Attendee.ATT_email'                      => array('LIKE', $search_string),
1424
+				'Attendee.ATT_address'                    => array('LIKE', $search_string),
1425
+				'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1426
+				'Attendee.ATT_city'                       => array('LIKE', $search_string),
1427
+				'REG_final_price'                         => array('LIKE', $search_string),
1428
+				'REG_code'                                => array('LIKE', $search_string),
1429
+				'REG_count'                               => array('LIKE', $search_string),
1430
+				'REG_group_size'                          => array('LIKE', $search_string),
1431
+				'Ticket.TKT_name'                         => array('LIKE', $search_string),
1432
+				'Ticket.TKT_description'                  => array('LIKE', $search_string),
1433
+				'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1434
+			);
1435
+		}
1436
+		return $where;
1437
+	}
1438
+
1439
+
1440
+	/**
1441
+	 * Sets up the where conditions for the registrations query.
1442
+	 *
1443
+	 * @param array $request
1444
+	 * @return array
1445
+	 * @throws EE_Error
1446
+	 */
1447
+	protected function _get_where_conditions_for_registrations_query($request)
1448
+	{
1449
+		return apply_filters(
1450
+			'FHEE__Registrations_Admin_Page___get_where_conditions_for_registrations_query',
1451
+			array_merge(
1452
+				$this->addAttendeeIdToWhereConditions($request),
1453
+				$this->_add_event_id_to_where_conditions($request),
1454
+				$this->_add_category_id_to_where_conditions($request),
1455
+				$this->_add_datetime_id_to_where_conditions($request),
1456
+				$this->_add_registration_status_to_where_conditions($request),
1457
+				$this->_add_date_to_where_conditions($request),
1458
+				$this->_add_search_to_where_conditions($request)
1459
+			),
1460
+			$request
1461
+		);
1462
+	}
1463
+
1464
+
1465
+	/**
1466
+	 * Sets up the orderby for the registrations query.
1467
+	 *
1468
+	 * @return array
1469
+	 */
1470
+	protected function _get_orderby_for_registrations_query()
1471
+	{
1472
+		$orderby_field = ! empty($this->_req_data['orderby'])
1473
+			? sanitize_text_field($this->_req_data['orderby'])
1474
+			: '_REG_date';
1475
+		switch ($orderby_field) {
1476
+			case '_REG_ID':
1477
+				$orderby = array('REG_ID');
1478
+				break;
1479
+			case '_Reg_status':
1480
+				$orderby = array('STS_ID');
1481
+				break;
1482
+			case 'ATT_fname':
1483
+				$orderby = array('Attendee.ATT_fname', 'Attendee.ATT_lname');
1484
+				break;
1485
+			case 'ATT_lname':
1486
+				$orderby = array('Attendee.ATT_lname', 'Attendee.ATT_fname');
1487
+				break;
1488
+			case 'event_name':
1489
+				$orderby = array('Event.EVT_name');
1490
+				break;
1491
+			case 'DTT_EVT_start':
1492
+				$orderby = array('Event.Datetime.DTT_EVT_start');
1493
+				break;
1494
+			case '_REG_date':
1495
+				$orderby = array('REG_date');
1496
+				break;
1497
+			default:
1498
+				$orderby = array($orderby_field);
1499
+				break;
1500
+		}
1501
+
1502
+		// order
1503
+		$order = ! empty($this->_req_data['order'])
1504
+			? sanitize_text_field($this->_req_data['order'])
1505
+			: 'DESC';
1506
+		$orderby = array_combine(
1507
+			$orderby,
1508
+			array_fill(0, count($orderby), $order)
1509
+		);
1510
+		// because there are many registrations with the same date, define
1511
+		// a secondary way to order them, otherwise MySQL seems to be a bit random
1512
+		if (empty($orderby['REG_ID'])) {
1513
+			$orderby['REG_ID'] = $order;
1514
+		}
1515
+
1516
+		$orderby = apply_filters(
1517
+			'FHEE__Registrations_Admin_Page___get_orderby_for_registrations_query',
1518
+			$orderby,
1519
+			$this->_req_data
1520
+		);
1521
+
1522
+		return array('order_by' => $orderby);
1523
+	}
1524
+
1525
+
1526
+	/**
1527
+	 * Sets up the limit for the registrations query.
1528
+	 *
1529
+	 * @param $per_page
1530
+	 * @return array
1531
+	 */
1532
+	protected function _get_limit($per_page)
1533
+	{
1534
+		$current_page = ! empty($this->_req_data['paged'])
1535
+			? absint($this->_req_data['paged'])
1536
+			: 1;
1537
+		$per_page = ! empty($this->_req_data['perpage'])
1538
+			? $this->_req_data['perpage']
1539
+			: $per_page;
1540
+
1541
+		// -1 means return all results so get out if that's set.
1542
+		if ((int) $per_page === -1) {
1543
+			return array();
1544
+		}
1545
+		$per_page = absint($per_page);
1546
+		$offset = ($current_page - 1) * $per_page;
1547
+		return array('limit' => array($offset, $per_page));
1548
+	}
1549
+
1550
+
1551
+	public function get_registration_status_array()
1552
+	{
1553
+		return self::$_reg_status;
1554
+	}
1555
+
1556
+
1557
+
1558
+
1559
+	/***************************************        REGISTRATION DETAILS        ***************************************/
1560
+	/**
1561
+	 *        generates HTML for the View Registration Details Admin page
1562
+	 *
1563
+	 * @access protected
1564
+	 * @return void
1565
+	 * @throws DomainException
1566
+	 * @throws EE_Error
1567
+	 * @throws InvalidArgumentException
1568
+	 * @throws InvalidDataTypeException
1569
+	 * @throws InvalidInterfaceException
1570
+	 * @throws EntityNotFoundException
1571
+	 */
1572
+	protected function _registration_details()
1573
+	{
1574
+		$this->_template_args = array();
1575
+		$this->_set_registration_object();
1576
+		if (is_object($this->_registration)) {
1577
+			$transaction = $this->_registration->transaction()
1578
+				? $this->_registration->transaction()
1579
+				: EE_Transaction::new_instance();
1580
+			$this->_session = $transaction->session_data();
1581
+			$event_id = $this->_registration->event_ID();
1582
+			$this->_template_args['reg_nmbr']['value'] = $this->_registration->ID();
1583
+			$this->_template_args['reg_nmbr']['label'] = esc_html__('Registration Number', 'event_espresso');
1584
+			$this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1585
+			$this->_template_args['reg_datetime']['label'] = esc_html__('Date', 'event_espresso');
1586
+			$this->_template_args['grand_total'] = $transaction->total();
1587
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1588
+			// link back to overview
1589
+			$this->_template_args['reg_overview_url'] = REG_ADMIN_URL;
1590
+			$this->_template_args['registration'] = $this->_registration;
1591
+			$this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(
1592
+				array(
1593
+					'action'   => 'default',
1594
+					'event_id' => $event_id,
1595
+				),
1596
+				REG_ADMIN_URL
1597
+			);
1598
+			$this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(
1599
+				array(
1600
+					'action' => 'default',
1601
+					'EVT_ID' => $event_id,
1602
+					'page'   => 'espresso_transactions',
1603
+				),
1604
+				admin_url('admin.php')
1605
+			);
1606
+			$this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
1607
+				array(
1608
+					'page'   => 'espresso_events',
1609
+					'action' => 'edit',
1610
+					'post'   => $event_id,
1611
+				),
1612
+				admin_url('admin.php')
1613
+			);
1614
+			// next and previous links
1615
+			$next_reg = $this->_registration->next(
1616
+				null,
1617
+				array(),
1618
+				'REG_ID'
1619
+			);
1620
+			$this->_template_args['next_registration'] = $next_reg
1621
+				? $this->_next_link(
1622
+					EE_Admin_Page::add_query_args_and_nonce(
1623
+						array(
1624
+							'action'  => 'view_registration',
1625
+							'_REG_ID' => $next_reg['REG_ID'],
1626
+						),
1627
+						REG_ADMIN_URL
1628
+					),
1629
+					'dashicons dashicons-arrow-right ee-icon-size-22'
1630
+				)
1631
+				: '';
1632
+			$previous_reg = $this->_registration->previous(
1633
+				null,
1634
+				array(),
1635
+				'REG_ID'
1636
+			);
1637
+			$this->_template_args['previous_registration'] = $previous_reg
1638
+				? $this->_previous_link(
1639
+					EE_Admin_Page::add_query_args_and_nonce(
1640
+						array(
1641
+							'action'  => 'view_registration',
1642
+							'_REG_ID' => $previous_reg['REG_ID'],
1643
+						),
1644
+						REG_ADMIN_URL
1645
+					),
1646
+					'dashicons dashicons-arrow-left ee-icon-size-22'
1647
+				)
1648
+				: '';
1649
+			// grab header
1650
+			$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1651
+			$this->_template_args['REG_ID'] = $this->_registration->ID();
1652
+			$this->_template_args['admin_page_header'] = EEH_Template::display_template(
1653
+				$template_path,
1654
+				$this->_template_args,
1655
+				true
1656
+			);
1657
+		} else {
1658
+			$this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1659
+		}
1660
+		// the details template wrapper
1661
+		$this->display_admin_page_with_sidebar();
1662
+	}
1663
+
1664
+
1665
+	protected function _registration_details_metaboxes()
1666
+	{
1667
+		do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1668
+		$this->_set_registration_object();
1669
+		$attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1670
+		add_meta_box(
1671
+			'edit-reg-status-mbox',
1672
+			esc_html__('Registration Status', 'event_espresso'),
1673
+			array($this, 'set_reg_status_buttons_metabox'),
1674
+			$this->wp_page_slug,
1675
+			'normal',
1676
+			'high'
1677
+		);
1678
+		add_meta_box(
1679
+			'edit-reg-details-mbox',
1680
+			esc_html__('Registration Details', 'event_espresso'),
1681
+			array($this, '_reg_details_meta_box'),
1682
+			$this->wp_page_slug,
1683
+			'normal',
1684
+			'high'
1685
+		);
1686
+		if ($attendee instanceof EE_Attendee
1687
+			&& EE_Registry::instance()->CAP->current_user_can(
1688
+				'ee_read_registration',
1689
+				'edit-reg-questions-mbox',
1690
+				$this->_registration->ID()
1691
+			)
1692
+		) {
1693
+			add_meta_box(
1694
+				'edit-reg-questions-mbox',
1695
+				esc_html__('Registration Form Answers', 'event_espresso'),
1696
+				array($this, '_reg_questions_meta_box'),
1697
+				$this->wp_page_slug,
1698
+				'normal',
1699
+				'high'
1700
+			);
1701
+		}
1702
+		add_meta_box(
1703
+			'edit-reg-registrant-mbox',
1704
+			esc_html__('Contact Details', 'event_espresso'),
1705
+			array($this, '_reg_registrant_side_meta_box'),
1706
+			$this->wp_page_slug,
1707
+			'side',
1708
+			'high'
1709
+		);
1710
+		if ($this->_registration->group_size() > 1) {
1711
+			add_meta_box(
1712
+				'edit-reg-attendees-mbox',
1713
+				esc_html__('Other Registrations in this Transaction', 'event_espresso'),
1714
+				array($this, '_reg_attendees_meta_box'),
1715
+				$this->wp_page_slug,
1716
+				'normal',
1717
+				'high'
1718
+			);
1719
+		}
1720
+	}
1721
+
1722
+
1723
+	/**
1724
+	 * set_reg_status_buttons_metabox
1725
+	 *
1726
+	 * @access protected
1727
+	 * @return string
1728
+	 * @throws \EE_Error
1729
+	 */
1730
+	public function set_reg_status_buttons_metabox()
1731
+	{
1732
+		$this->_set_registration_object();
1733
+		$change_reg_status_form = $this->_generate_reg_status_change_form();
1734
+		echo $change_reg_status_form->form_open(
1735
+			self::add_query_args_and_nonce(
1736
+				array(
1737
+					'action' => 'change_reg_status',
1738
+				),
1739
+				REG_ADMIN_URL
1740
+			)
1741
+		);
1742
+		echo $change_reg_status_form->get_html();
1743
+		echo $change_reg_status_form->form_close();
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 * @return EE_Form_Section_Proper
1749
+	 * @throws EE_Error
1750
+	 * @throws InvalidArgumentException
1751
+	 * @throws InvalidDataTypeException
1752
+	 * @throws InvalidInterfaceException
1753
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
1754
+	 */
1755
+	protected function _generate_reg_status_change_form()
1756
+	{
1757
+		$reg_status_change_form_array = array(
1758
+			'name'            => 'reg_status_change_form',
1759
+			'html_id'         => 'reg-status-change-form',
1760
+			'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1761
+			'subsections'     => array(
1762
+				'return'             => new EE_Hidden_Input(
1763
+					array(
1764
+						'name'    => 'return',
1765
+						'default' => 'view_registration',
1766
+					)
1767
+				),
1768
+				'REG_ID'             => new EE_Hidden_Input(
1769
+					array(
1770
+						'name'    => 'REG_ID',
1771
+						'default' => $this->_registration->ID(),
1772
+					)
1773
+				),
1774
+				'current_status'     => new EE_Form_Section_HTML(
1775
+					EEH_HTML::tr(
1776
+						EEH_HTML::th(
1777
+							EEH_HTML::label(
1778
+								EEH_HTML::strong(
1779
+									esc_html__('Current Registration Status', 'event_espresso')
1780
+								)
1781
+							)
1782
+						)
1783
+						. EEH_HTML::td(
1784
+							EEH_HTML::strong(
1785
+								$this->_registration->pretty_status(),
1786
+								'',
1787
+								'status-' . $this->_registration->status_ID(),
1788
+								'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1789
+							)
1790
+						)
1791
+					)
1792
+				)
1793
+			)
1794
+		);
1795
+		if (EE_Registry::instance()->CAP->current_user_can(
1796
+			'ee_edit_registration',
1797
+			'toggle_registration_status',
1798
+			$this->_registration->ID()
1799
+		)) {
1800
+			$reg_status_change_form_array['subsections']['reg_status'] = new EE_Select_Input(
1801
+				$this->_get_reg_statuses(),
1802
+				array(
1803
+					'html_label_text' => esc_html__('Change Registration Status to', 'event_espresso'),
1804
+					'default'         => $this->_registration->status_ID(),
1805
+				)
1806
+			);
1807
+			$reg_status_change_form_array['subsections']['send_notifications'] = new EE_Yes_No_Input(
1808
+				array(
1809
+					'html_label_text' => esc_html__('Send Related Messages', 'event_espresso'),
1810
+					'default'         => false,
1811
+					'html_help_text'  => esc_html__(
1812
+						'If set to "Yes", then the related messages will be sent to the registrant.',
1813
+						'event_espresso'
1814
+					)
1815
+				)
1816
+			);
1817
+			$reg_status_change_form_array['subsections']['submit'] = new EE_Submit_Input(
1818
+				array(
1819
+					'html_class'      => 'button-primary',
1820
+					'html_label_text' => '&nbsp;',
1821
+					'default'         => esc_html__('Update Registration Status', 'event_espresso'),
1822
+				)
1823
+			);
1824
+		}
1825
+		return new EE_Form_Section_Proper($reg_status_change_form_array);
1826
+	}
1827
+
1828
+
1829
+	/**
1830
+	 * Returns an array of all the buttons for the various statuses and switch status actions
1831
+	 *
1832
+	 * @return array
1833
+	 * @throws EE_Error
1834
+	 * @throws InvalidArgumentException
1835
+	 * @throws InvalidDataTypeException
1836
+	 * @throws InvalidInterfaceException
1837
+	 * @throws EntityNotFoundException
1838
+	 */
1839
+	protected function _get_reg_statuses()
1840
+	{
1841
+		$reg_status_array = EEM_Registration::instance()->reg_status_array();
1842
+		unset($reg_status_array[ EEM_Registration::status_id_incomplete ]);
1843
+		// get current reg status
1844
+		$current_status = $this->_registration->status_ID();
1845
+		// is registration for free event? This will determine whether to display the pending payment option
1846
+		if ($current_status !== EEM_Registration::status_id_pending_payment
1847
+			&& EEH_Money::compare_floats($this->_registration->ticket()->price(), 0.00)
1848
+		) {
1849
+			unset($reg_status_array[ EEM_Registration::status_id_pending_payment ]);
1850
+		}
1851
+		return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1852
+	}
1853
+
1854
+
1855
+	/**
1856
+	 * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1857
+	 *
1858
+	 * @param bool $status REG status given for changing registrations to.
1859
+	 * @param bool $notify Whether to send messages notifications or not.
1860
+	 * @return array (array with reg_id(s) updated and whether update was successful.
1861
+	 * @throws EE_Error
1862
+	 * @throws InvalidArgumentException
1863
+	 * @throws InvalidDataTypeException
1864
+	 * @throws InvalidInterfaceException
1865
+	 * @throws ReflectionException
1866
+	 * @throws RuntimeException
1867
+	 * @throws EntityNotFoundException
1868
+	 */
1869
+	protected function _set_registration_status_from_request($status = false, $notify = false)
1870
+	{
1871
+		if (isset($this->_req_data['reg_status_change_form'])) {
1872
+			$REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1873
+				? (array) $this->_req_data['reg_status_change_form']['REG_ID']
1874
+				: array();
1875
+		} else {
1876
+			$REG_IDs = isset($this->_req_data['_REG_ID'])
1877
+				? (array) $this->_req_data['_REG_ID']
1878
+				: array();
1879
+		}
1880
+		// sanitize $REG_IDs
1881
+		$REG_IDs = array_map('absint', $REG_IDs);
1882
+		// and remove empty entries
1883
+		$REG_IDs = array_filter($REG_IDs);
1884
+
1885
+		$result = $this->_set_registration_status($REG_IDs, $status, $notify);
1886
+
1887
+		/**
1888
+		 * Set and filter $_req_data['_REG_ID'] for any potential future messages notifications.
1889
+		 * Currently this value is used downstream by the _process_resend_registration method.
1890
+		 *
1891
+		 * @param int|array                $registration_ids The registration ids that have had their status changed successfully.
1892
+		 * @param bool                     $status           The status registrations were changed to.
1893
+		 * @param bool                     $success          If the status was changed successfully for all registrations.
1894
+		 * @param Registrations_Admin_Page $admin_page_object
1895
+		 */
1896
+		$this->_req_data['_REG_ID'] = apply_filters(
1897
+			'FHEE__Registrations_Admin_Page___set_registration_status_from_request__REG_IDs',
1898
+			$result['REG_ID'],
1899
+			$status,
1900
+			$result['success'],
1901
+			$this
1902
+		);
1903
+
1904
+		// notify?
1905
+		if ($notify
1906
+			&& $result['success']
1907
+			&& ! empty($this->_req_data['_REG_ID'])
1908
+			&& EE_Registry::instance()->CAP->current_user_can(
1909
+				'ee_send_message',
1910
+				'espresso_registrations_resend_registration'
1911
+			)
1912
+		) {
1913
+			$this->_process_resend_registration();
1914
+		}
1915
+		return $result;
1916
+	}
1917
+
1918
+
1919
+	/**
1920
+	 * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1921
+	 * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1922
+	 *
1923
+	 * @param array  $REG_IDs
1924
+	 * @param string $status
1925
+	 * @param bool   $notify  Used to indicate whether notification was requested or not.  This determines the context
1926
+	 *                        slug sent with setting the registration status.
1927
+	 * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1928
+	 * @throws EE_Error
1929
+	 * @throws InvalidArgumentException
1930
+	 * @throws InvalidDataTypeException
1931
+	 * @throws InvalidInterfaceException
1932
+	 * @throws ReflectionException
1933
+	 * @throws RuntimeException
1934
+	 * @throws EntityNotFoundException
1935
+	 */
1936
+	protected function _set_registration_status($REG_IDs = array(), $status = '', $notify = false)
1937
+	{
1938
+		$success = false;
1939
+		// typecast $REG_IDs
1940
+		$REG_IDs = (array) $REG_IDs;
1941
+		if (! empty($REG_IDs)) {
1942
+			$success = true;
1943
+			// set default status if none is passed
1944
+			$status = $status ? $status : EEM_Registration::status_id_pending_payment;
1945
+			$status_context = $notify
1946
+				? Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN_NOTIFY
1947
+				: Domain::CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN;
1948
+			// loop through REG_ID's and change status
1949
+			foreach ($REG_IDs as $REG_ID) {
1950
+				$registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1951
+				if ($registration instanceof EE_Registration) {
1952
+					$registration->set_status(
1953
+						$status,
1954
+						false,
1955
+						new Context(
1956
+							$status_context,
1957
+							esc_html__(
1958
+								'Manually triggered status change on a Registration Admin Page route.',
1959
+								'event_espresso'
1960
+							)
1961
+						)
1962
+					);
1963
+					$result = $registration->save();
1964
+					// verifying explicit fails because update *may* just return 0 for 0 rows affected
1965
+					$success = $result !== false ? $success : false;
1966
+				}
1967
+			}
1968
+		}
1969
+
1970
+		// return $success and processed registrations
1971
+		return array('REG_ID' => $REG_IDs, 'success' => $success);
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 * Common logic for setting up success message and redirecting to appropriate route
1977
+	 *
1978
+	 * @param  string $STS_ID status id for the registration changed to
1979
+	 * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1980
+	 * @return void
1981
+	 * @throws EE_Error
1982
+	 */
1983
+	protected function _reg_status_change_return($STS_ID, $notify = false)
1984
+	{
1985
+		$result = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1986
+			: array('success' => false);
1987
+		$success = isset($result['success']) && $result['success'];
1988
+		// setup success message
1989
+		if ($success) {
1990
+			if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1991
+				$msg = sprintf(
1992
+					esc_html__('Registration status has been set to %s', 'event_espresso'),
1993
+					EEH_Template::pretty_status($STS_ID, false, 'lower')
1994
+				);
1995
+			} else {
1996
+				$msg = sprintf(
1997
+					esc_html__('Registrations have been set to %s.', 'event_espresso'),
1998
+					EEH_Template::pretty_status($STS_ID, false, 'lower')
1999
+				);
2000
+			}
2001
+			EE_Error::add_success($msg);
2002
+		} else {
2003
+			EE_Error::add_error(
2004
+				esc_html__(
2005
+					'Something went wrong, and the status was not changed',
2006
+					'event_espresso'
2007
+				),
2008
+				__FILE__,
2009
+				__LINE__,
2010
+				__FUNCTION__
2011
+			);
2012
+		}
2013
+		if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
2014
+			$route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
2015
+		} else {
2016
+			$route = array('action' => 'default');
2017
+		}
2018
+		$route = $this->mergeExistingRequestParamsWithRedirectArgs($route);
2019
+		$this->_redirect_after_action($success, '', '', $route, true);
2020
+	}
2021
+
2022
+
2023
+	/**
2024
+	 * incoming reg status change from reg details page.
2025
+	 *
2026
+	 * @return void
2027
+	 */
2028
+	protected function _change_reg_status()
2029
+	{
2030
+		$this->_req_data['return'] = 'view_registration';
2031
+		// set notify based on whether the send notifications toggle is set or not
2032
+		$notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
2033
+		// $notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
2034
+		$this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
2035
+			? $this->_req_data['reg_status_change_form']['reg_status'] : '';
2036
+		switch ($this->_req_data['reg_status_change_form']['reg_status']) {
2037
+			case EEM_Registration::status_id_approved:
2038
+			case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'):
2039
+				$this->approve_registration($notify);
2040
+				break;
2041
+			case EEM_Registration::status_id_pending_payment:
2042
+			case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'):
2043
+				$this->pending_registration($notify);
2044
+				break;
2045
+			case EEM_Registration::status_id_not_approved:
2046
+			case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'):
2047
+				$this->not_approve_registration($notify);
2048
+				break;
2049
+			case EEM_Registration::status_id_declined:
2050
+			case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'):
2051
+				$this->decline_registration($notify);
2052
+				break;
2053
+			case EEM_Registration::status_id_cancelled:
2054
+			case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'):
2055
+				$this->cancel_registration($notify);
2056
+				break;
2057
+			case EEM_Registration::status_id_wait_list:
2058
+			case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'):
2059
+				$this->wait_list_registration($notify);
2060
+				break;
2061
+			case EEM_Registration::status_id_incomplete:
2062
+			default:
2063
+				$result['success'] = false;
2064
+				unset($this->_req_data['return']);
2065
+				$this->_reg_status_change_return('', false);
2066
+				break;
2067
+		}
2068
+	}
2069
+
2070
+
2071
+	/**
2072
+	 * Callback for bulk action routes.
2073
+	 * Note: although we could just register the singular route callbacks for each bulk action route as well, this
2074
+	 * method was chosen so there is one central place all the registration status bulk actions are going through.
2075
+	 * Potentially, this provides an easier place to locate logic that is specific to these bulk actions (as opposed to
2076
+	 * when an action is happening on just a single registration).
2077
+	 *
2078
+	 * @param      $action
2079
+	 * @param bool $notify
2080
+	 */
2081
+	protected function bulk_action_on_registrations($action, $notify = false)
2082
+	{
2083
+		do_action(
2084
+			'AHEE__Registrations_Admin_Page__bulk_action_on_registrations__before_execution',
2085
+			$this,
2086
+			$action,
2087
+			$notify
2088
+		);
2089
+		$method = $action . '_registration';
2090
+		if (method_exists($this, $method)) {
2091
+			$this->$method($notify);
2092
+		}
2093
+	}
2094
+
2095
+
2096
+	/**
2097
+	 * approve_registration
2098
+	 *
2099
+	 * @access protected
2100
+	 * @param bool $notify whether or not to notify the registrant about their approval.
2101
+	 * @return void
2102
+	 */
2103
+	protected function approve_registration($notify = false)
2104
+	{
2105
+		$this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
2106
+	}
2107
+
2108
+
2109
+	/**
2110
+	 *        decline_registration
2111
+	 *
2112
+	 * @access protected
2113
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2114
+	 * @return void
2115
+	 */
2116
+	protected function decline_registration($notify = false)
2117
+	{
2118
+		$this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
2119
+	}
2120
+
2121
+
2122
+	/**
2123
+	 *        cancel_registration
2124
+	 *
2125
+	 * @access protected
2126
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2127
+	 * @return void
2128
+	 */
2129
+	protected function cancel_registration($notify = false)
2130
+	{
2131
+		$this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
2132
+	}
2133
+
2134
+
2135
+	/**
2136
+	 *        not_approve_registration
2137
+	 *
2138
+	 * @access protected
2139
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2140
+	 * @return void
2141
+	 */
2142
+	protected function not_approve_registration($notify = false)
2143
+	{
2144
+		$this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
2145
+	}
2146
+
2147
+
2148
+	/**
2149
+	 *        decline_registration
2150
+	 *
2151
+	 * @access protected
2152
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2153
+	 * @return void
2154
+	 */
2155
+	protected function pending_registration($notify = false)
2156
+	{
2157
+		$this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
2158
+	}
2159
+
2160
+
2161
+	/**
2162
+	 * waitlist_registration
2163
+	 *
2164
+	 * @access protected
2165
+	 * @param bool $notify whether or not to notify the registrant about their status change.
2166
+	 * @return void
2167
+	 */
2168
+	protected function wait_list_registration($notify = false)
2169
+	{
2170
+		$this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
2171
+	}
2172
+
2173
+
2174
+	/**
2175
+	 *        generates HTML for the Registration main meta box
2176
+	 *
2177
+	 * @access public
2178
+	 * @return void
2179
+	 * @throws DomainException
2180
+	 * @throws EE_Error
2181
+	 * @throws InvalidArgumentException
2182
+	 * @throws InvalidDataTypeException
2183
+	 * @throws InvalidInterfaceException
2184
+	 * @throws ReflectionException
2185
+	 * @throws EntityNotFoundException
2186
+	 */
2187
+	public function _reg_details_meta_box()
2188
+	{
2189
+		EEH_Autoloader::register_line_item_display_autoloaders();
2190
+		EEH_Autoloader::register_line_item_filter_autoloaders();
2191
+		EE_Registry::instance()->load_helper('Line_Item');
2192
+		$transaction = $this->_registration->transaction() ? $this->_registration->transaction()
2193
+			: EE_Transaction::new_instance();
2194
+		$this->_session = $transaction->session_data();
2195
+		$filters = new EE_Line_Item_Filter_Collection();
2196
+		// $filters->add( new EE_Non_Zero_Line_Item_Filter() );
2197
+		$filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
2198
+		$line_item_filter_processor = new EE_Line_Item_Filter_Processor(
2199
+			$filters,
2200
+			$transaction->total_line_item()
2201
+		);
2202
+		$filtered_line_item_tree = $line_item_filter_processor->process();
2203
+		$line_item_display = new EE_Line_Item_Display(
2204
+			'reg_admin_table',
2205
+			'EE_Admin_Table_Registration_Line_Item_Display_Strategy'
2206
+		);
2207
+		$this->_template_args['line_item_table'] = $line_item_display->display_line_item(
2208
+			$filtered_line_item_tree,
2209
+			array('EE_Registration' => $this->_registration)
2210
+		);
2211
+		$attendee = $this->_registration->attendee();
2212
+		if (EE_Registry::instance()->CAP->current_user_can(
2213
+			'ee_read_transaction',
2214
+			'espresso_transactions_view_transaction'
2215
+		)) {
2216
+			$this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(
2217
+				EE_Admin_Page::add_query_args_and_nonce(
2218
+					array(
2219
+						'action' => 'view_transaction',
2220
+						'TXN_ID' => $transaction->ID(),
2221
+					),
2222
+					TXN_ADMIN_URL
2223
+				),
2224
+				esc_html__(' View Transaction', 'event_espresso'),
2225
+				'button secondary-button right',
2226
+				'dashicons dashicons-cart'
2227
+			);
2228
+		} else {
2229
+			$this->_template_args['view_transaction_button'] = '';
2230
+		}
2231
+		if ($attendee instanceof EE_Attendee
2232
+			&& EE_Registry::instance()->CAP->current_user_can(
2233
+				'ee_send_message',
2234
+				'espresso_registrations_resend_registration'
2235
+			)
2236
+		) {
2237
+			$this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(
2238
+				EE_Admin_Page::add_query_args_and_nonce(
2239
+					array(
2240
+						'action'      => 'resend_registration',
2241
+						'_REG_ID'     => $this->_registration->ID(),
2242
+						'redirect_to' => 'view_registration',
2243
+					),
2244
+					REG_ADMIN_URL
2245
+				),
2246
+				esc_html__(' Resend Registration', 'event_espresso'),
2247
+				'button secondary-button right',
2248
+				'dashicons dashicons-email-alt'
2249
+			);
2250
+		} else {
2251
+			$this->_template_args['resend_registration_button'] = '';
2252
+		}
2253
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2254
+		$payment = $transaction->get_first_related('Payment');
2255
+		$payment = ! $payment instanceof EE_Payment
2256
+			? EE_Payment::new_instance()
2257
+			: $payment;
2258
+		$payment_method = $payment->get_first_related('Payment_Method');
2259
+		$payment_method = ! $payment_method instanceof EE_Payment_Method
2260
+			? EE_Payment_Method::new_instance()
2261
+			: $payment_method;
2262
+		$reg_details = array(
2263
+			'payment_method'       => $payment_method->name(),
2264
+			'response_msg'         => $payment->gateway_response(),
2265
+			'registration_id'      => $this->_registration->get('REG_code'),
2266
+			'registration_session' => $this->_registration->session_ID(),
2267
+			'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
2268
+			'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
2269
+		);
2270
+		if (isset($reg_details['registration_id'])) {
2271
+			$this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
2272
+			$this->_template_args['reg_details']['registration_id']['label'] = esc_html__(
2273
+				'Registration ID',
2274
+				'event_espresso'
2275
+			);
2276
+			$this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
2277
+		}
2278
+		if (isset($reg_details['payment_method'])) {
2279
+			$this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
2280
+			$this->_template_args['reg_details']['payment_method']['label'] = esc_html__(
2281
+				'Most Recent Payment Method',
2282
+				'event_espresso'
2283
+			);
2284
+			$this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
2285
+			$this->_template_args['reg_details']['response_msg']['value'] = $reg_details['response_msg'];
2286
+			$this->_template_args['reg_details']['response_msg']['label'] = esc_html__(
2287
+				'Payment method response',
2288
+				'event_espresso'
2289
+			);
2290
+			$this->_template_args['reg_details']['response_msg']['class'] = 'regular-text';
2291
+		}
2292
+		$this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
2293
+		$this->_template_args['reg_details']['registration_session']['label'] = esc_html__(
2294
+			'Registration Session',
2295
+			'event_espresso'
2296
+		);
2297
+		$this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
2298
+		$this->_template_args['reg_details']['ip_address']['value'] = $reg_details['ip_address'];
2299
+		$this->_template_args['reg_details']['ip_address']['label'] = esc_html__(
2300
+			'Registration placed from IP',
2301
+			'event_espresso'
2302
+		);
2303
+		$this->_template_args['reg_details']['ip_address']['class'] = 'regular-text';
2304
+		$this->_template_args['reg_details']['user_agent']['value'] = $reg_details['user_agent'];
2305
+		$this->_template_args['reg_details']['user_agent']['label'] = esc_html__(
2306
+			'Registrant User Agent',
2307
+			'event_espresso'
2308
+		);
2309
+		$this->_template_args['reg_details']['user_agent']['class'] = 'large-text';
2310
+		$this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(
2311
+			array(
2312
+				'action'   => 'default',
2313
+				'event_id' => $this->_registration->event_ID(),
2314
+			),
2315
+			REG_ADMIN_URL
2316
+		);
2317
+		$this->_template_args['REG_ID'] = $this->_registration->ID();
2318
+		$this->_template_args['event_id'] = $this->_registration->event_ID();
2319
+		$template_path =
2320
+			REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2321
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2322
+	}
2323
+
2324
+
2325
+	/**
2326
+	 * generates HTML for the Registration Questions meta box.
2327
+	 * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
2328
+	 * otherwise uses new forms system
2329
+	 *
2330
+	 * @access public
2331
+	 * @return void
2332
+	 * @throws DomainException
2333
+	 * @throws EE_Error
2334
+	 */
2335
+	public function _reg_questions_meta_box()
2336
+	{
2337
+		// allow someone to override this method entirely
2338
+		if (apply_filters(
2339
+			'FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default',
2340
+			true,
2341
+			$this,
2342
+			$this->_registration
2343
+		)) {
2344
+			$form = $this->_get_reg_custom_questions_form(
2345
+				$this->_registration->ID()
2346
+			);
2347
+			$this->_template_args['att_questions'] = count($form->subforms()) > 0
2348
+				? $form->get_html_and_js()
2349
+				: '';
2350
+			$this->_template_args['reg_questions_form_action'] = 'edit_registration';
2351
+			$this->_template_args['REG_ID'] = $this->_registration->ID();
2352
+			$template_path =
2353
+				REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2354
+			echo EEH_Template::display_template($template_path, $this->_template_args, true);
2355
+		}
2356
+	}
2357
+
2358
+
2359
+	/**
2360
+	 * form_before_question_group
2361
+	 *
2362
+	 * @deprecated    as of 4.8.32.rc.000
2363
+	 * @access        public
2364
+	 * @param        string $output
2365
+	 * @return        string
2366
+	 */
2367
+	public function form_before_question_group($output)
2368
+	{
2369
+		EE_Error::doing_it_wrong(
2370
+			__CLASS__ . '::' . __FUNCTION__,
2371
+			esc_html__(
2372
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2373
+				'event_espresso'
2374
+			),
2375
+			'4.8.32.rc.000'
2376
+		);
2377
+		return '
2378 2378
 	<table class="form-table ee-width-100">
2379 2379
 		<tbody>
2380 2380
 			';
2381
-    }
2382
-
2383
-
2384
-    /**
2385
-     * form_after_question_group
2386
-     *
2387
-     * @deprecated    as of 4.8.32.rc.000
2388
-     * @access        public
2389
-     * @param        string $output
2390
-     * @return        string
2391
-     */
2392
-    public function form_after_question_group($output)
2393
-    {
2394
-        EE_Error::doing_it_wrong(
2395
-            __CLASS__ . '::' . __FUNCTION__,
2396
-            esc_html__(
2397
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2398
-                'event_espresso'
2399
-            ),
2400
-            '4.8.32.rc.000'
2401
-        );
2402
-        return '
2381
+	}
2382
+
2383
+
2384
+	/**
2385
+	 * form_after_question_group
2386
+	 *
2387
+	 * @deprecated    as of 4.8.32.rc.000
2388
+	 * @access        public
2389
+	 * @param        string $output
2390
+	 * @return        string
2391
+	 */
2392
+	public function form_after_question_group($output)
2393
+	{
2394
+		EE_Error::doing_it_wrong(
2395
+			__CLASS__ . '::' . __FUNCTION__,
2396
+			esc_html__(
2397
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2398
+				'event_espresso'
2399
+			),
2400
+			'4.8.32.rc.000'
2401
+		);
2402
+		return '
2403 2403
 			<tr class="hide-if-no-js">
2404 2404
 				<th> </th>
2405 2405
 				<td class="reg-admin-edit-attendee-question-td">
2406 2406
 					<a class="reg-admin-edit-attendee-question-lnk" href="#" title="'
2407
-               . esc_attr__('click to edit question', 'event_espresso')
2408
-               . '">
2407
+			   . esc_attr__('click to edit question', 'event_espresso')
2408
+			   . '">
2409 2409
 						<span class="reg-admin-edit-question-group-spn lt-grey-txt">'
2410
-               . esc_html__('edit the above question group', 'event_espresso')
2411
-               . '</span>
2410
+			   . esc_html__('edit the above question group', 'event_espresso')
2411
+			   . '</span>
2412 2412
 						<div class="dashicons dashicons-edit"></div>
2413 2413
 					</a>
2414 2414
 				</td>
@@ -2416,608 +2416,608 @@  discard block
 block discarded – undo
2416 2416
 		</tbody>
2417 2417
 	</table>
2418 2418
 ';
2419
-    }
2420
-
2421
-
2422
-    /**
2423
-     * form_form_field_label_wrap
2424
-     *
2425
-     * @deprecated    as of 4.8.32.rc.000
2426
-     * @access        public
2427
-     * @param        string $label
2428
-     * @return        string
2429
-     */
2430
-    public function form_form_field_label_wrap($label)
2431
-    {
2432
-        EE_Error::doing_it_wrong(
2433
-            __CLASS__ . '::' . __FUNCTION__,
2434
-            esc_html__(
2435
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2436
-                'event_espresso'
2437
-            ),
2438
-            '4.8.32.rc.000'
2439
-        );
2440
-        return '
2419
+	}
2420
+
2421
+
2422
+	/**
2423
+	 * form_form_field_label_wrap
2424
+	 *
2425
+	 * @deprecated    as of 4.8.32.rc.000
2426
+	 * @access        public
2427
+	 * @param        string $label
2428
+	 * @return        string
2429
+	 */
2430
+	public function form_form_field_label_wrap($label)
2431
+	{
2432
+		EE_Error::doing_it_wrong(
2433
+			__CLASS__ . '::' . __FUNCTION__,
2434
+			esc_html__(
2435
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2436
+				'event_espresso'
2437
+			),
2438
+			'4.8.32.rc.000'
2439
+		);
2440
+		return '
2441 2441
 			<tr>
2442 2442
 				<th>
2443 2443
 					' . $label . '
2444 2444
 				</th>';
2445
-    }
2446
-
2447
-
2448
-    /**
2449
-     * form_form_field_input__wrap
2450
-     *
2451
-     * @deprecated    as of 4.8.32.rc.000
2452
-     * @access        public
2453
-     * @param        string $input
2454
-     * @return        string
2455
-     */
2456
-    public function form_form_field_input__wrap($input)
2457
-    {
2458
-        EE_Error::doing_it_wrong(
2459
-            __CLASS__ . '::' . __FUNCTION__,
2460
-            esc_html__(
2461
-                'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2462
-                'event_espresso'
2463
-            ),
2464
-            '4.8.32.rc.000'
2465
-        );
2466
-        return '
2445
+	}
2446
+
2447
+
2448
+	/**
2449
+	 * form_form_field_input__wrap
2450
+	 *
2451
+	 * @deprecated    as of 4.8.32.rc.000
2452
+	 * @access        public
2453
+	 * @param        string $input
2454
+	 * @return        string
2455
+	 */
2456
+	public function form_form_field_input__wrap($input)
2457
+	{
2458
+		EE_Error::doing_it_wrong(
2459
+			__CLASS__ . '::' . __FUNCTION__,
2460
+			esc_html__(
2461
+				'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2462
+				'event_espresso'
2463
+			),
2464
+			'4.8.32.rc.000'
2465
+		);
2466
+		return '
2467 2467
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
2468 2468
 					' . $input . '
2469 2469
 				</td>
2470 2470
 			</tr>';
2471
-    }
2472
-
2473
-
2474
-    /**
2475
-     * Updates the registration's custom questions according to the form info, if the form is submitted.
2476
-     * If it's not a post, the "view_registrations" route will be called next on the SAME request
2477
-     * to display the page
2478
-     *
2479
-     * @access protected
2480
-     * @return void
2481
-     * @throws EE_Error
2482
-     */
2483
-    protected function _update_attendee_registration_form()
2484
-    {
2485
-        do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2486
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2487
-            $REG_ID = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2488
-            $success = $this->_save_reg_custom_questions_form($REG_ID);
2489
-            if ($success) {
2490
-                $what = esc_html__('Registration Form', 'event_espresso');
2491
-                $route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2492
-                    : array('action' => 'default');
2493
-                $this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2494
-            }
2495
-        }
2496
-    }
2497
-
2498
-
2499
-    /**
2500
-     * Gets the form for saving registrations custom questions (if done
2501
-     * previously retrieves the cached form object, which may have validation errors in it)
2502
-     *
2503
-     * @param int $REG_ID
2504
-     * @return EE_Registration_Custom_Questions_Form
2505
-     * @throws EE_Error
2506
-     * @throws InvalidArgumentException
2507
-     * @throws InvalidDataTypeException
2508
-     * @throws InvalidInterfaceException
2509
-     */
2510
-    protected function _get_reg_custom_questions_form($REG_ID)
2511
-    {
2512
-        if (! $this->_reg_custom_questions_form) {
2513
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2514
-            $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2515
-                EEM_Registration::instance()->get_one_by_ID($REG_ID)
2516
-            );
2517
-            $this->_reg_custom_questions_form->_construct_finalize(null, null);
2518
-        }
2519
-        return $this->_reg_custom_questions_form;
2520
-    }
2521
-
2522
-
2523
-    /**
2524
-     * Saves
2525
-     *
2526
-     * @access private
2527
-     * @param bool $REG_ID
2528
-     * @return bool
2529
-     * @throws EE_Error
2530
-     * @throws InvalidArgumentException
2531
-     * @throws InvalidDataTypeException
2532
-     * @throws InvalidInterfaceException
2533
-     */
2534
-    private function _save_reg_custom_questions_form($REG_ID = false)
2535
-    {
2536
-        if (! $REG_ID) {
2537
-            EE_Error::add_error(
2538
-                esc_html__(
2539
-                    'An error occurred. No registration ID was received.',
2540
-                    'event_espresso'
2541
-                ),
2542
-                __FILE__,
2543
-                __FUNCTION__,
2544
-                __LINE__
2545
-            );
2546
-        }
2547
-        $form = $this->_get_reg_custom_questions_form($REG_ID);
2548
-        $form->receive_form_submission($this->_req_data);
2549
-        $success = false;
2550
-        if ($form->is_valid()) {
2551
-            foreach ($form->subforms() as $question_group_id => $question_group_form) {
2552
-                foreach ($question_group_form->inputs() as $question_id => $input) {
2553
-                    $where_conditions = array(
2554
-                        'QST_ID' => $question_id,
2555
-                        'REG_ID' => $REG_ID,
2556
-                    );
2557
-                    $possibly_new_values = array(
2558
-                        'ANS_value' => $input->normalized_value(),
2559
-                    );
2560
-                    $answer = EEM_Answer::instance()->get_one(array($where_conditions));
2561
-                    if ($answer instanceof EE_Answer) {
2562
-                        $success = $answer->save($possibly_new_values);
2563
-                    } else {
2564
-                        // insert it then
2565
-                        $cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2566
-                        $answer = EE_Answer::new_instance($cols_n_vals);
2567
-                        $success = $answer->save();
2568
-                    }
2569
-                }
2570
-            }
2571
-        } else {
2572
-            EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2573
-        }
2574
-        return $success;
2575
-    }
2576
-
2577
-
2578
-    /**
2579
-     *        generates HTML for the Registration main meta box
2580
-     *
2581
-     * @access public
2582
-     * @return void
2583
-     * @throws DomainException
2584
-     * @throws EE_Error
2585
-     * @throws InvalidArgumentException
2586
-     * @throws InvalidDataTypeException
2587
-     * @throws InvalidInterfaceException
2588
-     */
2589
-    public function _reg_attendees_meta_box()
2590
-    {
2591
-        $REG = EEM_Registration::instance();
2592
-        // get all other registrations on this transaction, and cache
2593
-        // the attendees for them so we don't have to run another query using force_join
2594
-        $registrations = $REG->get_all(
2595
-            array(
2596
-                array(
2597
-                    'TXN_ID' => $this->_registration->transaction_ID(),
2598
-                    'REG_ID' => array('!=', $this->_registration->ID()),
2599
-                ),
2600
-                'force_join' => array('Attendee'),
2601
-            )
2602
-        );
2603
-        $this->_template_args['attendees'] = array();
2604
-        $this->_template_args['attendee_notice'] = '';
2605
-        if (empty($registrations)
2606
-            || (is_array($registrations)
2607
-                && ! EEH_Array::get_one_item_from_array($registrations))
2608
-        ) {
2609
-            EE_Error::add_error(
2610
-                esc_html__(
2611
-                    'There are no records attached to this registration. Something may have gone wrong with the registration',
2612
-                    'event_espresso'
2613
-                ),
2614
-                __FILE__,
2615
-                __FUNCTION__,
2616
-                __LINE__
2617
-            );
2618
-            $this->_template_args['attendee_notice'] = EE_Error::get_notices();
2619
-        } else {
2620
-            $att_nmbr = 1;
2621
-            foreach ($registrations as $registration) {
2622
-                /* @var $registration EE_Registration */
2623
-                $attendee = $registration->attendee()
2624
-                    ? $registration->attendee()
2625
-                    : EEM_Attendee::instance()
2626
-                                  ->create_default_object();
2627
-                $this->_template_args['attendees'][ $att_nmbr ]['STS_ID'] = $registration->status_ID();
2628
-                $this->_template_args['attendees'][ $att_nmbr ]['fname'] = $attendee->fname();
2629
-                $this->_template_args['attendees'][ $att_nmbr ]['lname'] = $attendee->lname();
2630
-                $this->_template_args['attendees'][ $att_nmbr ]['email'] = $attendee->email();
2631
-                $this->_template_args['attendees'][ $att_nmbr ]['final_price'] = $registration->final_price();
2632
-                $this->_template_args['attendees'][ $att_nmbr ]['address'] = implode(
2633
-                    ', ',
2634
-                    $attendee->full_address_as_array()
2635
-                );
2636
-                $this->_template_args['attendees'][ $att_nmbr ]['att_link'] = self::add_query_args_and_nonce(
2637
-                    array(
2638
-                        'action' => 'edit_attendee',
2639
-                        'post'   => $attendee->ID(),
2640
-                    ),
2641
-                    REG_ADMIN_URL
2642
-                );
2643
-                $this->_template_args['attendees'][ $att_nmbr ]['event_name'] = $registration->event_obj() instanceof EE_Event
2644
-                    ? $registration->event_obj()->name()
2645
-                    : '';
2646
-                $att_nmbr++;
2647
-            }
2648
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2649
-        }
2650
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2651
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2652
-    }
2653
-
2654
-
2655
-    /**
2656
-     *        generates HTML for the Edit Registration side meta box
2657
-     *
2658
-     * @access public
2659
-     * @return void
2660
-     * @throws DomainException
2661
-     * @throws EE_Error
2662
-     * @throws InvalidArgumentException
2663
-     * @throws InvalidDataTypeException
2664
-     * @throws InvalidInterfaceException
2665
-     */
2666
-    public function _reg_registrant_side_meta_box()
2667
-    {
2668
-        /*@var $attendee EE_Attendee */
2669
-        $att_check = $this->_registration->attendee();
2670
-        $attendee = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2671
-        // now let's determine if this is not the primary registration.  If it isn't then we set the
2672
-        // primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2673
-        // primary registration object (that way we know if we need to show create button or not)
2674
-        if (! $this->_registration->is_primary_registrant()) {
2675
-            $primary_registration = $this->_registration->get_primary_registration();
2676
-            $primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2677
-                : null;
2678
-            if (! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2679
-                // in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2680
-                // custom attendee object so let's not worry about the primary reg.
2681
-                $primary_registration = null;
2682
-            }
2683
-        } else {
2684
-            $primary_registration = null;
2685
-        }
2686
-        $this->_template_args['ATT_ID'] = $attendee->ID();
2687
-        $this->_template_args['fname'] = $attendee->fname();
2688
-        $this->_template_args['lname'] = $attendee->lname();
2689
-        $this->_template_args['email'] = $attendee->email();
2690
-        $this->_template_args['phone'] = $attendee->phone();
2691
-        $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2692
-        // edit link
2693
-        $this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(
2694
-            array(
2695
-                'action' => 'edit_attendee',
2696
-                'post'   => $attendee->ID(),
2697
-            ),
2698
-            REG_ADMIN_URL
2699
-        );
2700
-        $this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2701
-        // create link
2702
-        $this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2703
-            ? EE_Admin_Page::add_query_args_and_nonce(
2704
-                array(
2705
-                    'action'  => 'duplicate_attendee',
2706
-                    '_REG_ID' => $this->_registration->ID(),
2707
-                ),
2708
-                REG_ADMIN_URL
2709
-            ) : '';
2710
-        $this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2711
-        $this->_template_args['att_check'] = $att_check;
2712
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2713
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2714
-    }
2715
-
2716
-
2717
-    /**
2718
-     * trash or restore registrations
2719
-     *
2720
-     * @param  boolean $trash whether to archive or restore
2721
-     * @return void
2722
-     * @throws EE_Error
2723
-     * @throws InvalidArgumentException
2724
-     * @throws InvalidDataTypeException
2725
-     * @throws InvalidInterfaceException
2726
-     * @throws RuntimeException
2727
-     * @access protected
2728
-     */
2729
-    protected function _trash_or_restore_registrations($trash = true)
2730
-    {
2731
-        // if empty _REG_ID then get out because there's nothing to do
2732
-        if (empty($this->_req_data['_REG_ID'])) {
2733
-            EE_Error::add_error(
2734
-                sprintf(
2735
-                    esc_html__(
2736
-                        'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2737
-                        'event_espresso'
2738
-                    ),
2739
-                    $trash ? 'trash' : 'restore'
2740
-                ),
2741
-                __FILE__,
2742
-                __LINE__,
2743
-                __FUNCTION__
2744
-            );
2745
-            $this->_redirect_after_action(false, '', '', array(), true);
2746
-        }
2747
-        $success = 0;
2748
-        $overwrite_msgs = false;
2749
-        // Checkboxes
2750
-        if (! is_array($this->_req_data['_REG_ID'])) {
2751
-            $this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2752
-        }
2753
-        $reg_count = count($this->_req_data['_REG_ID']);
2754
-        // cycle thru checkboxes
2755
-        foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2756
-            /** @var EE_Registration $REG */
2757
-            $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2758
-            $payments = $REG->registration_payments();
2759
-            if (! empty($payments)) {
2760
-                $name = $REG->attendee() instanceof EE_Attendee
2761
-                    ? $REG->attendee()->full_name()
2762
-                    : esc_html__('Unknown Attendee', 'event_espresso');
2763
-                $overwrite_msgs = true;
2764
-                EE_Error::add_error(
2765
-                    sprintf(
2766
-                        esc_html__(
2767
-                            'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2768
-                            'event_espresso'
2769
-                        ),
2770
-                        $name
2771
-                    ),
2772
-                    __FILE__,
2773
-                    __FUNCTION__,
2774
-                    __LINE__
2775
-                );
2776
-                // can't trash this registration because it has payments.
2777
-                continue;
2778
-            }
2779
-            $updated = $trash ? $REG->delete() : $REG->restore();
2780
-            if ($updated) {
2781
-                $success++;
2782
-            }
2783
-        }
2784
-        $this->_redirect_after_action(
2785
-            $success === $reg_count, // were ALL registrations affected?
2786
-            $success > 1
2787
-                ? esc_html__('Registrations', 'event_espresso')
2788
-                : esc_html__('Registration', 'event_espresso'),
2789
-            $trash
2790
-                ? esc_html__('moved to the trash', 'event_espresso')
2791
-                : esc_html__('restored', 'event_espresso'),
2792
-            $this->mergeExistingRequestParamsWithRedirectArgs(array('action' => 'default')),
2793
-            $overwrite_msgs
2794
-        );
2795
-    }
2796
-
2797
-
2798
-    /**
2799
-     * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2800
-     * registration but also.
2801
-     * 1. Removing relations to EE_Attendee
2802
-     * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2803
-     * ALSO trashed.
2804
-     * 3. Deleting permanently any related Line items but only if the above conditions are met.
2805
-     * 4. Removing relationships between all tickets and the related registrations
2806
-     * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2807
-     * 6. Deleting permanently any related Checkins.
2808
-     *
2809
-     * @return void
2810
-     * @throws EE_Error
2811
-     * @throws InvalidArgumentException
2812
-     * @throws InvalidDataTypeException
2813
-     * @throws InvalidInterfaceException
2814
-     */
2815
-    protected function _delete_registrations()
2816
-    {
2817
-        $REG_MDL = EEM_Registration::instance();
2818
-        $success = 1;
2819
-        // Checkboxes
2820
-        if (! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2821
-            // if array has more than one element than success message should be plural
2822
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2823
-            // cycle thru checkboxes
2824
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2825
-                $REG = $REG_MDL->get_one_by_ID($REG_ID);
2826
-                if (! $REG instanceof EE_Registration) {
2827
-                    continue;
2828
-                }
2829
-                $deleted = $this->_delete_registration($REG);
2830
-                if (! $deleted) {
2831
-                    $success = 0;
2832
-                }
2833
-            }
2834
-        } else {
2835
-            // grab single id and delete
2836
-            $REG_ID = $this->_req_data['_REG_ID'];
2837
-            $REG = $REG_MDL->get_one_by_ID($REG_ID);
2838
-            $deleted = $this->_delete_registration($REG);
2839
-            if (! $deleted) {
2840
-                $success = 0;
2841
-            }
2842
-        }
2843
-        $what = $success > 1
2844
-            ? esc_html__('Registrations', 'event_espresso')
2845
-            : esc_html__('Registration', 'event_espresso');
2846
-        $action_desc = esc_html__('permanently deleted.', 'event_espresso');
2847
-        $this->_redirect_after_action(
2848
-            $success,
2849
-            $what,
2850
-            $action_desc,
2851
-            $this->mergeExistingRequestParamsWithRedirectArgs(['action' => 'default']),
2852
-            true
2853
-        );
2854
-    }
2855
-
2856
-
2857
-    /**
2858
-     * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2859
-     * models get affected.
2860
-     *
2861
-     * @param  EE_Registration $REG registration to be deleted permenantly
2862
-     * @return bool true = successful deletion, false = fail.
2863
-     * @throws EE_Error
2864
-     */
2865
-    protected function _delete_registration(EE_Registration $REG)
2866
-    {
2867
-        // first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2868
-        // registrations on the transaction that are NOT trashed.
2869
-        $TXN = $REG->get_first_related('Transaction');
2870
-        $REGS = $TXN->get_many_related('Registration');
2871
-        $all_trashed = true;
2872
-        foreach ($REGS as $registration) {
2873
-            if (! $registration->get('REG_deleted')) {
2874
-                $all_trashed = false;
2875
-            }
2876
-        }
2877
-        if (! $all_trashed) {
2878
-            EE_Error::add_error(
2879
-                esc_html__(
2880
-                    'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2881
-                    'event_espresso'
2882
-                ),
2883
-                __FILE__,
2884
-                __FUNCTION__,
2885
-                __LINE__
2886
-            );
2887
-            return false;
2888
-        }
2889
-        // k made it here so that means we can delete all the related transactions and their answers (but let's do them
2890
-        // separately from THIS one).
2891
-        foreach ($REGS as $registration) {
2892
-            // delete related answers
2893
-            $registration->delete_related_permanently('Answer');
2894
-            // remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2895
-            $attendee = $registration->get_first_related('Attendee');
2896
-            if ($attendee instanceof EE_Attendee) {
2897
-                $registration->_remove_relation_to($attendee, 'Attendee');
2898
-            }
2899
-            // now remove relationships to tickets on this registration.
2900
-            $registration->_remove_relations('Ticket');
2901
-            // now delete permanently the checkins related to this registration.
2902
-            $registration->delete_related_permanently('Checkin');
2903
-            if ($registration->ID() === $REG->ID()) {
2904
-                continue;
2905
-            } //we don't want to delete permanently the existing registration just yet.
2906
-            // remove relation to transaction for these registrations if NOT the existing registrations
2907
-            $registration->_remove_relations('Transaction');
2908
-            // delete permanently any related messages.
2909
-            $registration->delete_related_permanently('Message');
2910
-            // now delete this registration permanently
2911
-            $registration->delete_permanently();
2912
-        }
2913
-        // now all related registrations on the transaction are handled.  So let's just handle this registration itself
2914
-        // (the transaction and line items should be all that's left).
2915
-        // delete the line items related to the transaction for this registration.
2916
-        $TXN->delete_related_permanently('Line_Item');
2917
-        // we need to remove all the relationships on the transaction
2918
-        $TXN->delete_related_permanently('Payment');
2919
-        $TXN->delete_related_permanently('Extra_Meta');
2920
-        $TXN->delete_related_permanently('Message');
2921
-        // now we can delete this REG permanently (and the transaction of course)
2922
-        $REG->delete_related_permanently('Transaction');
2923
-        return $REG->delete_permanently();
2924
-    }
2925
-
2926
-
2927
-    /**
2928
-     *    generates HTML for the Register New Attendee Admin page
2929
-     *
2930
-     * @access private
2931
-     * @throws DomainException
2932
-     * @throws EE_Error
2933
-     */
2934
-    public function new_registration()
2935
-    {
2936
-        if (! $this->_set_reg_event()) {
2937
-            throw new EE_Error(
2938
-                esc_html__(
2939
-                    'Unable to continue with registering because there is no Event ID in the request',
2940
-                    'event_espresso'
2941
-                )
2942
-            );
2943
-        }
2944
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2945
-        // gotta start with a clean slate if we're not coming here via ajax
2946
-        if (! defined('DOING_AJAX')
2947
-            && (! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2948
-        ) {
2949
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2950
-        }
2951
-        $this->_template_args['event_name'] = '';
2952
-        // event name
2953
-        if ($this->_reg_event) {
2954
-            $this->_template_args['event_name'] = $this->_reg_event->name();
2955
-            $edit_event_url = self::add_query_args_and_nonce(
2956
-                array(
2957
-                    'action' => 'edit',
2958
-                    'post'   => $this->_reg_event->ID(),
2959
-                ),
2960
-                EVENTS_ADMIN_URL
2961
-            );
2962
-            $edit_event_lnk = '<a href="'
2963
-                              . $edit_event_url
2964
-                              . '" title="'
2965
-                              . esc_attr__('Edit ', 'event_espresso')
2966
-                              . $this->_reg_event->name()
2967
-                              . '">'
2968
-                              . esc_html__('Edit Event', 'event_espresso')
2969
-                              . '</a>';
2970
-            $this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2971
-                                                   . $edit_event_lnk
2972
-                                                   . '</span>';
2973
-        }
2974
-        $this->_template_args['step_content'] = $this->_get_registration_step_content();
2975
-        if (defined('DOING_AJAX')) {
2976
-            $this->_return_json();
2977
-        }
2978
-        // grab header
2979
-        $template_path =
2980
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2981
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2982
-            $template_path,
2983
-            $this->_template_args,
2984
-            true
2985
-        );
2986
-        // $this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2987
-        // the details template wrapper
2988
-        $this->display_admin_page_with_sidebar();
2989
-    }
2990
-
2991
-
2992
-    /**
2993
-     * This returns the content for a registration step
2994
-     *
2995
-     * @access protected
2996
-     * @return string html
2997
-     * @throws DomainException
2998
-     * @throws EE_Error
2999
-     * @throws InvalidArgumentException
3000
-     * @throws InvalidDataTypeException
3001
-     * @throws InvalidInterfaceException
3002
-     */
3003
-    protected function _get_registration_step_content()
3004
-    {
3005
-        if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
3006
-            $warning_msg = sprintf(
3007
-                esc_html__(
3008
-                    '%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
3009
-                    'event_espresso'
3010
-                ),
3011
-                '<br />',
3012
-                '<h3 class="important-notice">',
3013
-                '</h3>',
3014
-                '<div class="float-right">',
3015
-                '<span id="redirect_timer" class="important-notice">30</span>',
3016
-                '</div>',
3017
-                '<b>',
3018
-                '</b>'
3019
-            );
3020
-            return '
2471
+	}
2472
+
2473
+
2474
+	/**
2475
+	 * Updates the registration's custom questions according to the form info, if the form is submitted.
2476
+	 * If it's not a post, the "view_registrations" route will be called next on the SAME request
2477
+	 * to display the page
2478
+	 *
2479
+	 * @access protected
2480
+	 * @return void
2481
+	 * @throws EE_Error
2482
+	 */
2483
+	protected function _update_attendee_registration_form()
2484
+	{
2485
+		do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
2486
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
2487
+			$REG_ID = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
2488
+			$success = $this->_save_reg_custom_questions_form($REG_ID);
2489
+			if ($success) {
2490
+				$what = esc_html__('Registration Form', 'event_espresso');
2491
+				$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
2492
+					: array('action' => 'default');
2493
+				$this->_redirect_after_action($success, $what, esc_html__('updated', 'event_espresso'), $route);
2494
+			}
2495
+		}
2496
+	}
2497
+
2498
+
2499
+	/**
2500
+	 * Gets the form for saving registrations custom questions (if done
2501
+	 * previously retrieves the cached form object, which may have validation errors in it)
2502
+	 *
2503
+	 * @param int $REG_ID
2504
+	 * @return EE_Registration_Custom_Questions_Form
2505
+	 * @throws EE_Error
2506
+	 * @throws InvalidArgumentException
2507
+	 * @throws InvalidDataTypeException
2508
+	 * @throws InvalidInterfaceException
2509
+	 */
2510
+	protected function _get_reg_custom_questions_form($REG_ID)
2511
+	{
2512
+		if (! $this->_reg_custom_questions_form) {
2513
+			require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2514
+			$this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2515
+				EEM_Registration::instance()->get_one_by_ID($REG_ID)
2516
+			);
2517
+			$this->_reg_custom_questions_form->_construct_finalize(null, null);
2518
+		}
2519
+		return $this->_reg_custom_questions_form;
2520
+	}
2521
+
2522
+
2523
+	/**
2524
+	 * Saves
2525
+	 *
2526
+	 * @access private
2527
+	 * @param bool $REG_ID
2528
+	 * @return bool
2529
+	 * @throws EE_Error
2530
+	 * @throws InvalidArgumentException
2531
+	 * @throws InvalidDataTypeException
2532
+	 * @throws InvalidInterfaceException
2533
+	 */
2534
+	private function _save_reg_custom_questions_form($REG_ID = false)
2535
+	{
2536
+		if (! $REG_ID) {
2537
+			EE_Error::add_error(
2538
+				esc_html__(
2539
+					'An error occurred. No registration ID was received.',
2540
+					'event_espresso'
2541
+				),
2542
+				__FILE__,
2543
+				__FUNCTION__,
2544
+				__LINE__
2545
+			);
2546
+		}
2547
+		$form = $this->_get_reg_custom_questions_form($REG_ID);
2548
+		$form->receive_form_submission($this->_req_data);
2549
+		$success = false;
2550
+		if ($form->is_valid()) {
2551
+			foreach ($form->subforms() as $question_group_id => $question_group_form) {
2552
+				foreach ($question_group_form->inputs() as $question_id => $input) {
2553
+					$where_conditions = array(
2554
+						'QST_ID' => $question_id,
2555
+						'REG_ID' => $REG_ID,
2556
+					);
2557
+					$possibly_new_values = array(
2558
+						'ANS_value' => $input->normalized_value(),
2559
+					);
2560
+					$answer = EEM_Answer::instance()->get_one(array($where_conditions));
2561
+					if ($answer instanceof EE_Answer) {
2562
+						$success = $answer->save($possibly_new_values);
2563
+					} else {
2564
+						// insert it then
2565
+						$cols_n_vals = array_merge($where_conditions, $possibly_new_values);
2566
+						$answer = EE_Answer::new_instance($cols_n_vals);
2567
+						$success = $answer->save();
2568
+					}
2569
+				}
2570
+			}
2571
+		} else {
2572
+			EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
2573
+		}
2574
+		return $success;
2575
+	}
2576
+
2577
+
2578
+	/**
2579
+	 *        generates HTML for the Registration main meta box
2580
+	 *
2581
+	 * @access public
2582
+	 * @return void
2583
+	 * @throws DomainException
2584
+	 * @throws EE_Error
2585
+	 * @throws InvalidArgumentException
2586
+	 * @throws InvalidDataTypeException
2587
+	 * @throws InvalidInterfaceException
2588
+	 */
2589
+	public function _reg_attendees_meta_box()
2590
+	{
2591
+		$REG = EEM_Registration::instance();
2592
+		// get all other registrations on this transaction, and cache
2593
+		// the attendees for them so we don't have to run another query using force_join
2594
+		$registrations = $REG->get_all(
2595
+			array(
2596
+				array(
2597
+					'TXN_ID' => $this->_registration->transaction_ID(),
2598
+					'REG_ID' => array('!=', $this->_registration->ID()),
2599
+				),
2600
+				'force_join' => array('Attendee'),
2601
+			)
2602
+		);
2603
+		$this->_template_args['attendees'] = array();
2604
+		$this->_template_args['attendee_notice'] = '';
2605
+		if (empty($registrations)
2606
+			|| (is_array($registrations)
2607
+				&& ! EEH_Array::get_one_item_from_array($registrations))
2608
+		) {
2609
+			EE_Error::add_error(
2610
+				esc_html__(
2611
+					'There are no records attached to this registration. Something may have gone wrong with the registration',
2612
+					'event_espresso'
2613
+				),
2614
+				__FILE__,
2615
+				__FUNCTION__,
2616
+				__LINE__
2617
+			);
2618
+			$this->_template_args['attendee_notice'] = EE_Error::get_notices();
2619
+		} else {
2620
+			$att_nmbr = 1;
2621
+			foreach ($registrations as $registration) {
2622
+				/* @var $registration EE_Registration */
2623
+				$attendee = $registration->attendee()
2624
+					? $registration->attendee()
2625
+					: EEM_Attendee::instance()
2626
+								  ->create_default_object();
2627
+				$this->_template_args['attendees'][ $att_nmbr ]['STS_ID'] = $registration->status_ID();
2628
+				$this->_template_args['attendees'][ $att_nmbr ]['fname'] = $attendee->fname();
2629
+				$this->_template_args['attendees'][ $att_nmbr ]['lname'] = $attendee->lname();
2630
+				$this->_template_args['attendees'][ $att_nmbr ]['email'] = $attendee->email();
2631
+				$this->_template_args['attendees'][ $att_nmbr ]['final_price'] = $registration->final_price();
2632
+				$this->_template_args['attendees'][ $att_nmbr ]['address'] = implode(
2633
+					', ',
2634
+					$attendee->full_address_as_array()
2635
+				);
2636
+				$this->_template_args['attendees'][ $att_nmbr ]['att_link'] = self::add_query_args_and_nonce(
2637
+					array(
2638
+						'action' => 'edit_attendee',
2639
+						'post'   => $attendee->ID(),
2640
+					),
2641
+					REG_ADMIN_URL
2642
+				);
2643
+				$this->_template_args['attendees'][ $att_nmbr ]['event_name'] = $registration->event_obj() instanceof EE_Event
2644
+					? $registration->event_obj()->name()
2645
+					: '';
2646
+				$att_nmbr++;
2647
+			}
2648
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2649
+		}
2650
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2651
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2652
+	}
2653
+
2654
+
2655
+	/**
2656
+	 *        generates HTML for the Edit Registration side meta box
2657
+	 *
2658
+	 * @access public
2659
+	 * @return void
2660
+	 * @throws DomainException
2661
+	 * @throws EE_Error
2662
+	 * @throws InvalidArgumentException
2663
+	 * @throws InvalidDataTypeException
2664
+	 * @throws InvalidInterfaceException
2665
+	 */
2666
+	public function _reg_registrant_side_meta_box()
2667
+	{
2668
+		/*@var $attendee EE_Attendee */
2669
+		$att_check = $this->_registration->attendee();
2670
+		$attendee = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2671
+		// now let's determine if this is not the primary registration.  If it isn't then we set the
2672
+		// primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2673
+		// primary registration object (that way we know if we need to show create button or not)
2674
+		if (! $this->_registration->is_primary_registrant()) {
2675
+			$primary_registration = $this->_registration->get_primary_registration();
2676
+			$primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2677
+				: null;
2678
+			if (! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2679
+				// in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2680
+				// custom attendee object so let's not worry about the primary reg.
2681
+				$primary_registration = null;
2682
+			}
2683
+		} else {
2684
+			$primary_registration = null;
2685
+		}
2686
+		$this->_template_args['ATT_ID'] = $attendee->ID();
2687
+		$this->_template_args['fname'] = $attendee->fname();
2688
+		$this->_template_args['lname'] = $attendee->lname();
2689
+		$this->_template_args['email'] = $attendee->email();
2690
+		$this->_template_args['phone'] = $attendee->phone();
2691
+		$this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2692
+		// edit link
2693
+		$this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(
2694
+			array(
2695
+				'action' => 'edit_attendee',
2696
+				'post'   => $attendee->ID(),
2697
+			),
2698
+			REG_ADMIN_URL
2699
+		);
2700
+		$this->_template_args['att_edit_label'] = esc_html__('View/Edit Contact', 'event_espresso');
2701
+		// create link
2702
+		$this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2703
+			? EE_Admin_Page::add_query_args_and_nonce(
2704
+				array(
2705
+					'action'  => 'duplicate_attendee',
2706
+					'_REG_ID' => $this->_registration->ID(),
2707
+				),
2708
+				REG_ADMIN_URL
2709
+			) : '';
2710
+		$this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2711
+		$this->_template_args['att_check'] = $att_check;
2712
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2713
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2714
+	}
2715
+
2716
+
2717
+	/**
2718
+	 * trash or restore registrations
2719
+	 *
2720
+	 * @param  boolean $trash whether to archive or restore
2721
+	 * @return void
2722
+	 * @throws EE_Error
2723
+	 * @throws InvalidArgumentException
2724
+	 * @throws InvalidDataTypeException
2725
+	 * @throws InvalidInterfaceException
2726
+	 * @throws RuntimeException
2727
+	 * @access protected
2728
+	 */
2729
+	protected function _trash_or_restore_registrations($trash = true)
2730
+	{
2731
+		// if empty _REG_ID then get out because there's nothing to do
2732
+		if (empty($this->_req_data['_REG_ID'])) {
2733
+			EE_Error::add_error(
2734
+				sprintf(
2735
+					esc_html__(
2736
+						'In order to %1$s registrations you must select which ones you wish to %1$s by clicking the checkboxes.',
2737
+						'event_espresso'
2738
+					),
2739
+					$trash ? 'trash' : 'restore'
2740
+				),
2741
+				__FILE__,
2742
+				__LINE__,
2743
+				__FUNCTION__
2744
+			);
2745
+			$this->_redirect_after_action(false, '', '', array(), true);
2746
+		}
2747
+		$success = 0;
2748
+		$overwrite_msgs = false;
2749
+		// Checkboxes
2750
+		if (! is_array($this->_req_data['_REG_ID'])) {
2751
+			$this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2752
+		}
2753
+		$reg_count = count($this->_req_data['_REG_ID']);
2754
+		// cycle thru checkboxes
2755
+		foreach ($this->_req_data['_REG_ID'] as $REG_ID) {
2756
+			/** @var EE_Registration $REG */
2757
+			$REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2758
+			$payments = $REG->registration_payments();
2759
+			if (! empty($payments)) {
2760
+				$name = $REG->attendee() instanceof EE_Attendee
2761
+					? $REG->attendee()->full_name()
2762
+					: esc_html__('Unknown Attendee', 'event_espresso');
2763
+				$overwrite_msgs = true;
2764
+				EE_Error::add_error(
2765
+					sprintf(
2766
+						esc_html__(
2767
+							'The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2768
+							'event_espresso'
2769
+						),
2770
+						$name
2771
+					),
2772
+					__FILE__,
2773
+					__FUNCTION__,
2774
+					__LINE__
2775
+				);
2776
+				// can't trash this registration because it has payments.
2777
+				continue;
2778
+			}
2779
+			$updated = $trash ? $REG->delete() : $REG->restore();
2780
+			if ($updated) {
2781
+				$success++;
2782
+			}
2783
+		}
2784
+		$this->_redirect_after_action(
2785
+			$success === $reg_count, // were ALL registrations affected?
2786
+			$success > 1
2787
+				? esc_html__('Registrations', 'event_espresso')
2788
+				: esc_html__('Registration', 'event_espresso'),
2789
+			$trash
2790
+				? esc_html__('moved to the trash', 'event_espresso')
2791
+				: esc_html__('restored', 'event_espresso'),
2792
+			$this->mergeExistingRequestParamsWithRedirectArgs(array('action' => 'default')),
2793
+			$overwrite_msgs
2794
+		);
2795
+	}
2796
+
2797
+
2798
+	/**
2799
+	 * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2800
+	 * registration but also.
2801
+	 * 1. Removing relations to EE_Attendee
2802
+	 * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2803
+	 * ALSO trashed.
2804
+	 * 3. Deleting permanently any related Line items but only if the above conditions are met.
2805
+	 * 4. Removing relationships between all tickets and the related registrations
2806
+	 * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2807
+	 * 6. Deleting permanently any related Checkins.
2808
+	 *
2809
+	 * @return void
2810
+	 * @throws EE_Error
2811
+	 * @throws InvalidArgumentException
2812
+	 * @throws InvalidDataTypeException
2813
+	 * @throws InvalidInterfaceException
2814
+	 */
2815
+	protected function _delete_registrations()
2816
+	{
2817
+		$REG_MDL = EEM_Registration::instance();
2818
+		$success = 1;
2819
+		// Checkboxes
2820
+		if (! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2821
+			// if array has more than one element than success message should be plural
2822
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2823
+			// cycle thru checkboxes
2824
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2825
+				$REG = $REG_MDL->get_one_by_ID($REG_ID);
2826
+				if (! $REG instanceof EE_Registration) {
2827
+					continue;
2828
+				}
2829
+				$deleted = $this->_delete_registration($REG);
2830
+				if (! $deleted) {
2831
+					$success = 0;
2832
+				}
2833
+			}
2834
+		} else {
2835
+			// grab single id and delete
2836
+			$REG_ID = $this->_req_data['_REG_ID'];
2837
+			$REG = $REG_MDL->get_one_by_ID($REG_ID);
2838
+			$deleted = $this->_delete_registration($REG);
2839
+			if (! $deleted) {
2840
+				$success = 0;
2841
+			}
2842
+		}
2843
+		$what = $success > 1
2844
+			? esc_html__('Registrations', 'event_espresso')
2845
+			: esc_html__('Registration', 'event_espresso');
2846
+		$action_desc = esc_html__('permanently deleted.', 'event_espresso');
2847
+		$this->_redirect_after_action(
2848
+			$success,
2849
+			$what,
2850
+			$action_desc,
2851
+			$this->mergeExistingRequestParamsWithRedirectArgs(['action' => 'default']),
2852
+			true
2853
+		);
2854
+	}
2855
+
2856
+
2857
+	/**
2858
+	 * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2859
+	 * models get affected.
2860
+	 *
2861
+	 * @param  EE_Registration $REG registration to be deleted permenantly
2862
+	 * @return bool true = successful deletion, false = fail.
2863
+	 * @throws EE_Error
2864
+	 */
2865
+	protected function _delete_registration(EE_Registration $REG)
2866
+	{
2867
+		// first we start with the transaction... ultimately, we WILL not delete permanently if there are any related
2868
+		// registrations on the transaction that are NOT trashed.
2869
+		$TXN = $REG->get_first_related('Transaction');
2870
+		$REGS = $TXN->get_many_related('Registration');
2871
+		$all_trashed = true;
2872
+		foreach ($REGS as $registration) {
2873
+			if (! $registration->get('REG_deleted')) {
2874
+				$all_trashed = false;
2875
+			}
2876
+		}
2877
+		if (! $all_trashed) {
2878
+			EE_Error::add_error(
2879
+				esc_html__(
2880
+					'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2881
+					'event_espresso'
2882
+				),
2883
+				__FILE__,
2884
+				__FUNCTION__,
2885
+				__LINE__
2886
+			);
2887
+			return false;
2888
+		}
2889
+		// k made it here so that means we can delete all the related transactions and their answers (but let's do them
2890
+		// separately from THIS one).
2891
+		foreach ($REGS as $registration) {
2892
+			// delete related answers
2893
+			$registration->delete_related_permanently('Answer');
2894
+			// remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2895
+			$attendee = $registration->get_first_related('Attendee');
2896
+			if ($attendee instanceof EE_Attendee) {
2897
+				$registration->_remove_relation_to($attendee, 'Attendee');
2898
+			}
2899
+			// now remove relationships to tickets on this registration.
2900
+			$registration->_remove_relations('Ticket');
2901
+			// now delete permanently the checkins related to this registration.
2902
+			$registration->delete_related_permanently('Checkin');
2903
+			if ($registration->ID() === $REG->ID()) {
2904
+				continue;
2905
+			} //we don't want to delete permanently the existing registration just yet.
2906
+			// remove relation to transaction for these registrations if NOT the existing registrations
2907
+			$registration->_remove_relations('Transaction');
2908
+			// delete permanently any related messages.
2909
+			$registration->delete_related_permanently('Message');
2910
+			// now delete this registration permanently
2911
+			$registration->delete_permanently();
2912
+		}
2913
+		// now all related registrations on the transaction are handled.  So let's just handle this registration itself
2914
+		// (the transaction and line items should be all that's left).
2915
+		// delete the line items related to the transaction for this registration.
2916
+		$TXN->delete_related_permanently('Line_Item');
2917
+		// we need to remove all the relationships on the transaction
2918
+		$TXN->delete_related_permanently('Payment');
2919
+		$TXN->delete_related_permanently('Extra_Meta');
2920
+		$TXN->delete_related_permanently('Message');
2921
+		// now we can delete this REG permanently (and the transaction of course)
2922
+		$REG->delete_related_permanently('Transaction');
2923
+		return $REG->delete_permanently();
2924
+	}
2925
+
2926
+
2927
+	/**
2928
+	 *    generates HTML for the Register New Attendee Admin page
2929
+	 *
2930
+	 * @access private
2931
+	 * @throws DomainException
2932
+	 * @throws EE_Error
2933
+	 */
2934
+	public function new_registration()
2935
+	{
2936
+		if (! $this->_set_reg_event()) {
2937
+			throw new EE_Error(
2938
+				esc_html__(
2939
+					'Unable to continue with registering because there is no Event ID in the request',
2940
+					'event_espresso'
2941
+				)
2942
+			);
2943
+		}
2944
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2945
+		// gotta start with a clean slate if we're not coming here via ajax
2946
+		if (! defined('DOING_AJAX')
2947
+			&& (! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2948
+		) {
2949
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2950
+		}
2951
+		$this->_template_args['event_name'] = '';
2952
+		// event name
2953
+		if ($this->_reg_event) {
2954
+			$this->_template_args['event_name'] = $this->_reg_event->name();
2955
+			$edit_event_url = self::add_query_args_and_nonce(
2956
+				array(
2957
+					'action' => 'edit',
2958
+					'post'   => $this->_reg_event->ID(),
2959
+				),
2960
+				EVENTS_ADMIN_URL
2961
+			);
2962
+			$edit_event_lnk = '<a href="'
2963
+							  . $edit_event_url
2964
+							  . '" title="'
2965
+							  . esc_attr__('Edit ', 'event_espresso')
2966
+							  . $this->_reg_event->name()
2967
+							  . '">'
2968
+							  . esc_html__('Edit Event', 'event_espresso')
2969
+							  . '</a>';
2970
+			$this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2971
+												   . $edit_event_lnk
2972
+												   . '</span>';
2973
+		}
2974
+		$this->_template_args['step_content'] = $this->_get_registration_step_content();
2975
+		if (defined('DOING_AJAX')) {
2976
+			$this->_return_json();
2977
+		}
2978
+		// grab header
2979
+		$template_path =
2980
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2981
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
2982
+			$template_path,
2983
+			$this->_template_args,
2984
+			true
2985
+		);
2986
+		// $this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2987
+		// the details template wrapper
2988
+		$this->display_admin_page_with_sidebar();
2989
+	}
2990
+
2991
+
2992
+	/**
2993
+	 * This returns the content for a registration step
2994
+	 *
2995
+	 * @access protected
2996
+	 * @return string html
2997
+	 * @throws DomainException
2998
+	 * @throws EE_Error
2999
+	 * @throws InvalidArgumentException
3000
+	 * @throws InvalidDataTypeException
3001
+	 * @throws InvalidInterfaceException
3002
+	 */
3003
+	protected function _get_registration_step_content()
3004
+	{
3005
+		if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
3006
+			$warning_msg = sprintf(
3007
+				esc_html__(
3008
+					'%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
3009
+					'event_espresso'
3010
+				),
3011
+				'<br />',
3012
+				'<h3 class="important-notice">',
3013
+				'</h3>',
3014
+				'<div class="float-right">',
3015
+				'<span id="redirect_timer" class="important-notice">30</span>',
3016
+				'</div>',
3017
+				'<b>',
3018
+				'</b>'
3019
+			);
3020
+			return '
3021 3021
 	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
3022 3022
 	<script >
3023 3023
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
@@ -3030,855 +3030,855 @@  discard block
 block discarded – undo
3030 3030
 	        }
3031 3031
 	    }, 800 );
3032 3032
 	</script >';
3033
-        }
3034
-        $template_args = array(
3035
-            'title'                    => '',
3036
-            'content'                  => '',
3037
-            'step_button_text'         => '',
3038
-            'show_notification_toggle' => false,
3039
-        );
3040
-        // to indicate we're processing a new registration
3041
-        $hidden_fields = array(
3042
-            'processing_registration' => array(
3043
-                'type'  => 'hidden',
3044
-                'value' => 0,
3045
-            ),
3046
-            'event_id'                => array(
3047
-                'type'  => 'hidden',
3048
-                'value' => $this->_reg_event->ID(),
3049
-            ),
3050
-        );
3051
-        // if the cart is empty then we know we're at step one so we'll display ticket selector
3052
-        $cart = EE_Registry::instance()->SSN->cart();
3053
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3054
-        switch ($step) {
3055
-            case 'ticket':
3056
-                $hidden_fields['processing_registration']['value'] = 1;
3057
-                $template_args['title'] = esc_html__(
3058
-                    'Step One: Select the Ticket for this registration',
3059
-                    'event_espresso'
3060
-                );
3061
-                $template_args['content'] =
3062
-                    EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
3063
-                $template_args['step_button_text'] = esc_html__(
3064
-                    'Add Tickets and Continue to Registrant Details',
3065
-                    'event_espresso'
3066
-                );
3067
-                $template_args['show_notification_toggle'] = false;
3068
-                break;
3069
-            case 'questions':
3070
-                $hidden_fields['processing_registration']['value'] = 2;
3071
-                $template_args['title'] = esc_html__(
3072
-                    'Step Two: Add Registrant Details for this Registration',
3073
-                    'event_espresso'
3074
-                );
3075
-                // in theory we should be able to run EED_SPCO at this point because the cart should have been setup
3076
-                // properly by the first process_reg_step run.
3077
-                $template_args['content'] =
3078
-                    EED_Single_Page_Checkout::registration_checkout_for_admin();
3079
-                $template_args['step_button_text'] = esc_html__(
3080
-                    'Save Registration and Continue to Details',
3081
-                    'event_espresso'
3082
-                );
3083
-                $template_args['show_notification_toggle'] = true;
3084
-                break;
3085
-        }
3086
-        // we come back to the process_registration_step route.
3087
-        $this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
3088
-        return EEH_Template::display_template(
3089
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
3090
-            $template_args,
3091
-            true
3092
-        );
3093
-    }
3094
-
3095
-
3096
-    /**
3097
-     *        set_reg_event
3098
-     *
3099
-     * @access private
3100
-     * @return bool
3101
-     * @throws EE_Error
3102
-     * @throws InvalidArgumentException
3103
-     * @throws InvalidDataTypeException
3104
-     * @throws InvalidInterfaceException
3105
-     */
3106
-    private function _set_reg_event()
3107
-    {
3108
-        if (is_object($this->_reg_event)) {
3109
-            return true;
3110
-        }
3111
-        $EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
3112
-        if (! $EVT_ID) {
3113
-            return false;
3114
-        }
3115
-        $this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
3116
-        return true;
3117
-    }
3118
-
3119
-
3120
-    /**
3121
-     * process_reg_step
3122
-     *
3123
-     * @access        public
3124
-     * @return string
3125
-     * @throws DomainException
3126
-     * @throws EE_Error
3127
-     * @throws InvalidArgumentException
3128
-     * @throws InvalidDataTypeException
3129
-     * @throws InvalidInterfaceException
3130
-     * @throws ReflectionException
3131
-     * @throws RuntimeException
3132
-     */
3133
-    public function process_reg_step()
3134
-    {
3135
-        EE_System::do_not_cache();
3136
-        $this->_set_reg_event();
3137
-        EE_Registry::instance()->REQ->set_espresso_page(true);
3138
-        EE_Registry::instance()->REQ->set('uts', time());
3139
-        // what step are we on?
3140
-        $cart = EE_Registry::instance()->SSN->cart();
3141
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3142
-        // if doing ajax then we need to verify the nonce
3143
-        if (defined('DOING_AJAX')) {
3144
-            $nonce = isset($this->_req_data[ $this->_req_nonce ])
3145
-                ? sanitize_text_field($this->_req_data[ $this->_req_nonce ]) : '';
3146
-            $this->_verify_nonce($nonce, $this->_req_nonce);
3147
-        }
3148
-        switch ($step) {
3149
-            case 'ticket':
3150
-                // process ticket selection
3151
-                $success = EED_Ticket_Selector::instance()->process_ticket_selections();
3152
-                if ($success) {
3153
-                    EE_Error::add_success(
3154
-                        esc_html__(
3155
-                            'Tickets Selected. Now complete the registration.',
3156
-                            'event_espresso'
3157
-                        )
3158
-                    );
3159
-                } else {
3160
-                    $query_args['step_error'] = $this->_req_data['step_error'] = true;
3161
-                }
3162
-                if (defined('DOING_AJAX')) {
3163
-                    $this->new_registration(); // display next step
3164
-                } else {
3165
-                    $query_args = array(
3166
-                        'action'                  => 'new_registration',
3167
-                        'processing_registration' => 1,
3168
-                        'event_id'                => $this->_reg_event->ID(),
3169
-                        'uts'                     => time(),
3170
-                    );
3171
-                    $this->_redirect_after_action(
3172
-                        false,
3173
-                        '',
3174
-                        '',
3175
-                        $query_args,
3176
-                        true
3177
-                    );
3178
-                }
3179
-                break;
3180
-            case 'questions':
3181
-                if (! isset(
3182
-                    $this->_req_data['txn_reg_status_change'],
3183
-                    $this->_req_data['txn_reg_status_change']['send_notifications']
3184
-                )
3185
-                ) {
3186
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
3187
-                }
3188
-                // process registration
3189
-                $transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
3190
-                if ($cart instanceof EE_Cart) {
3191
-                    $grand_total = $cart->get_cart_grand_total();
3192
-                    if ($grand_total instanceof EE_Line_Item) {
3193
-                        $grand_total->save_this_and_descendants_to_txn();
3194
-                    }
3195
-                }
3196
-                if (! $transaction instanceof EE_Transaction) {
3197
-                    $query_args = array(
3198
-                        'action'                  => 'new_registration',
3199
-                        'processing_registration' => 2,
3200
-                        'event_id'                => $this->_reg_event->ID(),
3201
-                        'uts'                     => time(),
3202
-                    );
3203
-                    if (defined('DOING_AJAX')) {
3204
-                        // display registration form again because there are errors (maybe validation?)
3205
-                        $this->new_registration();
3206
-                        return;
3207
-                    } else {
3208
-                        $this->_redirect_after_action(
3209
-                            false,
3210
-                            '',
3211
-                            '',
3212
-                            $query_args,
3213
-                            true
3214
-                        );
3215
-                        return;
3216
-                    }
3217
-                }
3218
-                // maybe update status, and make sure to save transaction if not done already
3219
-                if (! $transaction->update_status_based_on_total_paid()) {
3220
-                    $transaction->save();
3221
-                }
3222
-                EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3223
-                $this->_req_data = array();
3224
-                $query_args = array(
3225
-                    'action'        => 'redirect_to_txn',
3226
-                    'TXN_ID'        => $transaction->ID(),
3227
-                    'EVT_ID'        => $this->_reg_event->ID(),
3228
-                    'event_name'    => urlencode($this->_reg_event->name()),
3229
-                    'redirect_from' => 'new_registration',
3230
-                );
3231
-                $this->_redirect_after_action(false, '', '', $query_args, true);
3232
-                break;
3233
-        }
3234
-        // what are you looking here for?  Should be nothing to do at this point.
3235
-    }
3236
-
3237
-
3238
-    /**
3239
-     * redirect_to_txn
3240
-     *
3241
-     * @access public
3242
-     * @return void
3243
-     * @throws EE_Error
3244
-     * @throws InvalidArgumentException
3245
-     * @throws InvalidDataTypeException
3246
-     * @throws InvalidInterfaceException
3247
-     */
3248
-    public function redirect_to_txn()
3249
-    {
3250
-        EE_System::do_not_cache();
3251
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3252
-        $query_args = array(
3253
-            'action' => 'view_transaction',
3254
-            'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
3255
-            'page'   => 'espresso_transactions',
3256
-        );
3257
-        if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
3258
-            $query_args['EVT_ID'] = $this->_req_data['EVT_ID'];
3259
-            $query_args['event_name'] = urlencode($this->_req_data['event_name']);
3260
-            $query_args['redirect_from'] = $this->_req_data['redirect_from'];
3261
-        }
3262
-        EE_Error::add_success(
3263
-            esc_html__(
3264
-                'Registration Created.  Please review the transaction and add any payments as necessary',
3265
-                'event_espresso'
3266
-            )
3267
-        );
3268
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3269
-    }
3270
-
3271
-
3272
-    /**
3273
-     *        generates HTML for the Attendee Contact List
3274
-     *
3275
-     * @access protected
3276
-     * @return void
3277
-     */
3278
-    protected function _attendee_contact_list_table()
3279
-    {
3280
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3281
-        $this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
3282
-        $this->display_admin_list_table_page_with_no_sidebar();
3283
-    }
3284
-
3285
-
3286
-    /**
3287
-     *        get_attendees
3288
-     *
3289
-     * @param      $per_page
3290
-     * @param bool $count whether to return count or data.
3291
-     * @param bool $trash
3292
-     * @return array
3293
-     * @throws EE_Error
3294
-     * @throws InvalidArgumentException
3295
-     * @throws InvalidDataTypeException
3296
-     * @throws InvalidInterfaceException
3297
-     * @access public
3298
-     */
3299
-    public function get_attendees($per_page, $count = false, $trash = false)
3300
-    {
3301
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3302
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3303
-        $ATT_MDL = EEM_Attendee::instance();
3304
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3305
-        switch ($this->_req_data['orderby']) {
3306
-            case 'ATT_ID':
3307
-                $orderby = 'ATT_ID';
3308
-                break;
3309
-            case 'ATT_fname':
3310
-                $orderby = 'ATT_fname';
3311
-                break;
3312
-            case 'ATT_email':
3313
-                $orderby = 'ATT_email';
3314
-                break;
3315
-            case 'ATT_city':
3316
-                $orderby = 'ATT_city';
3317
-                break;
3318
-            case 'STA_ID':
3319
-                $orderby = 'STA_ID';
3320
-                break;
3321
-            case 'CNT_ID':
3322
-                $orderby = 'CNT_ID';
3323
-                break;
3324
-            case 'Registration_Count':
3325
-                $orderby = 'Registration_Count';
3326
-                break;
3327
-            default:
3328
-                $orderby = 'ATT_lname';
3329
-        }
3330
-        $sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
3331
-            ? $this->_req_data['order']
3332
-            : 'ASC';
3333
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
3334
-            ? $this->_req_data['paged']
3335
-            : 1;
3336
-        $per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
3337
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3338
-            ? $this->_req_data['perpage']
3339
-            : $per_page;
3340
-        $_where = array();
3341
-        if (! empty($this->_req_data['s'])) {
3342
-            $sstr = '%' . $this->_req_data['s'] . '%';
3343
-            $_where['OR'] = array(
3344
-                'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3345
-                'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3346
-                'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3347
-                'ATT_fname'                         => array('LIKE', $sstr),
3348
-                'ATT_lname'                         => array('LIKE', $sstr),
3349
-                'ATT_short_bio'                     => array('LIKE', $sstr),
3350
-                'ATT_email'                         => array('LIKE', $sstr),
3351
-                'ATT_address'                       => array('LIKE', $sstr),
3352
-                'ATT_address2'                      => array('LIKE', $sstr),
3353
-                'ATT_city'                          => array('LIKE', $sstr),
3354
-                'Country.CNT_name'                  => array('LIKE', $sstr),
3355
-                'State.STA_name'                    => array('LIKE', $sstr),
3356
-                'ATT_phone'                         => array('LIKE', $sstr),
3357
-                'Registration.REG_final_price'      => array('LIKE', $sstr),
3358
-                'Registration.REG_code'             => array('LIKE', $sstr),
3359
-                'Registration.REG_group_size'       => array('LIKE', $sstr),
3360
-            );
3361
-        }
3362
-        $offset = ($current_page - 1) * $per_page;
3363
-        $limit = $count ? null : array($offset, $per_page);
3364
-        $query_args = array(
3365
-            $_where,
3366
-            'extra_selects' => array('Registration_Count' => array('Registration.REG_ID', 'count', '%d')),
3367
-            'limit'         => $limit,
3368
-        );
3369
-        if (! $count) {
3370
-            $query_args['order_by'] = array($orderby => $sort);
3371
-        }
3372
-        if ($trash) {
3373
-            $query_args[0]['status'] = array('!=', 'publish');
3374
-            $all_attendees = $count
3375
-                ? $ATT_MDL->count($query_args, 'ATT_ID', true)
3376
-                : $ATT_MDL->get_all($query_args);
3377
-        } else {
3378
-            $query_args[0]['status'] = array('IN', array('publish'));
3379
-            $all_attendees = $count
3380
-                ? $ATT_MDL->count($query_args, 'ATT_ID', true)
3381
-                : $ATT_MDL->get_all($query_args);
3382
-        }
3383
-        return $all_attendees;
3384
-    }
3385
-
3386
-
3387
-    /**
3388
-     * This is just taking care of resending the registration confirmation
3389
-     *
3390
-     * @access protected
3391
-     * @return void
3392
-     */
3393
-    protected function _resend_registration()
3394
-    {
3395
-        $this->_process_resend_registration();
3396
-        $query_args = isset($this->_req_data['redirect_to'])
3397
-            ? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3398
-            : array('action' => 'default');
3399
-        $this->_redirect_after_action(false, '', '', $query_args, true);
3400
-    }
3401
-
3402
-    /**
3403
-     * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3404
-     * to use when selecting registrations
3405
-     *
3406
-     * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3407
-     *                                                     the query parameters from the request
3408
-     * @return void ends the request with a redirect or download
3409
-     */
3410
-    public function _registrations_report_base($method_name_for_getting_query_params)
3411
-    {
3412
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3413
-            wp_redirect(
3414
-                EE_Admin_Page::add_query_args_and_nonce(
3415
-                    array(
3416
-                        'page'        => 'espresso_batch',
3417
-                        'batch'       => 'file',
3418
-                        'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3419
-                        'filters'     => urlencode(
3420
-                            serialize(
3421
-                                call_user_func(
3422
-                                    array($this, $method_name_for_getting_query_params),
3423
-                                    EEH_Array::is_set(
3424
-                                        $this->_req_data,
3425
-                                        'filters',
3426
-                                        array()
3427
-                                    )
3428
-                                )
3429
-                            )
3430
-                        ),
3431
-                        'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3432
-                        'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3433
-                        'return_url'  => urlencode($this->_req_data['return_url']),
3434
-                    )
3435
-                )
3436
-            );
3437
-        } else {
3438
-            $new_request_args = array(
3439
-                'export' => 'report',
3440
-                'action' => 'registrations_report_for_event',
3441
-                'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3442
-            );
3443
-            $this->_req_data = array_merge($this->_req_data, $new_request_args);
3444
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3445
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3446
-                $EE_Export = EE_Export::instance($this->_req_data);
3447
-                $EE_Export->export();
3448
-            }
3449
-        }
3450
-    }
3451
-
3452
-
3453
-    /**
3454
-     * Creates a registration report using only query parameters in the request
3455
-     *
3456
-     * @return void
3457
-     */
3458
-    public function _registrations_report()
3459
-    {
3460
-        $this->_registrations_report_base('_get_registration_query_parameters');
3461
-    }
3462
-
3463
-
3464
-    public function _contact_list_export()
3465
-    {
3466
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3467
-            require_once(EE_CLASSES . 'EE_Export.class.php');
3468
-            $EE_Export = EE_Export::instance($this->_req_data);
3469
-            $EE_Export->export_attendees();
3470
-        }
3471
-    }
3472
-
3473
-
3474
-    public function _contact_list_report()
3475
-    {
3476
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3477
-            wp_redirect(
3478
-                EE_Admin_Page::add_query_args_and_nonce(
3479
-                    array(
3480
-                        'page'        => 'espresso_batch',
3481
-                        'batch'       => 'file',
3482
-                        'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3483
-                        'return_url'  => urlencode($this->_req_data['return_url']),
3484
-                    )
3485
-                )
3486
-            );
3487
-        } else {
3488
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3489
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3490
-                $EE_Export = EE_Export::instance($this->_req_data);
3491
-                $EE_Export->report_attendees();
3492
-            }
3493
-        }
3494
-    }
3495
-
3496
-
3497
-
3498
-
3499
-
3500
-    /***************************************        ATTENDEE DETAILS        ***************************************/
3501
-    /**
3502
-     * This duplicates the attendee object for the given incoming registration id and attendee_id.
3503
-     *
3504
-     * @return void
3505
-     * @throws EE_Error
3506
-     * @throws InvalidArgumentException
3507
-     * @throws InvalidDataTypeException
3508
-     * @throws InvalidInterfaceException
3509
-     */
3510
-    protected function _duplicate_attendee()
3511
-    {
3512
-        $action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3513
-        // verify we have necessary info
3514
-        if (empty($this->_req_data['_REG_ID'])) {
3515
-            EE_Error::add_error(
3516
-                esc_html__(
3517
-                    'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3518
-                    'event_espresso'
3519
-                ),
3520
-                __FILE__,
3521
-                __LINE__,
3522
-                __FUNCTION__
3523
-            );
3524
-            $query_args = array('action' => $action);
3525
-            $this->_redirect_after_action('', '', '', $query_args, true);
3526
-        }
3527
-        // okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3528
-        $registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3529
-        $attendee = $registration->attendee();
3530
-        // remove relation of existing attendee on registration
3531
-        $registration->_remove_relation_to($attendee, 'Attendee');
3532
-        // new attendee
3533
-        $new_attendee = clone $attendee;
3534
-        $new_attendee->set('ATT_ID', 0);
3535
-        $new_attendee->save();
3536
-        // add new attendee to reg
3537
-        $registration->_add_relation_to($new_attendee, 'Attendee');
3538
-        EE_Error::add_success(
3539
-            esc_html__(
3540
-                'New Contact record created.  Now make any edits you wish to make for this contact.',
3541
-                'event_espresso'
3542
-            )
3543
-        );
3544
-        // redirect to edit page for attendee
3545
-        $query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3546
-        $this->_redirect_after_action('', '', '', $query_args, true);
3547
-    }
3548
-
3549
-
3550
-    /**
3551
-     * Callback invoked by parent EE_Admin_CPT class hooked in on `save_post` wp hook.
3552
-     *
3553
-     * @param int     $post_id
3554
-     * @param WP_POST $post
3555
-     * @throws DomainException
3556
-     * @throws EE_Error
3557
-     * @throws InvalidArgumentException
3558
-     * @throws InvalidDataTypeException
3559
-     * @throws InvalidInterfaceException
3560
-     * @throws LogicException
3561
-     * @throws InvalidFormSubmissionException
3562
-     */
3563
-    protected function _insert_update_cpt_item($post_id, $post)
3564
-    {
3565
-        $success = true;
3566
-        $attendee = $post instanceof WP_Post && $post->post_type === 'espresso_attendees'
3567
-            ? EEM_Attendee::instance()->get_one_by_ID($post_id)
3568
-            : null;
3569
-        // for attendee updates
3570
-        if ($attendee instanceof EE_Attendee) {
3571
-            // note we should only be UPDATING attendees at this point.
3572
-            $updated_fields = array(
3573
-                'ATT_fname'     => $this->_req_data['ATT_fname'],
3574
-                'ATT_lname'     => $this->_req_data['ATT_lname'],
3575
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3576
-                'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3577
-                'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3578
-                'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3579
-                'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3580
-                'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3581
-                'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3582
-            );
3583
-            foreach ($updated_fields as $field => $value) {
3584
-                $attendee->set($field, $value);
3585
-            }
3586
-
3587
-            // process contact details metabox form handler (which will also save the attendee)
3588
-            $contact_details_form = $this->getAttendeeContactDetailsMetaboxFormHandler($attendee);
3589
-            $success = $contact_details_form->process($this->_req_data);
3590
-
3591
-            $attendee_update_callbacks = apply_filters(
3592
-                'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3593
-                array()
3594
-            );
3595
-            foreach ($attendee_update_callbacks as $a_callback) {
3596
-                if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3597
-                    throw new EE_Error(
3598
-                        sprintf(
3599
-                            esc_html__(
3600
-                                'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3601
-                                'event_espresso'
3602
-                            ),
3603
-                            $a_callback
3604
-                        )
3605
-                    );
3606
-                }
3607
-            }
3608
-        }
3609
-
3610
-        if ($success === false) {
3611
-            EE_Error::add_error(
3612
-                esc_html__(
3613
-                    'Something went wrong with updating the meta table data for the registration.',
3614
-                    'event_espresso'
3615
-                ),
3616
-                __FILE__,
3617
-                __FUNCTION__,
3618
-                __LINE__
3619
-            );
3620
-        }
3621
-    }
3622
-
3623
-
3624
-    public function trash_cpt_item($post_id)
3625
-    {
3626
-    }
3627
-
3628
-
3629
-    public function delete_cpt_item($post_id)
3630
-    {
3631
-    }
3632
-
3633
-
3634
-    public function restore_cpt_item($post_id)
3635
-    {
3636
-    }
3637
-
3638
-
3639
-    protected function _restore_cpt_item($post_id, $revision_id)
3640
-    {
3641
-    }
3642
-
3643
-
3644
-    public function attendee_editor_metaboxes()
3645
-    {
3646
-        $this->verify_cpt_object();
3647
-        remove_meta_box(
3648
-            'postexcerpt',
3649
-            esc_html__('Excerpt', 'event_espresso'),
3650
-            'post_excerpt_meta_box',
3651
-            $this->_cpt_routes[ $this->_req_action ],
3652
-            'normal',
3653
-            'core'
3654
-        );
3655
-        remove_meta_box('commentstatusdiv', $this->_cpt_routes[ $this->_req_action ], 'normal', 'core');
3656
-        if (post_type_supports('espresso_attendees', 'excerpt')) {
3657
-            add_meta_box(
3658
-                'postexcerpt',
3659
-                esc_html__('Short Biography', 'event_espresso'),
3660
-                'post_excerpt_meta_box',
3661
-                $this->_cpt_routes[ $this->_req_action ],
3662
-                'normal'
3663
-            );
3664
-        }
3665
-        if (post_type_supports('espresso_attendees', 'comments')) {
3666
-            add_meta_box(
3667
-                'commentsdiv',
3668
-                esc_html__('Notes on the Contact', 'event_espresso'),
3669
-                'post_comment_meta_box',
3670
-                $this->_cpt_routes[ $this->_req_action ],
3671
-                'normal',
3672
-                'core'
3673
-            );
3674
-        }
3675
-        add_meta_box(
3676
-            'attendee_contact_info',
3677
-            esc_html__('Contact Info', 'event_espresso'),
3678
-            array($this, 'attendee_contact_info'),
3679
-            $this->_cpt_routes[ $this->_req_action ],
3680
-            'side',
3681
-            'core'
3682
-        );
3683
-        add_meta_box(
3684
-            'attendee_details_address',
3685
-            esc_html__('Address Details', 'event_espresso'),
3686
-            array($this, 'attendee_address_details'),
3687
-            $this->_cpt_routes[ $this->_req_action ],
3688
-            'normal',
3689
-            'core'
3690
-        );
3691
-        add_meta_box(
3692
-            'attendee_registrations',
3693
-            esc_html__('Registrations for this Contact', 'event_espresso'),
3694
-            array($this, 'attendee_registrations_meta_box'),
3695
-            $this->_cpt_routes[ $this->_req_action ],
3696
-            'normal',
3697
-            'high'
3698
-        );
3699
-    }
3700
-
3701
-
3702
-    /**
3703
-     * Metabox for attendee contact info
3704
-     *
3705
-     * @param  WP_Post $post wp post object
3706
-     * @return string attendee contact info ( and form )
3707
-     * @throws EE_Error
3708
-     * @throws InvalidArgumentException
3709
-     * @throws InvalidDataTypeException
3710
-     * @throws InvalidInterfaceException
3711
-     * @throws LogicException
3712
-     * @throws DomainException
3713
-     */
3714
-    public function attendee_contact_info($post)
3715
-    {
3716
-        // get attendee object ( should already have it )
3717
-        $form = $this->getAttendeeContactDetailsMetaboxFormHandler($this->_cpt_model_obj);
3718
-        $form->enqueueStylesAndScripts();
3719
-        echo $form->display();
3720
-    }
3721
-
3722
-
3723
-    /**
3724
-     * Return form handler for the contact details metabox
3725
-     *
3726
-     * @param EE_Attendee $attendee
3727
-     * @return AttendeeContactDetailsMetaboxFormHandler
3728
-     * @throws DomainException
3729
-     * @throws InvalidArgumentException
3730
-     * @throws InvalidDataTypeException
3731
-     * @throws InvalidInterfaceException
3732
-     */
3733
-    protected function getAttendeeContactDetailsMetaboxFormHandler(EE_Attendee $attendee)
3734
-    {
3735
-        return new AttendeeContactDetailsMetaboxFormHandler($attendee, EE_Registry::instance());
3736
-    }
3737
-
3738
-
3739
-    /**
3740
-     * Metabox for attendee details
3741
-     *
3742
-     * @param  WP_Post $post wp post object
3743
-     * @throws DomainException
3744
-     */
3745
-    public function attendee_address_details($post)
3746
-    {
3747
-        // get attendee object (should already have it)
3748
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
3749
-        $this->_template_args['state_html'] = EEH_Form_Fields::generate_form_input(
3750
-            new EE_Question_Form_Input(
3751
-                EE_Question::new_instance(
3752
-                    array(
3753
-                        'QST_ID'           => 0,
3754
-                        'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3755
-                        'QST_system'       => 'admin-state',
3756
-                    )
3757
-                ),
3758
-                EE_Answer::new_instance(
3759
-                    array(
3760
-                        'ANS_ID'    => 0,
3761
-                        'ANS_value' => $this->_cpt_model_obj->state_ID(),
3762
-                    )
3763
-                ),
3764
-                array(
3765
-                    'input_id'       => 'STA_ID',
3766
-                    'input_name'     => 'STA_ID',
3767
-                    'input_prefix'   => '',
3768
-                    'append_qstn_id' => false,
3769
-                )
3770
-            )
3771
-        );
3772
-        $this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3773
-            new EE_Question_Form_Input(
3774
-                EE_Question::new_instance(
3775
-                    array(
3776
-                        'QST_ID'           => 0,
3777
-                        'QST_display_text' => esc_html__('Country', 'event_espresso'),
3778
-                        'QST_system'       => 'admin-country',
3779
-                    )
3780
-                ),
3781
-                EE_Answer::new_instance(
3782
-                    array(
3783
-                        'ANS_ID'    => 0,
3784
-                        'ANS_value' => $this->_cpt_model_obj->country_ID(),
3785
-                    )
3786
-                ),
3787
-                array(
3788
-                    'input_id'       => 'CNT_ISO',
3789
-                    'input_name'     => 'CNT_ISO',
3790
-                    'input_prefix'   => '',
3791
-                    'append_qstn_id' => false,
3792
-                )
3793
-            )
3794
-        );
3795
-        $template =
3796
-            REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3797
-        EEH_Template::display_template($template, $this->_template_args);
3798
-    }
3799
-
3800
-
3801
-    /**
3802
-     *        _attendee_details
3803
-     *
3804
-     * @access protected
3805
-     * @param $post
3806
-     * @return void
3807
-     * @throws DomainException
3808
-     * @throws EE_Error
3809
-     */
3810
-    public function attendee_registrations_meta_box($post)
3811
-    {
3812
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
3813
-        $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3814
-        $template =
3815
-            REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3816
-        EEH_Template::display_template($template, $this->_template_args);
3817
-    }
3818
-
3819
-
3820
-    /**
3821
-     * add in the form fields for the attendee edit
3822
-     *
3823
-     * @param  WP_Post $post wp post object
3824
-     * @return string html for new form.
3825
-     * @throws DomainException
3826
-     */
3827
-    public function after_title_form_fields($post)
3828
-    {
3829
-        if ($post->post_type == 'espresso_attendees') {
3830
-            $template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3831
-            $template_args['attendee'] = $this->_cpt_model_obj;
3832
-            EEH_Template::display_template($template, $template_args);
3833
-        }
3834
-    }
3835
-
3836
-
3837
-    /**
3838
-     *        _trash_or_restore_attendee
3839
-     *
3840
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3841
-     * @return void
3842
-     * @throws EE_Error
3843
-     * @throws InvalidArgumentException
3844
-     * @throws InvalidDataTypeException
3845
-     * @throws InvalidInterfaceException
3846
-     * @access protected
3847
-     */
3848
-    protected function _trash_or_restore_attendees($trash = true)
3849
-    {
3850
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3851
-        $ATT_MDL = EEM_Attendee::instance();
3852
-        $success = 1;
3853
-        // Checkboxes
3854
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3855
-            // if array has more than one element than success message should be plural
3856
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3857
-            // cycle thru checkboxes
3858
-            while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3859
-                $updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3860
-                    : $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3861
-                if (! $updated) {
3862
-                    $success = 0;
3863
-                }
3864
-            }
3865
-        } else {
3866
-            // grab single id and delete
3867
-            $ATT_ID = absint($this->_req_data['ATT_ID']);
3868
-            // get attendee
3869
-            $att = $ATT_MDL->get_one_by_ID($ATT_ID);
3870
-            $updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3871
-            $updated = $att->save();
3872
-            if (! $updated) {
3873
-                $success = 0;
3874
-            }
3875
-        }
3876
-        $what = $success > 1
3877
-            ? esc_html__('Contacts', 'event_espresso')
3878
-            : esc_html__('Contact', 'event_espresso');
3879
-        $action_desc = $trash
3880
-            ? esc_html__('moved to the trash', 'event_espresso')
3881
-            : esc_html__('restored', 'event_espresso');
3882
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3883
-    }
3033
+		}
3034
+		$template_args = array(
3035
+			'title'                    => '',
3036
+			'content'                  => '',
3037
+			'step_button_text'         => '',
3038
+			'show_notification_toggle' => false,
3039
+		);
3040
+		// to indicate we're processing a new registration
3041
+		$hidden_fields = array(
3042
+			'processing_registration' => array(
3043
+				'type'  => 'hidden',
3044
+				'value' => 0,
3045
+			),
3046
+			'event_id'                => array(
3047
+				'type'  => 'hidden',
3048
+				'value' => $this->_reg_event->ID(),
3049
+			),
3050
+		);
3051
+		// if the cart is empty then we know we're at step one so we'll display ticket selector
3052
+		$cart = EE_Registry::instance()->SSN->cart();
3053
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3054
+		switch ($step) {
3055
+			case 'ticket':
3056
+				$hidden_fields['processing_registration']['value'] = 1;
3057
+				$template_args['title'] = esc_html__(
3058
+					'Step One: Select the Ticket for this registration',
3059
+					'event_espresso'
3060
+				);
3061
+				$template_args['content'] =
3062
+					EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
3063
+				$template_args['step_button_text'] = esc_html__(
3064
+					'Add Tickets and Continue to Registrant Details',
3065
+					'event_espresso'
3066
+				);
3067
+				$template_args['show_notification_toggle'] = false;
3068
+				break;
3069
+			case 'questions':
3070
+				$hidden_fields['processing_registration']['value'] = 2;
3071
+				$template_args['title'] = esc_html__(
3072
+					'Step Two: Add Registrant Details for this Registration',
3073
+					'event_espresso'
3074
+				);
3075
+				// in theory we should be able to run EED_SPCO at this point because the cart should have been setup
3076
+				// properly by the first process_reg_step run.
3077
+				$template_args['content'] =
3078
+					EED_Single_Page_Checkout::registration_checkout_for_admin();
3079
+				$template_args['step_button_text'] = esc_html__(
3080
+					'Save Registration and Continue to Details',
3081
+					'event_espresso'
3082
+				);
3083
+				$template_args['show_notification_toggle'] = true;
3084
+				break;
3085
+		}
3086
+		// we come back to the process_registration_step route.
3087
+		$this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
3088
+		return EEH_Template::display_template(
3089
+			REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
3090
+			$template_args,
3091
+			true
3092
+		);
3093
+	}
3094
+
3095
+
3096
+	/**
3097
+	 *        set_reg_event
3098
+	 *
3099
+	 * @access private
3100
+	 * @return bool
3101
+	 * @throws EE_Error
3102
+	 * @throws InvalidArgumentException
3103
+	 * @throws InvalidDataTypeException
3104
+	 * @throws InvalidInterfaceException
3105
+	 */
3106
+	private function _set_reg_event()
3107
+	{
3108
+		if (is_object($this->_reg_event)) {
3109
+			return true;
3110
+		}
3111
+		$EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
3112
+		if (! $EVT_ID) {
3113
+			return false;
3114
+		}
3115
+		$this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
3116
+		return true;
3117
+	}
3118
+
3119
+
3120
+	/**
3121
+	 * process_reg_step
3122
+	 *
3123
+	 * @access        public
3124
+	 * @return string
3125
+	 * @throws DomainException
3126
+	 * @throws EE_Error
3127
+	 * @throws InvalidArgumentException
3128
+	 * @throws InvalidDataTypeException
3129
+	 * @throws InvalidInterfaceException
3130
+	 * @throws ReflectionException
3131
+	 * @throws RuntimeException
3132
+	 */
3133
+	public function process_reg_step()
3134
+	{
3135
+		EE_System::do_not_cache();
3136
+		$this->_set_reg_event();
3137
+		EE_Registry::instance()->REQ->set_espresso_page(true);
3138
+		EE_Registry::instance()->REQ->set('uts', time());
3139
+		// what step are we on?
3140
+		$cart = EE_Registry::instance()->SSN->cart();
3141
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3142
+		// if doing ajax then we need to verify the nonce
3143
+		if (defined('DOING_AJAX')) {
3144
+			$nonce = isset($this->_req_data[ $this->_req_nonce ])
3145
+				? sanitize_text_field($this->_req_data[ $this->_req_nonce ]) : '';
3146
+			$this->_verify_nonce($nonce, $this->_req_nonce);
3147
+		}
3148
+		switch ($step) {
3149
+			case 'ticket':
3150
+				// process ticket selection
3151
+				$success = EED_Ticket_Selector::instance()->process_ticket_selections();
3152
+				if ($success) {
3153
+					EE_Error::add_success(
3154
+						esc_html__(
3155
+							'Tickets Selected. Now complete the registration.',
3156
+							'event_espresso'
3157
+						)
3158
+					);
3159
+				} else {
3160
+					$query_args['step_error'] = $this->_req_data['step_error'] = true;
3161
+				}
3162
+				if (defined('DOING_AJAX')) {
3163
+					$this->new_registration(); // display next step
3164
+				} else {
3165
+					$query_args = array(
3166
+						'action'                  => 'new_registration',
3167
+						'processing_registration' => 1,
3168
+						'event_id'                => $this->_reg_event->ID(),
3169
+						'uts'                     => time(),
3170
+					);
3171
+					$this->_redirect_after_action(
3172
+						false,
3173
+						'',
3174
+						'',
3175
+						$query_args,
3176
+						true
3177
+					);
3178
+				}
3179
+				break;
3180
+			case 'questions':
3181
+				if (! isset(
3182
+					$this->_req_data['txn_reg_status_change'],
3183
+					$this->_req_data['txn_reg_status_change']['send_notifications']
3184
+				)
3185
+				) {
3186
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
3187
+				}
3188
+				// process registration
3189
+				$transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
3190
+				if ($cart instanceof EE_Cart) {
3191
+					$grand_total = $cart->get_cart_grand_total();
3192
+					if ($grand_total instanceof EE_Line_Item) {
3193
+						$grand_total->save_this_and_descendants_to_txn();
3194
+					}
3195
+				}
3196
+				if (! $transaction instanceof EE_Transaction) {
3197
+					$query_args = array(
3198
+						'action'                  => 'new_registration',
3199
+						'processing_registration' => 2,
3200
+						'event_id'                => $this->_reg_event->ID(),
3201
+						'uts'                     => time(),
3202
+					);
3203
+					if (defined('DOING_AJAX')) {
3204
+						// display registration form again because there are errors (maybe validation?)
3205
+						$this->new_registration();
3206
+						return;
3207
+					} else {
3208
+						$this->_redirect_after_action(
3209
+							false,
3210
+							'',
3211
+							'',
3212
+							$query_args,
3213
+							true
3214
+						);
3215
+						return;
3216
+					}
3217
+				}
3218
+				// maybe update status, and make sure to save transaction if not done already
3219
+				if (! $transaction->update_status_based_on_total_paid()) {
3220
+					$transaction->save();
3221
+				}
3222
+				EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3223
+				$this->_req_data = array();
3224
+				$query_args = array(
3225
+					'action'        => 'redirect_to_txn',
3226
+					'TXN_ID'        => $transaction->ID(),
3227
+					'EVT_ID'        => $this->_reg_event->ID(),
3228
+					'event_name'    => urlencode($this->_reg_event->name()),
3229
+					'redirect_from' => 'new_registration',
3230
+				);
3231
+				$this->_redirect_after_action(false, '', '', $query_args, true);
3232
+				break;
3233
+		}
3234
+		// what are you looking here for?  Should be nothing to do at this point.
3235
+	}
3236
+
3237
+
3238
+	/**
3239
+	 * redirect_to_txn
3240
+	 *
3241
+	 * @access public
3242
+	 * @return void
3243
+	 * @throws EE_Error
3244
+	 * @throws InvalidArgumentException
3245
+	 * @throws InvalidDataTypeException
3246
+	 * @throws InvalidInterfaceException
3247
+	 */
3248
+	public function redirect_to_txn()
3249
+	{
3250
+		EE_System::do_not_cache();
3251
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
3252
+		$query_args = array(
3253
+			'action' => 'view_transaction',
3254
+			'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
3255
+			'page'   => 'espresso_transactions',
3256
+		);
3257
+		if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
3258
+			$query_args['EVT_ID'] = $this->_req_data['EVT_ID'];
3259
+			$query_args['event_name'] = urlencode($this->_req_data['event_name']);
3260
+			$query_args['redirect_from'] = $this->_req_data['redirect_from'];
3261
+		}
3262
+		EE_Error::add_success(
3263
+			esc_html__(
3264
+				'Registration Created.  Please review the transaction and add any payments as necessary',
3265
+				'event_espresso'
3266
+			)
3267
+		);
3268
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3269
+	}
3270
+
3271
+
3272
+	/**
3273
+	 *        generates HTML for the Attendee Contact List
3274
+	 *
3275
+	 * @access protected
3276
+	 * @return void
3277
+	 */
3278
+	protected function _attendee_contact_list_table()
3279
+	{
3280
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3281
+		$this->_search_btn_label = esc_html__('Contacts', 'event_espresso');
3282
+		$this->display_admin_list_table_page_with_no_sidebar();
3283
+	}
3284
+
3285
+
3286
+	/**
3287
+	 *        get_attendees
3288
+	 *
3289
+	 * @param      $per_page
3290
+	 * @param bool $count whether to return count or data.
3291
+	 * @param bool $trash
3292
+	 * @return array
3293
+	 * @throws EE_Error
3294
+	 * @throws InvalidArgumentException
3295
+	 * @throws InvalidDataTypeException
3296
+	 * @throws InvalidInterfaceException
3297
+	 * @access public
3298
+	 */
3299
+	public function get_attendees($per_page, $count = false, $trash = false)
3300
+	{
3301
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3302
+		require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3303
+		$ATT_MDL = EEM_Attendee::instance();
3304
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3305
+		switch ($this->_req_data['orderby']) {
3306
+			case 'ATT_ID':
3307
+				$orderby = 'ATT_ID';
3308
+				break;
3309
+			case 'ATT_fname':
3310
+				$orderby = 'ATT_fname';
3311
+				break;
3312
+			case 'ATT_email':
3313
+				$orderby = 'ATT_email';
3314
+				break;
3315
+			case 'ATT_city':
3316
+				$orderby = 'ATT_city';
3317
+				break;
3318
+			case 'STA_ID':
3319
+				$orderby = 'STA_ID';
3320
+				break;
3321
+			case 'CNT_ID':
3322
+				$orderby = 'CNT_ID';
3323
+				break;
3324
+			case 'Registration_Count':
3325
+				$orderby = 'Registration_Count';
3326
+				break;
3327
+			default:
3328
+				$orderby = 'ATT_lname';
3329
+		}
3330
+		$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
3331
+			? $this->_req_data['order']
3332
+			: 'ASC';
3333
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
3334
+			? $this->_req_data['paged']
3335
+			: 1;
3336
+		$per_page = isset($per_page) && ! empty($per_page) ? $per_page : 10;
3337
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
3338
+			? $this->_req_data['perpage']
3339
+			: $per_page;
3340
+		$_where = array();
3341
+		if (! empty($this->_req_data['s'])) {
3342
+			$sstr = '%' . $this->_req_data['s'] . '%';
3343
+			$_where['OR'] = array(
3344
+				'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3345
+				'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
3346
+				'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
3347
+				'ATT_fname'                         => array('LIKE', $sstr),
3348
+				'ATT_lname'                         => array('LIKE', $sstr),
3349
+				'ATT_short_bio'                     => array('LIKE', $sstr),
3350
+				'ATT_email'                         => array('LIKE', $sstr),
3351
+				'ATT_address'                       => array('LIKE', $sstr),
3352
+				'ATT_address2'                      => array('LIKE', $sstr),
3353
+				'ATT_city'                          => array('LIKE', $sstr),
3354
+				'Country.CNT_name'                  => array('LIKE', $sstr),
3355
+				'State.STA_name'                    => array('LIKE', $sstr),
3356
+				'ATT_phone'                         => array('LIKE', $sstr),
3357
+				'Registration.REG_final_price'      => array('LIKE', $sstr),
3358
+				'Registration.REG_code'             => array('LIKE', $sstr),
3359
+				'Registration.REG_group_size'       => array('LIKE', $sstr),
3360
+			);
3361
+		}
3362
+		$offset = ($current_page - 1) * $per_page;
3363
+		$limit = $count ? null : array($offset, $per_page);
3364
+		$query_args = array(
3365
+			$_where,
3366
+			'extra_selects' => array('Registration_Count' => array('Registration.REG_ID', 'count', '%d')),
3367
+			'limit'         => $limit,
3368
+		);
3369
+		if (! $count) {
3370
+			$query_args['order_by'] = array($orderby => $sort);
3371
+		}
3372
+		if ($trash) {
3373
+			$query_args[0]['status'] = array('!=', 'publish');
3374
+			$all_attendees = $count
3375
+				? $ATT_MDL->count($query_args, 'ATT_ID', true)
3376
+				: $ATT_MDL->get_all($query_args);
3377
+		} else {
3378
+			$query_args[0]['status'] = array('IN', array('publish'));
3379
+			$all_attendees = $count
3380
+				? $ATT_MDL->count($query_args, 'ATT_ID', true)
3381
+				: $ATT_MDL->get_all($query_args);
3382
+		}
3383
+		return $all_attendees;
3384
+	}
3385
+
3386
+
3387
+	/**
3388
+	 * This is just taking care of resending the registration confirmation
3389
+	 *
3390
+	 * @access protected
3391
+	 * @return void
3392
+	 */
3393
+	protected function _resend_registration()
3394
+	{
3395
+		$this->_process_resend_registration();
3396
+		$query_args = isset($this->_req_data['redirect_to'])
3397
+			? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
3398
+			: array('action' => 'default');
3399
+		$this->_redirect_after_action(false, '', '', $query_args, true);
3400
+	}
3401
+
3402
+	/**
3403
+	 * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
3404
+	 * to use when selecting registrations
3405
+	 *
3406
+	 * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
3407
+	 *                                                     the query parameters from the request
3408
+	 * @return void ends the request with a redirect or download
3409
+	 */
3410
+	public function _registrations_report_base($method_name_for_getting_query_params)
3411
+	{
3412
+		if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3413
+			wp_redirect(
3414
+				EE_Admin_Page::add_query_args_and_nonce(
3415
+					array(
3416
+						'page'        => 'espresso_batch',
3417
+						'batch'       => 'file',
3418
+						'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3419
+						'filters'     => urlencode(
3420
+							serialize(
3421
+								call_user_func(
3422
+									array($this, $method_name_for_getting_query_params),
3423
+									EEH_Array::is_set(
3424
+										$this->_req_data,
3425
+										'filters',
3426
+										array()
3427
+									)
3428
+								)
3429
+							)
3430
+						),
3431
+						'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
3432
+						'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
3433
+						'return_url'  => urlencode($this->_req_data['return_url']),
3434
+					)
3435
+				)
3436
+			);
3437
+		} else {
3438
+			$new_request_args = array(
3439
+				'export' => 'report',
3440
+				'action' => 'registrations_report_for_event',
3441
+				'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3442
+			);
3443
+			$this->_req_data = array_merge($this->_req_data, $new_request_args);
3444
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3445
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3446
+				$EE_Export = EE_Export::instance($this->_req_data);
3447
+				$EE_Export->export();
3448
+			}
3449
+		}
3450
+	}
3451
+
3452
+
3453
+	/**
3454
+	 * Creates a registration report using only query parameters in the request
3455
+	 *
3456
+	 * @return void
3457
+	 */
3458
+	public function _registrations_report()
3459
+	{
3460
+		$this->_registrations_report_base('_get_registration_query_parameters');
3461
+	}
3462
+
3463
+
3464
+	public function _contact_list_export()
3465
+	{
3466
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3467
+			require_once(EE_CLASSES . 'EE_Export.class.php');
3468
+			$EE_Export = EE_Export::instance($this->_req_data);
3469
+			$EE_Export->export_attendees();
3470
+		}
3471
+	}
3472
+
3473
+
3474
+	public function _contact_list_report()
3475
+	{
3476
+		if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3477
+			wp_redirect(
3478
+				EE_Admin_Page::add_query_args_and_nonce(
3479
+					array(
3480
+						'page'        => 'espresso_batch',
3481
+						'batch'       => 'file',
3482
+						'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
3483
+						'return_url'  => urlencode($this->_req_data['return_url']),
3484
+					)
3485
+				)
3486
+			);
3487
+		} else {
3488
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3489
+				require_once(EE_CLASSES . 'EE_Export.class.php');
3490
+				$EE_Export = EE_Export::instance($this->_req_data);
3491
+				$EE_Export->report_attendees();
3492
+			}
3493
+		}
3494
+	}
3495
+
3496
+
3497
+
3498
+
3499
+
3500
+	/***************************************        ATTENDEE DETAILS        ***************************************/
3501
+	/**
3502
+	 * This duplicates the attendee object for the given incoming registration id and attendee_id.
3503
+	 *
3504
+	 * @return void
3505
+	 * @throws EE_Error
3506
+	 * @throws InvalidArgumentException
3507
+	 * @throws InvalidDataTypeException
3508
+	 * @throws InvalidInterfaceException
3509
+	 */
3510
+	protected function _duplicate_attendee()
3511
+	{
3512
+		$action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
3513
+		// verify we have necessary info
3514
+		if (empty($this->_req_data['_REG_ID'])) {
3515
+			EE_Error::add_error(
3516
+				esc_html__(
3517
+					'Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
3518
+					'event_espresso'
3519
+				),
3520
+				__FILE__,
3521
+				__LINE__,
3522
+				__FUNCTION__
3523
+			);
3524
+			$query_args = array('action' => $action);
3525
+			$this->_redirect_after_action('', '', '', $query_args, true);
3526
+		}
3527
+		// okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
3528
+		$registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
3529
+		$attendee = $registration->attendee();
3530
+		// remove relation of existing attendee on registration
3531
+		$registration->_remove_relation_to($attendee, 'Attendee');
3532
+		// new attendee
3533
+		$new_attendee = clone $attendee;
3534
+		$new_attendee->set('ATT_ID', 0);
3535
+		$new_attendee->save();
3536
+		// add new attendee to reg
3537
+		$registration->_add_relation_to($new_attendee, 'Attendee');
3538
+		EE_Error::add_success(
3539
+			esc_html__(
3540
+				'New Contact record created.  Now make any edits you wish to make for this contact.',
3541
+				'event_espresso'
3542
+			)
3543
+		);
3544
+		// redirect to edit page for attendee
3545
+		$query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
3546
+		$this->_redirect_after_action('', '', '', $query_args, true);
3547
+	}
3548
+
3549
+
3550
+	/**
3551
+	 * Callback invoked by parent EE_Admin_CPT class hooked in on `save_post` wp hook.
3552
+	 *
3553
+	 * @param int     $post_id
3554
+	 * @param WP_POST $post
3555
+	 * @throws DomainException
3556
+	 * @throws EE_Error
3557
+	 * @throws InvalidArgumentException
3558
+	 * @throws InvalidDataTypeException
3559
+	 * @throws InvalidInterfaceException
3560
+	 * @throws LogicException
3561
+	 * @throws InvalidFormSubmissionException
3562
+	 */
3563
+	protected function _insert_update_cpt_item($post_id, $post)
3564
+	{
3565
+		$success = true;
3566
+		$attendee = $post instanceof WP_Post && $post->post_type === 'espresso_attendees'
3567
+			? EEM_Attendee::instance()->get_one_by_ID($post_id)
3568
+			: null;
3569
+		// for attendee updates
3570
+		if ($attendee instanceof EE_Attendee) {
3571
+			// note we should only be UPDATING attendees at this point.
3572
+			$updated_fields = array(
3573
+				'ATT_fname'     => $this->_req_data['ATT_fname'],
3574
+				'ATT_lname'     => $this->_req_data['ATT_lname'],
3575
+				'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3576
+				'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3577
+				'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3578
+				'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
3579
+				'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
3580
+				'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
3581
+				'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
3582
+			);
3583
+			foreach ($updated_fields as $field => $value) {
3584
+				$attendee->set($field, $value);
3585
+			}
3586
+
3587
+			// process contact details metabox form handler (which will also save the attendee)
3588
+			$contact_details_form = $this->getAttendeeContactDetailsMetaboxFormHandler($attendee);
3589
+			$success = $contact_details_form->process($this->_req_data);
3590
+
3591
+			$attendee_update_callbacks = apply_filters(
3592
+				'FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
3593
+				array()
3594
+			);
3595
+			foreach ($attendee_update_callbacks as $a_callback) {
3596
+				if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
3597
+					throw new EE_Error(
3598
+						sprintf(
3599
+							esc_html__(
3600
+								'The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
3601
+								'event_espresso'
3602
+							),
3603
+							$a_callback
3604
+						)
3605
+					);
3606
+				}
3607
+			}
3608
+		}
3609
+
3610
+		if ($success === false) {
3611
+			EE_Error::add_error(
3612
+				esc_html__(
3613
+					'Something went wrong with updating the meta table data for the registration.',
3614
+					'event_espresso'
3615
+				),
3616
+				__FILE__,
3617
+				__FUNCTION__,
3618
+				__LINE__
3619
+			);
3620
+		}
3621
+	}
3622
+
3623
+
3624
+	public function trash_cpt_item($post_id)
3625
+	{
3626
+	}
3627
+
3628
+
3629
+	public function delete_cpt_item($post_id)
3630
+	{
3631
+	}
3632
+
3633
+
3634
+	public function restore_cpt_item($post_id)
3635
+	{
3636
+	}
3637
+
3638
+
3639
+	protected function _restore_cpt_item($post_id, $revision_id)
3640
+	{
3641
+	}
3642
+
3643
+
3644
+	public function attendee_editor_metaboxes()
3645
+	{
3646
+		$this->verify_cpt_object();
3647
+		remove_meta_box(
3648
+			'postexcerpt',
3649
+			esc_html__('Excerpt', 'event_espresso'),
3650
+			'post_excerpt_meta_box',
3651
+			$this->_cpt_routes[ $this->_req_action ],
3652
+			'normal',
3653
+			'core'
3654
+		);
3655
+		remove_meta_box('commentstatusdiv', $this->_cpt_routes[ $this->_req_action ], 'normal', 'core');
3656
+		if (post_type_supports('espresso_attendees', 'excerpt')) {
3657
+			add_meta_box(
3658
+				'postexcerpt',
3659
+				esc_html__('Short Biography', 'event_espresso'),
3660
+				'post_excerpt_meta_box',
3661
+				$this->_cpt_routes[ $this->_req_action ],
3662
+				'normal'
3663
+			);
3664
+		}
3665
+		if (post_type_supports('espresso_attendees', 'comments')) {
3666
+			add_meta_box(
3667
+				'commentsdiv',
3668
+				esc_html__('Notes on the Contact', 'event_espresso'),
3669
+				'post_comment_meta_box',
3670
+				$this->_cpt_routes[ $this->_req_action ],
3671
+				'normal',
3672
+				'core'
3673
+			);
3674
+		}
3675
+		add_meta_box(
3676
+			'attendee_contact_info',
3677
+			esc_html__('Contact Info', 'event_espresso'),
3678
+			array($this, 'attendee_contact_info'),
3679
+			$this->_cpt_routes[ $this->_req_action ],
3680
+			'side',
3681
+			'core'
3682
+		);
3683
+		add_meta_box(
3684
+			'attendee_details_address',
3685
+			esc_html__('Address Details', 'event_espresso'),
3686
+			array($this, 'attendee_address_details'),
3687
+			$this->_cpt_routes[ $this->_req_action ],
3688
+			'normal',
3689
+			'core'
3690
+		);
3691
+		add_meta_box(
3692
+			'attendee_registrations',
3693
+			esc_html__('Registrations for this Contact', 'event_espresso'),
3694
+			array($this, 'attendee_registrations_meta_box'),
3695
+			$this->_cpt_routes[ $this->_req_action ],
3696
+			'normal',
3697
+			'high'
3698
+		);
3699
+	}
3700
+
3701
+
3702
+	/**
3703
+	 * Metabox for attendee contact info
3704
+	 *
3705
+	 * @param  WP_Post $post wp post object
3706
+	 * @return string attendee contact info ( and form )
3707
+	 * @throws EE_Error
3708
+	 * @throws InvalidArgumentException
3709
+	 * @throws InvalidDataTypeException
3710
+	 * @throws InvalidInterfaceException
3711
+	 * @throws LogicException
3712
+	 * @throws DomainException
3713
+	 */
3714
+	public function attendee_contact_info($post)
3715
+	{
3716
+		// get attendee object ( should already have it )
3717
+		$form = $this->getAttendeeContactDetailsMetaboxFormHandler($this->_cpt_model_obj);
3718
+		$form->enqueueStylesAndScripts();
3719
+		echo $form->display();
3720
+	}
3721
+
3722
+
3723
+	/**
3724
+	 * Return form handler for the contact details metabox
3725
+	 *
3726
+	 * @param EE_Attendee $attendee
3727
+	 * @return AttendeeContactDetailsMetaboxFormHandler
3728
+	 * @throws DomainException
3729
+	 * @throws InvalidArgumentException
3730
+	 * @throws InvalidDataTypeException
3731
+	 * @throws InvalidInterfaceException
3732
+	 */
3733
+	protected function getAttendeeContactDetailsMetaboxFormHandler(EE_Attendee $attendee)
3734
+	{
3735
+		return new AttendeeContactDetailsMetaboxFormHandler($attendee, EE_Registry::instance());
3736
+	}
3737
+
3738
+
3739
+	/**
3740
+	 * Metabox for attendee details
3741
+	 *
3742
+	 * @param  WP_Post $post wp post object
3743
+	 * @throws DomainException
3744
+	 */
3745
+	public function attendee_address_details($post)
3746
+	{
3747
+		// get attendee object (should already have it)
3748
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
3749
+		$this->_template_args['state_html'] = EEH_Form_Fields::generate_form_input(
3750
+			new EE_Question_Form_Input(
3751
+				EE_Question::new_instance(
3752
+					array(
3753
+						'QST_ID'           => 0,
3754
+						'QST_display_text' => esc_html__('State/Province', 'event_espresso'),
3755
+						'QST_system'       => 'admin-state',
3756
+					)
3757
+				),
3758
+				EE_Answer::new_instance(
3759
+					array(
3760
+						'ANS_ID'    => 0,
3761
+						'ANS_value' => $this->_cpt_model_obj->state_ID(),
3762
+					)
3763
+				),
3764
+				array(
3765
+					'input_id'       => 'STA_ID',
3766
+					'input_name'     => 'STA_ID',
3767
+					'input_prefix'   => '',
3768
+					'append_qstn_id' => false,
3769
+				)
3770
+			)
3771
+		);
3772
+		$this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(
3773
+			new EE_Question_Form_Input(
3774
+				EE_Question::new_instance(
3775
+					array(
3776
+						'QST_ID'           => 0,
3777
+						'QST_display_text' => esc_html__('Country', 'event_espresso'),
3778
+						'QST_system'       => 'admin-country',
3779
+					)
3780
+				),
3781
+				EE_Answer::new_instance(
3782
+					array(
3783
+						'ANS_ID'    => 0,
3784
+						'ANS_value' => $this->_cpt_model_obj->country_ID(),
3785
+					)
3786
+				),
3787
+				array(
3788
+					'input_id'       => 'CNT_ISO',
3789
+					'input_name'     => 'CNT_ISO',
3790
+					'input_prefix'   => '',
3791
+					'append_qstn_id' => false,
3792
+				)
3793
+			)
3794
+		);
3795
+		$template =
3796
+			REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3797
+		EEH_Template::display_template($template, $this->_template_args);
3798
+	}
3799
+
3800
+
3801
+	/**
3802
+	 *        _attendee_details
3803
+	 *
3804
+	 * @access protected
3805
+	 * @param $post
3806
+	 * @return void
3807
+	 * @throws DomainException
3808
+	 * @throws EE_Error
3809
+	 */
3810
+	public function attendee_registrations_meta_box($post)
3811
+	{
3812
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
3813
+		$this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3814
+		$template =
3815
+			REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3816
+		EEH_Template::display_template($template, $this->_template_args);
3817
+	}
3818
+
3819
+
3820
+	/**
3821
+	 * add in the form fields for the attendee edit
3822
+	 *
3823
+	 * @param  WP_Post $post wp post object
3824
+	 * @return string html for new form.
3825
+	 * @throws DomainException
3826
+	 */
3827
+	public function after_title_form_fields($post)
3828
+	{
3829
+		if ($post->post_type == 'espresso_attendees') {
3830
+			$template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3831
+			$template_args['attendee'] = $this->_cpt_model_obj;
3832
+			EEH_Template::display_template($template, $template_args);
3833
+		}
3834
+	}
3835
+
3836
+
3837
+	/**
3838
+	 *        _trash_or_restore_attendee
3839
+	 *
3840
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
3841
+	 * @return void
3842
+	 * @throws EE_Error
3843
+	 * @throws InvalidArgumentException
3844
+	 * @throws InvalidDataTypeException
3845
+	 * @throws InvalidInterfaceException
3846
+	 * @access protected
3847
+	 */
3848
+	protected function _trash_or_restore_attendees($trash = true)
3849
+	{
3850
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3851
+		$ATT_MDL = EEM_Attendee::instance();
3852
+		$success = 1;
3853
+		// Checkboxes
3854
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3855
+			// if array has more than one element than success message should be plural
3856
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3857
+			// cycle thru checkboxes
3858
+			while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3859
+				$updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3860
+					: $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3861
+				if (! $updated) {
3862
+					$success = 0;
3863
+				}
3864
+			}
3865
+		} else {
3866
+			// grab single id and delete
3867
+			$ATT_ID = absint($this->_req_data['ATT_ID']);
3868
+			// get attendee
3869
+			$att = $ATT_MDL->get_one_by_ID($ATT_ID);
3870
+			$updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3871
+			$updated = $att->save();
3872
+			if (! $updated) {
3873
+				$success = 0;
3874
+			}
3875
+		}
3876
+		$what = $success > 1
3877
+			? esc_html__('Contacts', 'event_espresso')
3878
+			: esc_html__('Contact', 'event_espresso');
3879
+		$action_desc = $trash
3880
+			? esc_html__('moved to the trash', 'event_espresso')
3881
+			: esc_html__('restored', 'event_espresso');
3882
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3883
+	}
3884 3884
 }
Please login to merge, or discard this patch.
Spacing   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
         // when adding a new registration...
66 66
         if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
67 67
             EE_System::do_not_cache();
68
-            if (! isset($this->_req_data['processing_registration'])
68
+            if ( ! isset($this->_req_data['processing_registration'])
69 69
                 || absint($this->_req_data['processing_registration']) !== 1
70 70
             ) {
71 71
                 // and it's NOT the attendee information reg step
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
         // style
659 659
         wp_register_style(
660 660
             'espresso_reg',
661
-            REG_ASSETS_URL . 'espresso_registrations_admin.css',
661
+            REG_ASSETS_URL.'espresso_registrations_admin.css',
662 662
             array('ee-admin-css'),
663 663
             EVENT_ESPRESSO_VERSION
664 664
         );
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
         // script
667 667
         wp_register_script(
668 668
             'espresso_reg',
669
-            REG_ASSETS_URL . 'espresso_registrations_admin.js',
669
+            REG_ASSETS_URL.'espresso_registrations_admin.js',
670 670
             array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'),
671 671
             EVENT_ESPRESSO_VERSION,
672 672
             true
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
         wp_dequeue_style('espresso_reg');
705 705
         wp_register_style(
706 706
             'espresso_att',
707
-            REG_ASSETS_URL . 'espresso_attendees_admin.css',
707
+            REG_ASSETS_URL.'espresso_attendees_admin.css',
708 708
             array('ee-admin-css'),
709 709
             EVENT_ESPRESSO_VERSION
710 710
         );
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
     {
717 717
         wp_register_script(
718 718
             'ee-spco-for-admin',
719
-            REG_ASSETS_URL . 'spco_for_admin.js',
719
+            REG_ASSETS_URL.'spco_for_admin.js',
720 720
             array('underscore', 'jquery'),
721 721
             EVENT_ESPRESSO_VERSION,
722 722
             true
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
         }
951 951
         $sc_items = array(
952 952
             'approved_status'   => array(
953
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
953
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_approved,
954 954
                 'desc'  => EEH_Template::pretty_status(
955 955
                     EEM_Registration::status_id_approved,
956 956
                     false,
@@ -958,7 +958,7 @@  discard block
 block discarded – undo
958 958
                 ),
959 959
             ),
960 960
             'pending_status'    => array(
961
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
961
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_pending_payment,
962 962
                 'desc'  => EEH_Template::pretty_status(
963 963
                     EEM_Registration::status_id_pending_payment,
964 964
                     false,
@@ -966,7 +966,7 @@  discard block
 block discarded – undo
966 966
                 ),
967 967
             ),
968 968
             'wait_list'         => array(
969
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
969
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_wait_list,
970 970
                 'desc'  => EEH_Template::pretty_status(
971 971
                     EEM_Registration::status_id_wait_list,
972 972
                     false,
@@ -974,7 +974,7 @@  discard block
 block discarded – undo
974 974
                 ),
975 975
             ),
976 976
             'incomplete_status' => array(
977
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
977
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_incomplete,
978 978
                 'desc'  => EEH_Template::pretty_status(
979 979
                     EEM_Registration::status_id_incomplete,
980 980
                     false,
@@ -982,7 +982,7 @@  discard block
 block discarded – undo
982 982
                 ),
983 983
             ),
984 984
             'not_approved'      => array(
985
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
985
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_not_approved,
986 986
                 'desc'  => EEH_Template::pretty_status(
987 987
                     EEM_Registration::status_id_not_approved,
988 988
                     false,
@@ -990,7 +990,7 @@  discard block
 block discarded – undo
990 990
                 ),
991 991
             ),
992 992
             'declined_status'   => array(
993
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
993
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_declined,
994 994
                 'desc'  => EEH_Template::pretty_status(
995 995
                     EEM_Registration::status_id_declined,
996 996
                     false,
@@ -998,7 +998,7 @@  discard block
 block discarded – undo
998 998
                 ),
999 999
             ),
1000 1000
             'cancelled_status'  => array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1001
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_cancelled,
1002 1002
                 'desc'  => EEH_Template::pretty_status(
1003 1003
                     EEM_Registration::status_id_cancelled,
1004 1004
                     false,
@@ -1033,13 +1033,13 @@  discard block
 block discarded – undo
1033 1033
                         'event_espresso'
1034 1034
                     ),
1035 1035
                     '<h3 style="line-height:1.5em;">',
1036
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
1036
+                    '<a href="'.EE_Admin_Page::add_query_args_and_nonce(
1037 1037
                         array(
1038 1038
                             'action' => 'edit_attendee',
1039 1039
                             'post'   => $ATT_ID,
1040 1040
                         ),
1041 1041
                         REG_ADMIN_URL
1042
-                    ) . '">' . $attendee->full_name() . '</a>',
1042
+                    ).'">'.$attendee->full_name().'</a>',
1043 1043
                     '</h3>'
1044 1044
                 );
1045 1045
             }
@@ -1050,7 +1050,7 @@  discard block
 block discarded – undo
1050 1050
                 'espresso_registrations_new_registration',
1051 1051
                 $EVT_ID
1052 1052
             )) {
1053
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
1053
+                $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
1054 1054
                     'new_registration',
1055 1055
                     'add-registrant',
1056 1056
                     array('event_id' => $EVT_ID),
@@ -1090,7 +1090,7 @@  discard block
 block discarded – undo
1090 1090
                 $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
1091 1091
                 $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
1092 1092
                 $this->_template_args['admin_page_header'] .= $datetime->name();
1093
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
1093
+                $this->_template_args['admin_page_header'] .= ' ( '.$datetime->start_date().' )';
1094 1094
                 $this->_template_args['admin_page_header'] .= '</span></h3>';
1095 1095
             }
1096 1096
         }
@@ -1116,7 +1116,7 @@  discard block
 block discarded – undo
1116 1116
             return true;
1117 1117
         }
1118 1118
         $REG = EEM_Registration::instance();
1119
-        $REG_ID = (! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1119
+        $REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
1120 1120
         if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
1121 1121
             return true;
1122 1122
         } else {
@@ -1200,7 +1200,7 @@  discard block
 block discarded – undo
1200 1200
             'caps'                     => EEM_Registration::caps_read_admin,
1201 1201
             'default_where_conditions' => 'this_model_only',
1202 1202
         );
1203
-        if (! $count) {
1203
+        if ( ! $count) {
1204 1204
             $query_params = array_merge(
1205 1205
                 $query_params,
1206 1206
                 $this->_get_orderby_for_registrations_query(),
@@ -1221,7 +1221,7 @@  discard block
 block discarded – undo
1221 1221
     protected function addAttendeeIdToWhereConditions(array $request)
1222 1222
     {
1223 1223
         $where = array();
1224
-        if (! empty($request['ATT_ID'])) {
1224
+        if ( ! empty($request['ATT_ID'])) {
1225 1225
             $where['ATT_ID'] = absint($request['ATT_ID']);
1226 1226
         }
1227 1227
         return $where;
@@ -1237,7 +1237,7 @@  discard block
 block discarded – undo
1237 1237
     protected function _add_event_id_to_where_conditions(array $request)
1238 1238
     {
1239 1239
         $where = array();
1240
-        if (! empty($request['event_id'])) {
1240
+        if ( ! empty($request['event_id'])) {
1241 1241
             $where['EVT_ID'] = absint($request['event_id']);
1242 1242
         }
1243 1243
         return $where;
@@ -1253,7 +1253,7 @@  discard block
 block discarded – undo
1253 1253
     protected function _add_category_id_to_where_conditions(array $request)
1254 1254
     {
1255 1255
         $where = array();
1256
-        if (! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
1256
+        if ( ! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
1257 1257
             $where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1258 1258
         }
1259 1259
         return $where;
@@ -1269,10 +1269,10 @@  discard block
 block discarded – undo
1269 1269
     protected function _add_datetime_id_to_where_conditions(array $request)
1270 1270
     {
1271 1271
         $where = array();
1272
-        if (! empty($request['datetime_id'])) {
1272
+        if ( ! empty($request['datetime_id'])) {
1273 1273
             $where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1274 1274
         }
1275
-        if (! empty($request['DTT_ID'])) {
1275
+        if ( ! empty($request['DTT_ID'])) {
1276 1276
             $where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1277 1277
         }
1278 1278
         return $where;
@@ -1298,7 +1298,7 @@  discard block
 block discarded – undo
1298 1298
          * If not filtering by specified status, then we show all registrations excluding incomplete registrations
1299 1299
          * UNLESS viewing trashed registrations.
1300 1300
          */
1301
-        if (! empty($registration_status)) {
1301
+        if ( ! empty($registration_status)) {
1302 1302
             $where['STS_ID'] = $registration_status;
1303 1303
         } else {
1304 1304
             // make sure we exclude incomplete registrations, but only if not trashed.
@@ -1341,12 +1341,12 @@  discard block
 block discarded – undo
1341 1341
                 array(
1342 1342
                     EEM_Registration::instance()->convert_datetime_for_query(
1343 1343
                         'REG_date',
1344
-                        $now . ' 00:00:00',
1344
+                        $now.' 00:00:00',
1345 1345
                         'Y-m-d H:i:s'
1346 1346
                     ),
1347 1347
                     EEM_Registration::instance()->convert_datetime_for_query(
1348 1348
                         'REG_date',
1349
-                        $now . ' 23:59:59',
1349
+                        $now.' 23:59:59',
1350 1350
                         'Y-m-d H:i:s'
1351 1351
                     ),
1352 1352
                 ),
@@ -1359,12 +1359,12 @@  discard block
 block discarded – undo
1359 1359
                 array(
1360 1360
                     EEM_Registration::instance()->convert_datetime_for_query(
1361 1361
                         'REG_date',
1362
-                        $current_year_and_month . '-01 00:00:00',
1362
+                        $current_year_and_month.'-01 00:00:00',
1363 1363
                         'Y-m-d H:i:s'
1364 1364
                     ),
1365 1365
                     EEM_Registration::instance()->convert_datetime_for_query(
1366 1366
                         'REG_date',
1367
-                        $current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1367
+                        $current_year_and_month.'-'.$days_this_month.' 23:59:59',
1368 1368
                         'Y-m-d H:i:s'
1369 1369
                     ),
1370 1370
                 ),
@@ -1379,18 +1379,18 @@  discard block
 block discarded – undo
1379 1379
                 : '';
1380 1380
             // if there is not a month or year then we can't go further
1381 1381
             if ($month_requested && $year_requested) {
1382
-                $days_in_month = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1382
+                $days_in_month = date('t', strtotime($year_requested.'-'.$month_requested.'-'.'01'));
1383 1383
                 $where['REG_date'] = array(
1384 1384
                     'BETWEEN',
1385 1385
                     array(
1386 1386
                         EEM_Registration::instance()->convert_datetime_for_query(
1387 1387
                             'REG_date',
1388
-                            $year_requested . '-' . $month_requested . '-01 00:00:00',
1388
+                            $year_requested.'-'.$month_requested.'-01 00:00:00',
1389 1389
                             'Y-m-d H:i:s'
1390 1390
                         ),
1391 1391
                         EEM_Registration::instance()->convert_datetime_for_query(
1392 1392
                             'REG_date',
1393
-                            $year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1393
+                            $year_requested.'-'.$month_requested.'-'.$days_in_month.' 23:59:59',
1394 1394
                             'Y-m-d H:i:s'
1395 1395
                         ),
1396 1396
                     ),
@@ -1410,8 +1410,8 @@  discard block
 block discarded – undo
1410 1410
     protected function _add_search_to_where_conditions(array $request)
1411 1411
     {
1412 1412
         $where = array();
1413
-        if (! empty($request['s'])) {
1414
-            $search_string = '%' . sanitize_text_field($request['s']) . '%';
1413
+        if ( ! empty($request['s'])) {
1414
+            $search_string = '%'.sanitize_text_field($request['s']).'%';
1415 1415
             $where['OR*search_conditions'] = array(
1416 1416
                 'Event.EVT_name'                          => array('LIKE', $search_string),
1417 1417
                 'Event.EVT_desc'                          => array('LIKE', $search_string),
@@ -1647,7 +1647,7 @@  discard block
 block discarded – undo
1647 1647
                 )
1648 1648
                 : '';
1649 1649
             // grab header
1650
-            $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1650
+            $template_path = REG_TEMPLATE_PATH.'reg_admin_details_header.template.php';
1651 1651
             $this->_template_args['REG_ID'] = $this->_registration->ID();
1652 1652
             $this->_template_args['admin_page_header'] = EEH_Template::display_template(
1653 1653
                 $template_path,
@@ -1784,7 +1784,7 @@  discard block
 block discarded – undo
1784 1784
                             EEH_HTML::strong(
1785 1785
                                 $this->_registration->pretty_status(),
1786 1786
                                 '',
1787
-                                'status-' . $this->_registration->status_ID(),
1787
+                                'status-'.$this->_registration->status_ID(),
1788 1788
                                 'line-height: 1em; font-size: 1.5em; font-weight: bold;'
1789 1789
                             )
1790 1790
                         )
@@ -1839,14 +1839,14 @@  discard block
 block discarded – undo
1839 1839
     protected function _get_reg_statuses()
1840 1840
     {
1841 1841
         $reg_status_array = EEM_Registration::instance()->reg_status_array();
1842
-        unset($reg_status_array[ EEM_Registration::status_id_incomplete ]);
1842
+        unset($reg_status_array[EEM_Registration::status_id_incomplete]);
1843 1843
         // get current reg status
1844 1844
         $current_status = $this->_registration->status_ID();
1845 1845
         // is registration for free event? This will determine whether to display the pending payment option
1846 1846
         if ($current_status !== EEM_Registration::status_id_pending_payment
1847 1847
             && EEH_Money::compare_floats($this->_registration->ticket()->price(), 0.00)
1848 1848
         ) {
1849
-            unset($reg_status_array[ EEM_Registration::status_id_pending_payment ]);
1849
+            unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1850 1850
         }
1851 1851
         return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1852 1852
     }
@@ -1938,7 +1938,7 @@  discard block
 block discarded – undo
1938 1938
         $success = false;
1939 1939
         // typecast $REG_IDs
1940 1940
         $REG_IDs = (array) $REG_IDs;
1941
-        if (! empty($REG_IDs)) {
1941
+        if ( ! empty($REG_IDs)) {
1942 1942
             $success = true;
1943 1943
             // set default status if none is passed
1944 1944
             $status = $status ? $status : EEM_Registration::status_id_pending_payment;
@@ -2086,7 +2086,7 @@  discard block
 block discarded – undo
2086 2086
             $action,
2087 2087
             $notify
2088 2088
         );
2089
-        $method = $action . '_registration';
2089
+        $method = $action.'_registration';
2090 2090
         if (method_exists($this, $method)) {
2091 2091
             $this->$method($notify);
2092 2092
         }
@@ -2317,7 +2317,7 @@  discard block
 block discarded – undo
2317 2317
         $this->_template_args['REG_ID'] = $this->_registration->ID();
2318 2318
         $this->_template_args['event_id'] = $this->_registration->event_ID();
2319 2319
         $template_path =
2320
-            REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
2320
+            REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_reg_details.template.php';
2321 2321
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
2322 2322
     }
2323 2323
 
@@ -2350,7 +2350,7 @@  discard block
 block discarded – undo
2350 2350
             $this->_template_args['reg_questions_form_action'] = 'edit_registration';
2351 2351
             $this->_template_args['REG_ID'] = $this->_registration->ID();
2352 2352
             $template_path =
2353
-                REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
2353
+                REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_reg_questions.template.php';
2354 2354
             echo EEH_Template::display_template($template_path, $this->_template_args, true);
2355 2355
         }
2356 2356
     }
@@ -2367,7 +2367,7 @@  discard block
 block discarded – undo
2367 2367
     public function form_before_question_group($output)
2368 2368
     {
2369 2369
         EE_Error::doing_it_wrong(
2370
-            __CLASS__ . '::' . __FUNCTION__,
2370
+            __CLASS__.'::'.__FUNCTION__,
2371 2371
             esc_html__(
2372 2372
                 'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2373 2373
                 'event_espresso'
@@ -2392,7 +2392,7 @@  discard block
 block discarded – undo
2392 2392
     public function form_after_question_group($output)
2393 2393
     {
2394 2394
         EE_Error::doing_it_wrong(
2395
-            __CLASS__ . '::' . __FUNCTION__,
2395
+            __CLASS__.'::'.__FUNCTION__,
2396 2396
             esc_html__(
2397 2397
                 'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2398 2398
                 'event_espresso'
@@ -2430,7 +2430,7 @@  discard block
 block discarded – undo
2430 2430
     public function form_form_field_label_wrap($label)
2431 2431
     {
2432 2432
         EE_Error::doing_it_wrong(
2433
-            __CLASS__ . '::' . __FUNCTION__,
2433
+            __CLASS__.'::'.__FUNCTION__,
2434 2434
             esc_html__(
2435 2435
                 'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2436 2436
                 'event_espresso'
@@ -2440,7 +2440,7 @@  discard block
 block discarded – undo
2440 2440
         return '
2441 2441
 			<tr>
2442 2442
 				<th>
2443
-					' . $label . '
2443
+					' . $label.'
2444 2444
 				</th>';
2445 2445
     }
2446 2446
 
@@ -2456,7 +2456,7 @@  discard block
 block discarded – undo
2456 2456
     public function form_form_field_input__wrap($input)
2457 2457
     {
2458 2458
         EE_Error::doing_it_wrong(
2459
-            __CLASS__ . '::' . __FUNCTION__,
2459
+            __CLASS__.'::'.__FUNCTION__,
2460 2460
             esc_html__(
2461 2461
                 'This method would have been protected but was used on a filter callback so needed to be public. Please discontinue usage as it will be removed soon.',
2462 2462
                 'event_espresso'
@@ -2465,7 +2465,7 @@  discard block
 block discarded – undo
2465 2465
         );
2466 2466
         return '
2467 2467
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
2468
-					' . $input . '
2468
+					' . $input.'
2469 2469
 				</td>
2470 2470
 			</tr>';
2471 2471
     }
@@ -2509,8 +2509,8 @@  discard block
 block discarded – undo
2509 2509
      */
2510 2510
     protected function _get_reg_custom_questions_form($REG_ID)
2511 2511
     {
2512
-        if (! $this->_reg_custom_questions_form) {
2513
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
2512
+        if ( ! $this->_reg_custom_questions_form) {
2513
+            require_once(REG_ADMIN.'form_sections'.DS.'EE_Registration_Custom_Questions_Form.form.php');
2514 2514
             $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(
2515 2515
                 EEM_Registration::instance()->get_one_by_ID($REG_ID)
2516 2516
             );
@@ -2533,7 +2533,7 @@  discard block
 block discarded – undo
2533 2533
      */
2534 2534
     private function _save_reg_custom_questions_form($REG_ID = false)
2535 2535
     {
2536
-        if (! $REG_ID) {
2536
+        if ( ! $REG_ID) {
2537 2537
             EE_Error::add_error(
2538 2538
                 esc_html__(
2539 2539
                     'An error occurred. No registration ID was received.',
@@ -2624,30 +2624,30 @@  discard block
 block discarded – undo
2624 2624
                     ? $registration->attendee()
2625 2625
                     : EEM_Attendee::instance()
2626 2626
                                   ->create_default_object();
2627
-                $this->_template_args['attendees'][ $att_nmbr ]['STS_ID'] = $registration->status_ID();
2628
-                $this->_template_args['attendees'][ $att_nmbr ]['fname'] = $attendee->fname();
2629
-                $this->_template_args['attendees'][ $att_nmbr ]['lname'] = $attendee->lname();
2630
-                $this->_template_args['attendees'][ $att_nmbr ]['email'] = $attendee->email();
2631
-                $this->_template_args['attendees'][ $att_nmbr ]['final_price'] = $registration->final_price();
2632
-                $this->_template_args['attendees'][ $att_nmbr ]['address'] = implode(
2627
+                $this->_template_args['attendees'][$att_nmbr]['STS_ID'] = $registration->status_ID();
2628
+                $this->_template_args['attendees'][$att_nmbr]['fname'] = $attendee->fname();
2629
+                $this->_template_args['attendees'][$att_nmbr]['lname'] = $attendee->lname();
2630
+                $this->_template_args['attendees'][$att_nmbr]['email'] = $attendee->email();
2631
+                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();
2632
+                $this->_template_args['attendees'][$att_nmbr]['address'] = implode(
2633 2633
                     ', ',
2634 2634
                     $attendee->full_address_as_array()
2635 2635
                 );
2636
-                $this->_template_args['attendees'][ $att_nmbr ]['att_link'] = self::add_query_args_and_nonce(
2636
+                $this->_template_args['attendees'][$att_nmbr]['att_link'] = self::add_query_args_and_nonce(
2637 2637
                     array(
2638 2638
                         'action' => 'edit_attendee',
2639 2639
                         'post'   => $attendee->ID(),
2640 2640
                     ),
2641 2641
                     REG_ADMIN_URL
2642 2642
                 );
2643
-                $this->_template_args['attendees'][ $att_nmbr ]['event_name'] = $registration->event_obj() instanceof EE_Event
2643
+                $this->_template_args['attendees'][$att_nmbr]['event_name'] = $registration->event_obj() instanceof EE_Event
2644 2644
                     ? $registration->event_obj()->name()
2645 2645
                     : '';
2646 2646
                 $att_nmbr++;
2647 2647
             }
2648 2648
             $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2649 2649
         }
2650
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2650
+        $template_path = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_attendees.template.php';
2651 2651
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
2652 2652
     }
2653 2653
 
@@ -2671,11 +2671,11 @@  discard block
 block discarded – undo
2671 2671
         // now let's determine if this is not the primary registration.  If it isn't then we set the
2672 2672
         // primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the
2673 2673
         // primary registration object (that way we know if we need to show create button or not)
2674
-        if (! $this->_registration->is_primary_registrant()) {
2674
+        if ( ! $this->_registration->is_primary_registrant()) {
2675 2675
             $primary_registration = $this->_registration->get_primary_registration();
2676 2676
             $primary_attendee = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2677 2677
                 : null;
2678
-            if (! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2678
+            if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2679 2679
                 // in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own
2680 2680
                 // custom attendee object so let's not worry about the primary reg.
2681 2681
                 $primary_registration = null;
@@ -2709,7 +2709,7 @@  discard block
 block discarded – undo
2709 2709
             ) : '';
2710 2710
         $this->_template_args['create_label'] = esc_html__('Create Contact', 'event_espresso');
2711 2711
         $this->_template_args['att_check'] = $att_check;
2712
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2712
+        $template_path = REG_TEMPLATE_PATH.'reg_admin_details_side_meta_box_registrant.template.php';
2713 2713
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
2714 2714
     }
2715 2715
 
@@ -2747,7 +2747,7 @@  discard block
 block discarded – undo
2747 2747
         $success = 0;
2748 2748
         $overwrite_msgs = false;
2749 2749
         // Checkboxes
2750
-        if (! is_array($this->_req_data['_REG_ID'])) {
2750
+        if ( ! is_array($this->_req_data['_REG_ID'])) {
2751 2751
             $this->_req_data['_REG_ID'] = array($this->_req_data['_REG_ID']);
2752 2752
         }
2753 2753
         $reg_count = count($this->_req_data['_REG_ID']);
@@ -2756,7 +2756,7 @@  discard block
 block discarded – undo
2756 2756
             /** @var EE_Registration $REG */
2757 2757
             $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
2758 2758
             $payments = $REG->registration_payments();
2759
-            if (! empty($payments)) {
2759
+            if ( ! empty($payments)) {
2760 2760
                 $name = $REG->attendee() instanceof EE_Attendee
2761 2761
                     ? $REG->attendee()->full_name()
2762 2762
                     : esc_html__('Unknown Attendee', 'event_espresso');
@@ -2817,17 +2817,17 @@  discard block
 block discarded – undo
2817 2817
         $REG_MDL = EEM_Registration::instance();
2818 2818
         $success = 1;
2819 2819
         // Checkboxes
2820
-        if (! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2820
+        if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2821 2821
             // if array has more than one element than success message should be plural
2822 2822
             $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2823 2823
             // cycle thru checkboxes
2824 2824
             while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2825 2825
                 $REG = $REG_MDL->get_one_by_ID($REG_ID);
2826
-                if (! $REG instanceof EE_Registration) {
2826
+                if ( ! $REG instanceof EE_Registration) {
2827 2827
                     continue;
2828 2828
                 }
2829 2829
                 $deleted = $this->_delete_registration($REG);
2830
-                if (! $deleted) {
2830
+                if ( ! $deleted) {
2831 2831
                     $success = 0;
2832 2832
                 }
2833 2833
             }
@@ -2836,7 +2836,7 @@  discard block
 block discarded – undo
2836 2836
             $REG_ID = $this->_req_data['_REG_ID'];
2837 2837
             $REG = $REG_MDL->get_one_by_ID($REG_ID);
2838 2838
             $deleted = $this->_delete_registration($REG);
2839
-            if (! $deleted) {
2839
+            if ( ! $deleted) {
2840 2840
                 $success = 0;
2841 2841
             }
2842 2842
         }
@@ -2870,11 +2870,11 @@  discard block
 block discarded – undo
2870 2870
         $REGS = $TXN->get_many_related('Registration');
2871 2871
         $all_trashed = true;
2872 2872
         foreach ($REGS as $registration) {
2873
-            if (! $registration->get('REG_deleted')) {
2873
+            if ( ! $registration->get('REG_deleted')) {
2874 2874
                 $all_trashed = false;
2875 2875
             }
2876 2876
         }
2877
-        if (! $all_trashed) {
2877
+        if ( ! $all_trashed) {
2878 2878
             EE_Error::add_error(
2879 2879
                 esc_html__(
2880 2880
                     'Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
@@ -2933,7 +2933,7 @@  discard block
 block discarded – undo
2933 2933
      */
2934 2934
     public function new_registration()
2935 2935
     {
2936
-        if (! $this->_set_reg_event()) {
2936
+        if ( ! $this->_set_reg_event()) {
2937 2937
             throw new EE_Error(
2938 2938
                 esc_html__(
2939 2939
                     'Unable to continue with registering because there is no Event ID in the request',
@@ -2943,8 +2943,8 @@  discard block
 block discarded – undo
2943 2943
         }
2944 2944
         EE_Registry::instance()->REQ->set_espresso_page(true);
2945 2945
         // gotta start with a clean slate if we're not coming here via ajax
2946
-        if (! defined('DOING_AJAX')
2947
-            && (! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2946
+        if ( ! defined('DOING_AJAX')
2947
+            && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2948 2948
         ) {
2949 2949
             EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2950 2950
         }
@@ -2977,7 +2977,7 @@  discard block
 block discarded – undo
2977 2977
         }
2978 2978
         // grab header
2979 2979
         $template_path =
2980
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2980
+            REG_TEMPLATE_PATH.'reg_admin_register_new_attendee.template.php';
2981 2981
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2982 2982
             $template_path,
2983 2983
             $this->_template_args,
@@ -3018,7 +3018,7 @@  discard block
 block discarded – undo
3018 3018
                 '</b>'
3019 3019
             );
3020 3020
             return '
3021
-	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
3021
+	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg.'</p></div>
3022 3022
 	<script >
3023 3023
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
3024 3024
 		// after just adding a new registration... we gotta try to put a stop to that !!!
@@ -3086,7 +3086,7 @@  discard block
 block discarded – undo
3086 3086
         // we come back to the process_registration_step route.
3087 3087
         $this->_set_add_edit_form_tags('process_reg_step', $hidden_fields);
3088 3088
         return EEH_Template::display_template(
3089
-            REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee_step_content.template.php',
3089
+            REG_TEMPLATE_PATH.'reg_admin_register_new_attendee_step_content.template.php',
3090 3090
             $template_args,
3091 3091
             true
3092 3092
         );
@@ -3108,8 +3108,8 @@  discard block
 block discarded – undo
3108 3108
         if (is_object($this->_reg_event)) {
3109 3109
             return true;
3110 3110
         }
3111
-        $EVT_ID = (! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
3112
-        if (! $EVT_ID) {
3111
+        $EVT_ID = ( ! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
3112
+        if ( ! $EVT_ID) {
3113 3113
             return false;
3114 3114
         }
3115 3115
         $this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
@@ -3141,8 +3141,8 @@  discard block
 block discarded – undo
3141 3141
         $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
3142 3142
         // if doing ajax then we need to verify the nonce
3143 3143
         if (defined('DOING_AJAX')) {
3144
-            $nonce = isset($this->_req_data[ $this->_req_nonce ])
3145
-                ? sanitize_text_field($this->_req_data[ $this->_req_nonce ]) : '';
3144
+            $nonce = isset($this->_req_data[$this->_req_nonce])
3145
+                ? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
3146 3146
             $this->_verify_nonce($nonce, $this->_req_nonce);
3147 3147
         }
3148 3148
         switch ($step) {
@@ -3178,7 +3178,7 @@  discard block
 block discarded – undo
3178 3178
                 }
3179 3179
                 break;
3180 3180
             case 'questions':
3181
-                if (! isset(
3181
+                if ( ! isset(
3182 3182
                     $this->_req_data['txn_reg_status_change'],
3183 3183
                     $this->_req_data['txn_reg_status_change']['send_notifications']
3184 3184
                 )
@@ -3193,7 +3193,7 @@  discard block
 block discarded – undo
3193 3193
                         $grand_total->save_this_and_descendants_to_txn();
3194 3194
                     }
3195 3195
                 }
3196
-                if (! $transaction instanceof EE_Transaction) {
3196
+                if ( ! $transaction instanceof EE_Transaction) {
3197 3197
                     $query_args = array(
3198 3198
                         'action'                  => 'new_registration',
3199 3199
                         'processing_registration' => 2,
@@ -3216,7 +3216,7 @@  discard block
 block discarded – undo
3216 3216
                     }
3217 3217
                 }
3218 3218
                 // maybe update status, and make sure to save transaction if not done already
3219
-                if (! $transaction->update_status_based_on_total_paid()) {
3219
+                if ( ! $transaction->update_status_based_on_total_paid()) {
3220 3220
                     $transaction->save();
3221 3221
                 }
3222 3222
                 EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
@@ -3299,7 +3299,7 @@  discard block
 block discarded – undo
3299 3299
     public function get_attendees($per_page, $count = false, $trash = false)
3300 3300
     {
3301 3301
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3302
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
3302
+        require_once(REG_ADMIN.'EE_Attendee_Contact_List_Table.class.php');
3303 3303
         $ATT_MDL = EEM_Attendee::instance();
3304 3304
         $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
3305 3305
         switch ($this->_req_data['orderby']) {
@@ -3338,8 +3338,8 @@  discard block
 block discarded – undo
3338 3338
             ? $this->_req_data['perpage']
3339 3339
             : $per_page;
3340 3340
         $_where = array();
3341
-        if (! empty($this->_req_data['s'])) {
3342
-            $sstr = '%' . $this->_req_data['s'] . '%';
3341
+        if ( ! empty($this->_req_data['s'])) {
3342
+            $sstr = '%'.$this->_req_data['s'].'%';
3343 3343
             $_where['OR'] = array(
3344 3344
                 'Registration.Event.EVT_name'       => array('LIKE', $sstr),
3345 3345
                 'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
@@ -3366,7 +3366,7 @@  discard block
 block discarded – undo
3366 3366
             'extra_selects' => array('Registration_Count' => array('Registration.REG_ID', 'count', '%d')),
3367 3367
             'limit'         => $limit,
3368 3368
         );
3369
-        if (! $count) {
3369
+        if ( ! $count) {
3370 3370
             $query_args['order_by'] = array($orderby => $sort);
3371 3371
         }
3372 3372
         if ($trash) {
@@ -3409,7 +3409,7 @@  discard block
 block discarded – undo
3409 3409
      */
3410 3410
     public function _registrations_report_base($method_name_for_getting_query_params)
3411 3411
     {
3412
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3412
+        if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3413 3413
             wp_redirect(
3414 3414
                 EE_Admin_Page::add_query_args_and_nonce(
3415 3415
                     array(
@@ -3441,8 +3441,8 @@  discard block
 block discarded – undo
3441 3441
                 'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
3442 3442
             );
3443 3443
             $this->_req_data = array_merge($this->_req_data, $new_request_args);
3444
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3445
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3444
+            if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
3445
+                require_once(EE_CLASSES.'EE_Export.class.php');
3446 3446
                 $EE_Export = EE_Export::instance($this->_req_data);
3447 3447
                 $EE_Export->export();
3448 3448
             }
@@ -3463,8 +3463,8 @@  discard block
 block discarded – undo
3463 3463
 
3464 3464
     public function _contact_list_export()
3465 3465
     {
3466
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3467
-            require_once(EE_CLASSES . 'EE_Export.class.php');
3466
+        if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
3467
+            require_once(EE_CLASSES.'EE_Export.class.php');
3468 3468
             $EE_Export = EE_Export::instance($this->_req_data);
3469 3469
             $EE_Export->export_attendees();
3470 3470
         }
@@ -3473,7 +3473,7 @@  discard block
 block discarded – undo
3473 3473
 
3474 3474
     public function _contact_list_report()
3475 3475
     {
3476
-        if (! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3476
+        if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
3477 3477
             wp_redirect(
3478 3478
                 EE_Admin_Page::add_query_args_and_nonce(
3479 3479
                     array(
@@ -3485,8 +3485,8 @@  discard block
 block discarded – undo
3485 3485
                 )
3486 3486
             );
3487 3487
         } else {
3488
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
3489
-                require_once(EE_CLASSES . 'EE_Export.class.php');
3488
+            if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
3489
+                require_once(EE_CLASSES.'EE_Export.class.php');
3490 3490
                 $EE_Export = EE_Export::instance($this->_req_data);
3491 3491
                 $EE_Export->report_attendees();
3492 3492
             }
@@ -3572,7 +3572,7 @@  discard block
 block discarded – undo
3572 3572
             $updated_fields = array(
3573 3573
                 'ATT_fname'     => $this->_req_data['ATT_fname'],
3574 3574
                 'ATT_lname'     => $this->_req_data['ATT_lname'],
3575
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
3575
+                'ATT_full_name' => $this->_req_data['ATT_fname'].' '.$this->_req_data['ATT_lname'],
3576 3576
                 'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
3577 3577
                 'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
3578 3578
                 'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
@@ -3648,17 +3648,17 @@  discard block
 block discarded – undo
3648 3648
             'postexcerpt',
3649 3649
             esc_html__('Excerpt', 'event_espresso'),
3650 3650
             'post_excerpt_meta_box',
3651
-            $this->_cpt_routes[ $this->_req_action ],
3651
+            $this->_cpt_routes[$this->_req_action],
3652 3652
             'normal',
3653 3653
             'core'
3654 3654
         );
3655
-        remove_meta_box('commentstatusdiv', $this->_cpt_routes[ $this->_req_action ], 'normal', 'core');
3655
+        remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
3656 3656
         if (post_type_supports('espresso_attendees', 'excerpt')) {
3657 3657
             add_meta_box(
3658 3658
                 'postexcerpt',
3659 3659
                 esc_html__('Short Biography', 'event_espresso'),
3660 3660
                 'post_excerpt_meta_box',
3661
-                $this->_cpt_routes[ $this->_req_action ],
3661
+                $this->_cpt_routes[$this->_req_action],
3662 3662
                 'normal'
3663 3663
             );
3664 3664
         }
@@ -3667,7 +3667,7 @@  discard block
 block discarded – undo
3667 3667
                 'commentsdiv',
3668 3668
                 esc_html__('Notes on the Contact', 'event_espresso'),
3669 3669
                 'post_comment_meta_box',
3670
-                $this->_cpt_routes[ $this->_req_action ],
3670
+                $this->_cpt_routes[$this->_req_action],
3671 3671
                 'normal',
3672 3672
                 'core'
3673 3673
             );
@@ -3676,7 +3676,7 @@  discard block
 block discarded – undo
3676 3676
             'attendee_contact_info',
3677 3677
             esc_html__('Contact Info', 'event_espresso'),
3678 3678
             array($this, 'attendee_contact_info'),
3679
-            $this->_cpt_routes[ $this->_req_action ],
3679
+            $this->_cpt_routes[$this->_req_action],
3680 3680
             'side',
3681 3681
             'core'
3682 3682
         );
@@ -3684,7 +3684,7 @@  discard block
 block discarded – undo
3684 3684
             'attendee_details_address',
3685 3685
             esc_html__('Address Details', 'event_espresso'),
3686 3686
             array($this, 'attendee_address_details'),
3687
-            $this->_cpt_routes[ $this->_req_action ],
3687
+            $this->_cpt_routes[$this->_req_action],
3688 3688
             'normal',
3689 3689
             'core'
3690 3690
         );
@@ -3692,7 +3692,7 @@  discard block
 block discarded – undo
3692 3692
             'attendee_registrations',
3693 3693
             esc_html__('Registrations for this Contact', 'event_espresso'),
3694 3694
             array($this, 'attendee_registrations_meta_box'),
3695
-            $this->_cpt_routes[ $this->_req_action ],
3695
+            $this->_cpt_routes[$this->_req_action],
3696 3696
             'normal',
3697 3697
             'high'
3698 3698
         );
@@ -3793,7 +3793,7 @@  discard block
 block discarded – undo
3793 3793
             )
3794 3794
         );
3795 3795
         $template =
3796
-            REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
3796
+            REG_TEMPLATE_PATH.'attendee_address_details_metabox_content.template.php';
3797 3797
         EEH_Template::display_template($template, $this->_template_args);
3798 3798
     }
3799 3799
 
@@ -3812,7 +3812,7 @@  discard block
 block discarded – undo
3812 3812
         $this->_template_args['attendee'] = $this->_cpt_model_obj;
3813 3813
         $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
3814 3814
         $template =
3815
-            REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
3815
+            REG_TEMPLATE_PATH.'attendee_registrations_main_meta_box.template.php';
3816 3816
         EEH_Template::display_template($template, $this->_template_args);
3817 3817
     }
3818 3818
 
@@ -3827,7 +3827,7 @@  discard block
 block discarded – undo
3827 3827
     public function after_title_form_fields($post)
3828 3828
     {
3829 3829
         if ($post->post_type == 'espresso_attendees') {
3830
-            $template = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
3830
+            $template = REG_TEMPLATE_PATH.'attendee_details_after_title_form_fields.template.php';
3831 3831
             $template_args['attendee'] = $this->_cpt_model_obj;
3832 3832
             EEH_Template::display_template($template, $template_args);
3833 3833
         }
@@ -3851,14 +3851,14 @@  discard block
 block discarded – undo
3851 3851
         $ATT_MDL = EEM_Attendee::instance();
3852 3852
         $success = 1;
3853 3853
         // Checkboxes
3854
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3854
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3855 3855
             // if array has more than one element than success message should be plural
3856 3856
             $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3857 3857
             // cycle thru checkboxes
3858 3858
             while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
3859 3859
                 $updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
3860 3860
                     : $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
3861
-                if (! $updated) {
3861
+                if ( ! $updated) {
3862 3862
                     $success = 0;
3863 3863
                 }
3864 3864
             }
@@ -3869,7 +3869,7 @@  discard block
 block discarded – undo
3869 3869
             $att = $ATT_MDL->get_one_by_ID($ATT_ID);
3870 3870
             $updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3871 3871
             $updated = $att->save();
3872
-            if (! $updated) {
3872
+            if ( ! $updated) {
3873 3873
                 $success = 0;
3874 3874
             }
3875 3875
         }
Please login to merge, or discard this patch.
core/db_classes/EE_Message.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -697,7 +697,7 @@
 block discarded – undo
697 697
     /**
698 698
      * Gets any error message.
699 699
      *
700
-     * @return mixed|null
700
+     * @return string
701 701
      */
702 702
     public function error_message()
703 703
     {
Please login to merge, or discard this patch.
Indentation   +867 added lines, -867 removed lines patch added patch discarded remove patch
@@ -10,875 +10,875 @@
 block discarded – undo
10 10
 class EE_Message extends EE_Base_Class implements EEI_Admin_Links
11 11
 {
12 12
 
13
-    /**
14
-     * @deprecated 4.9.0  Added for backward compat with add-on's
15
-     * @type null
16
-     */
17
-    public $template_pack;
18
-
19
-    /**
20
-     * @deprecated 4.9.0 Added for backward compat with add-on's
21
-     * @type null
22
-     */
23
-    public $template_variation;
24
-
25
-    /**
26
-     * @deprecated 4.9.0 Added for backward compat with add-on's
27
-     * @type string
28
-     */
29
-    public $content = '';
30
-
31
-
32
-    /**
33
-     * @type EE_messenger $_messenger
34
-     */
35
-    protected $_messenger = null;
36
-
37
-    /**
38
-     * @type EE_message_type $_message_type
39
-     */
40
-    protected $_message_type = null;
41
-
42
-
43
-    /**
44
-     * @param array  $props_n_values
45
-     * @param string $timezone
46
-     * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
47
-     *                             format.
48
-     * @return EE_Message
49
-     */
50
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
51
-    {
52
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
53
-        // if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
-        if (! $has_object) {
55
-            EE_Registry::instance()->load_helper('URL');
56
-            $props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57
-        }
58
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
59
-    }
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values
64
-     * @param string $timezone
65
-     * @return EE_Message
66
-     */
67
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
68
-    {
69
-        return new self($props_n_values, true, $timezone);
70
-    }
71
-
72
-
73
-    /**
74
-     * Gets MSG_token
75
-     *
76
-     * @return int
77
-     */
78
-    public function MSG_token()
79
-    {
80
-        return $this->get('MSG_token');
81
-    }
82
-
83
-
84
-    /**
85
-     * Sets MSG_token
86
-     *
87
-     * @param int $MSG_token
88
-     */
89
-    public function set_MSG_token($MSG_token)
90
-    {
91
-        $this->set('MSG_token', $MSG_token);
92
-    }
93
-
94
-
95
-    /**
96
-     * Gets GRP_ID
97
-     *
98
-     * @return int
99
-     */
100
-    public function GRP_ID()
101
-    {
102
-        return $this->get('GRP_ID');
103
-    }
104
-
105
-
106
-    /**
107
-     * Sets GRP_ID
108
-     *
109
-     * @param int $GRP_ID
110
-     */
111
-    public function set_GRP_ID($GRP_ID)
112
-    {
113
-        $this->set('GRP_ID', $GRP_ID);
114
-    }
115
-
116
-
117
-    /**
118
-     * Gets TXN_ID
119
-     *
120
-     * @return int
121
-     */
122
-    public function TXN_ID()
123
-    {
124
-        return $this->get('TXN_ID');
125
-    }
126
-
127
-
128
-    /**
129
-     * Sets TXN_ID
130
-     *
131
-     * @param int $TXN_ID
132
-     */
133
-    public function set_TXN_ID($TXN_ID)
134
-    {
135
-        $this->set('TXN_ID', $TXN_ID);
136
-    }
137
-
138
-
139
-    /**
140
-     * Gets messenger
141
-     *
142
-     * @return string
143
-     */
144
-    public function messenger()
145
-    {
146
-        return $this->get('MSG_messenger');
147
-    }
148
-
149
-
150
-    /**
151
-     * Sets messenger
152
-     *
153
-     * @param string $messenger
154
-     */
155
-    public function set_messenger($messenger)
156
-    {
157
-        $this->set('MSG_messenger', $messenger);
158
-    }
159
-
160
-
161
-    /**
162
-     * Returns corresponding messenger object for the set messenger on this message
163
-     *
164
-     * @return EE_messenger | null
165
-     */
166
-    public function messenger_object()
167
-    {
168
-        return $this->_messenger;
169
-    }
170
-
171
-
172
-    /**
173
-     * Sets messenger
174
-     *
175
-     * @param EE_messenger $messenger
176
-     */
177
-    public function set_messenger_object(EE_messenger $messenger)
178
-    {
179
-        $this->_messenger = $messenger;
180
-    }
181
-
182
-
183
-    /**
184
-     * validates messenger
185
-     *
186
-     * @param bool $throw_exceptions
187
-     * @return bool
188
-     * @throws \EE_Error
189
-     */
190
-    public function valid_messenger($throw_exceptions = false)
191
-    {
192
-        if ($this->_messenger instanceof EE_messenger) {
193
-            return true;
194
-        }
195
-        if ($throw_exceptions) {
196
-            throw new EE_Error(
197
-                sprintf(
198
-                    __(
199
-                        'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
200
-                        'event_espresso'
201
-                    ),
202
-                    $this->messenger()
203
-                )
204
-            );
205
-        }
206
-        return false;
207
-    }
208
-
209
-
210
-    /**
211
-     * This returns the set localized label for the messenger on this message.
212
-     * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
213
-     * with this message.
214
-     *
215
-     * @param   bool $plural whether to return the plural label or not.
216
-     * @return string
217
-     */
218
-    public function messenger_label($plural = false)
219
-    {
220
-        $label_type = $plural ? 'plural' : 'singular';
221
-        $messenger = $this->messenger_object();
222
-        return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
223
-    }
224
-
225
-
226
-    /**
227
-     * Gets message_type
228
-     *
229
-     * @return string
230
-     */
231
-    public function message_type()
232
-    {
233
-        return $this->get('MSG_message_type');
234
-    }
235
-
236
-
237
-    /**
238
-     * Sets message_type
239
-     *
240
-     * @param string $message_type
241
-     */
242
-    public function set_message_type($message_type)
243
-    {
244
-        $this->set('MSG_message_type', $message_type);
245
-    }
246
-
247
-
248
-    /**
249
-     * Returns the message type object for the set message type on this message
250
-     *
251
-     * @return EE_message_type | null
252
-     */
253
-    public function message_type_object()
254
-    {
255
-        return $this->_message_type;
256
-    }
257
-
258
-
259
-    /**
260
-     * Sets message_type
261
-     *
262
-     * @param EE_message_type $message_type
263
-     * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
264
-     *                                        the message type or not.
265
-     */
266
-    public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
267
-    {
268
-        $this->_message_type = $message_type;
269
-        if ($set_priority) {
270
-            $this->set_priority($this->_message_type->get_priority());
271
-        }
272
-    }
273
-
274
-
275
-    /**
276
-     * validates message_type
277
-     *
278
-     * @param bool $throw_exceptions
279
-     * @return bool
280
-     * @throws \EE_Error
281
-     */
282
-    public function valid_message_type($throw_exceptions = false)
283
-    {
284
-        if ($this->_message_type instanceof EE_message_type) {
285
-            return true;
286
-        }
287
-        if ($throw_exceptions) {
288
-            throw new EE_Error(
289
-                sprintf(
290
-                    __(
291
-                        'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
292
-                        'event_espresso'
293
-                    ),
294
-                    $this->message_type()
295
-                )
296
-            );
297
-        }
298
-        return false;
299
-    }
300
-
301
-
302
-    /**
303
-     * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
304
-     *
305
-     * @param bool $throw_exceptions
306
-     * @return bool
307
-     * @throws \EE_Error
308
-     */
309
-    public function is_valid($throw_exceptions = false)
310
-    {
311
-        if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
312
-            return true;
313
-        }
314
-        return false;
315
-    }
316
-
317
-
318
-    /**
319
-     * This validates whether the internal messenger and message type objects are valid for sending.
320
-     * Three checks are done:
321
-     * 1. There is a valid messenger object.
322
-     * 2. There is a valid message type object.
323
-     * 3. The message type object is active for the messenger.
324
-     *
325
-     * @throws EE_Error  But only if $throw_exceptions is set to true.
326
-     * @param bool $throw_exceptions
327
-     * @return bool
328
-     */
329
-    public function is_valid_for_sending_or_generation($throw_exceptions = false)
330
-    {
331
-        $valid = false;
332
-        if ($this->is_valid($throw_exceptions)) {
333
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
334
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
335
-            $valid = $message_resource_manager->is_message_type_active_for_messenger(
336
-                $this->messenger(),
337
-                $this->message_type()
338
-            );
339
-            if (! $valid && $throw_exceptions) {
340
-                throw new EE_Error(
341
-                    sprintf(
342
-                        __(
343
-                            'The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
344
-                            'event_espresso'
345
-                        ),
346
-                        $this->message_type(),
347
-                        $this->messenger()
348
-                    )
349
-                );
350
-            }
351
-        }
352
-        return $valid;
353
-    }
354
-
355
-
356
-    /**
357
-     * This returns the set localized label for the message type on this message.
358
-     * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
359
-     * with this message.
360
-     *
361
-     * @param   bool $plural whether to return the plural label or not.
362
-     * @return string
363
-     */
364
-    public function message_type_label($plural = false)
365
-    {
366
-        $label_type = $plural ? 'plural' : 'singular';
367
-        $message_type = $this->message_type_object();
368
-        return $message_type instanceof EE_message_type
369
-            ? $message_type->label[ $label_type ]
370
-            : str_replace(
371
-                '_',
372
-                ' ',
373
-                $this->message_type()
374
-            );
375
-    }
376
-
377
-
378
-    /**
379
-     * Gets context
380
-     *
381
-     * @return string
382
-     */
383
-    public function context()
384
-    {
385
-        return $this->get('MSG_context');
386
-    }
387
-
388
-
389
-    /**
390
-     * This returns the corresponding localized label for the given context slug, if possible from installed message
391
-     * types. Otherwise, this will just return the set context slug on this object.
392
-     *
393
-     * @return string
394
-     */
395
-    public function context_label()
396
-    {
397
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
398
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399
-        $contexts = $message_resource_manager->get_all_contexts();
400
-        return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
401
-    }
402
-
403
-
404
-    /**
405
-     * Sets context
406
-     *
407
-     * @param string $context
408
-     */
409
-    public function set_context($context)
410
-    {
411
-        $this->set('MSG_context', $context);
412
-    }
413
-
414
-
415
-    /**
416
-     * Gets recipient_ID
417
-     *
418
-     * @return int
419
-     */
420
-    public function recipient_ID()
421
-    {
422
-        return $this->get('MSG_recipient_ID');
423
-    }
424
-
425
-
426
-    /**
427
-     * Sets recipient_ID
428
-     *
429
-     * @param string $recipient_ID
430
-     */
431
-    public function set_recipient_ID($recipient_ID)
432
-    {
433
-        $this->set('MSG_recipient_ID', $recipient_ID);
434
-    }
435
-
436
-
437
-    /**
438
-     * Gets recipient_type
439
-     *
440
-     * @return string
441
-     */
442
-    public function recipient_type()
443
-    {
444
-        return $this->get('MSG_recipient_type');
445
-    }
446
-
447
-
448
-    /**
449
-     * Return the related object matching the recipient type and ID.
450
-     *
451
-     * @return EE_Base_Class | null
452
-     */
453
-    public function recipient_object()
454
-    {
455
-        if (! $this->recipient_type() || ! $this->recipient_ID()) {
456
-            return null;
457
-        }
458
-
459
-        return $this->get_first_related($this->recipient_type());
460
-    }
461
-
462
-
463
-    /**
464
-     * Sets recipient_type
465
-     *
466
-     * @param string $recipient_type
467
-     */
468
-    public function set_recipient_type($recipient_type)
469
-    {
470
-        $this->set('MSG_recipient_type', $recipient_type);
471
-    }
472
-
473
-
474
-    /**
475
-     * Gets content
476
-     *
477
-     * @return string
478
-     */
479
-    public function content()
480
-    {
481
-        return $this->get('MSG_content');
482
-    }
483
-
484
-
485
-    /**
486
-     * Sets content
487
-     *
488
-     * @param string $content
489
-     */
490
-    public function set_content($content)
491
-    {
492
-        $this->set('MSG_content', $content);
493
-    }
494
-
495
-
496
-    /**
497
-     * Gets subject
498
-     *
499
-     * @return string
500
-     */
501
-    public function subject()
502
-    {
503
-        return $this->get('MSG_subject');
504
-    }
505
-
506
-
507
-    /**
508
-     * Sets subject
509
-     *
510
-     * @param string $subject
511
-     */
512
-    public function set_subject($subject)
513
-    {
514
-        $this->set('MSG_subject', $subject);
515
-    }
516
-
517
-
518
-    /**
519
-     * Gets to
520
-     *
521
-     * @return string
522
-     */
523
-    public function to()
524
-    {
525
-        $to = $this->get('MSG_to');
526
-        return empty($to) ? __('No recipient', 'event_espresso') : $to;
527
-    }
528
-
529
-
530
-    /**
531
-     * Sets to
532
-     *
533
-     * @param string $to
534
-     */
535
-    public function set_to($to)
536
-    {
537
-        $this->set('MSG_to', $to);
538
-    }
539
-
540
-
541
-    /**
542
-     * Gets from
543
-     *
544
-     * @return string
545
-     */
546
-    public function from()
547
-    {
548
-        return $this->get('MSG_from');
549
-    }
550
-
551
-
552
-    /**
553
-     * Sets from
554
-     *
555
-     * @param string $from
556
-     */
557
-    public function set_from($from)
558
-    {
559
-        $this->set('MSG_from', $from);
560
-    }
561
-
562
-
563
-    /**
564
-     * Gets priority
565
-     *
566
-     * @return int
567
-     */
568
-    public function priority()
569
-    {
570
-        return $this->get('MSG_priority');
571
-    }
572
-
573
-
574
-    /**
575
-     * Sets priority
576
-     * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
577
-     * this method calls the send_now method to verify that.
578
-     *
579
-     * @param int $priority
580
-     */
581
-    public function set_priority($priority)
582
-    {
583
-        $priority = $this->send_now() ? EEM_Message::priority_high : $priority;
584
-        parent::set('MSG_priority', $priority);
585
-    }
586
-
587
-
588
-    /**
589
-     * Overrides parent::set method so we can capture any sets for priority.
590
-     *
591
-     * @see parent::set() for phpdocs
592
-     * @param string $field_name
593
-     * @param mixed  $field_value
594
-     * @param bool   $use_default
595
-     * @throws EE_Error
596
-     */
597
-    public function set($field_name, $field_value, $use_default = false)
598
-    {
599
-        if ($field_name === 'MSG_priority') {
600
-            $this->set_priority($field_value);
601
-        }
602
-        parent::set($field_name, $field_value, $use_default);
603
-    }
604
-
605
-
606
-    /**
607
-     * @return bool
608
-     * @throws \EE_Error
609
-     */
610
-    public function send_now()
611
-    {
612
-        $send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high
613
-            : $this->priority();
614
-        return $send_now === EEM_Message::priority_high ? true : false;
615
-    }
616
-
617
-
618
-    /**
619
-     * Gets STS_ID
620
-     *
621
-     * @return string
622
-     */
623
-    public function STS_ID()
624
-    {
625
-        return $this->get('STS_ID');
626
-    }
627
-
628
-
629
-    /**
630
-     * Sets STS_ID
631
-     *
632
-     * @param string $STS_ID
633
-     */
634
-    public function set_STS_ID($STS_ID)
635
-    {
636
-        $this->set('STS_ID', $STS_ID);
637
-    }
638
-
639
-
640
-    /**
641
-     * Gets created
642
-     *
643
-     * @return string
644
-     */
645
-    public function created()
646
-    {
647
-        return $this->get('MSG_created');
648
-    }
649
-
650
-
651
-    /**
652
-     * Sets created
653
-     *
654
-     * @param string $created
655
-     */
656
-    public function set_created($created)
657
-    {
658
-        $this->set('MSG_created', $created);
659
-    }
660
-
661
-
662
-    /**
663
-     * Gets modified
664
-     *
665
-     * @return string
666
-     */
667
-    public function modified()
668
-    {
669
-        return $this->get('MSG_modified');
670
-    }
671
-
672
-
673
-    /**
674
-     * Sets modified
675
-     *
676
-     * @param string $modified
677
-     */
678
-    public function set_modified($modified)
679
-    {
680
-        $this->set('MSG_modified', $modified);
681
-    }
682
-
683
-
684
-    /**
685
-     * Sets generation data for this message.
686
-     *
687
-     * @param mixed $data
688
-     */
689
-    public function set_generation_data($data)
690
-    {
691
-        $this->set_field_or_extra_meta('MSG_generation_data', $data);
692
-    }
693
-
694
-
695
-    /**
696
-     * Returns any set generation data for this message.
697
-     *
698
-     * @return mixed|null
699
-     */
700
-    public function get_generation_data()
701
-    {
702
-        return $this->get_field_or_extra_meta('MSG_generation_data');
703
-    }
704
-
705
-
706
-    /**
707
-     * Gets any error message.
708
-     *
709
-     * @return mixed|null
710
-     */
711
-    public function error_message()
712
-    {
713
-        return $this->get_field_or_extra_meta('MSG_error');
714
-    }
715
-
716
-
717
-    /**
718
-     * Sets an error message.
719
-     *
720
-     * @param $message
721
-     * @return bool|int
722
-     */
723
-    public function set_error_message($message)
724
-    {
725
-        return $this->set_field_or_extra_meta('MSG_error', $message);
726
-    }
727
-
728
-
729
-    /**
730
-     * This retrieves the associated template pack with this message.
731
-     *
732
-     * @return EE_Messages_Template_Pack | null
733
-     */
734
-    public function get_template_pack()
735
-    {
736
-        /**
737
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738
-         */
739
-        if (! empty($this->template_pack)) {
740
-            return $this->template_pack;
741
-        }
742
-        /** @type EE_Message_Template_Group $grp */
743
-        $grp = $this->get_first_related('Message_Template_Group');
744
-        // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
-        if (! $grp instanceof EE_Message_Template_Group) {
746
-            $grp = EEM_Message_Template_Group::instance()->get_one(
747
-                array(
748
-                    array(
749
-                        'MTP_messenger'    => $this->messenger(),
750
-                        'MTP_message_type' => $this->message_type(),
751
-                        'MTP_is_global'    => true,
752
-                    ),
753
-                )
754
-            );
755
-        }
756
-
757
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
758
-    }
759
-
760
-
761
-    /**
762
-     * Retrieves the variation used for generating this message.
763
-     *
764
-     * @return string
765
-     */
766
-    public function get_template_pack_variation()
767
-    {
768
-        /**
769
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770
-         */
771
-        if (! empty($this->template_variation)) {
772
-            return $this->template_variation;
773
-        }
774
-
775
-        /** @type EE_Message_Template_Group $grp */
776
-        $grp = $this->get_first_related('Message_Template_Group');
777
-
778
-        // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
-        if (! $grp instanceof EE_Message_Template_Group) {
780
-            $grp = EEM_Message_Template_Group::instance()->get_one(
781
-                array(
782
-                    array(
783
-                        'MTP_messenger'    => $this->messenger(),
784
-                        'MTP_message_type' => $this->message_type(),
785
-                        'MTP_is_global'    => true,
786
-                    ),
787
-                )
788
-            );
789
-        }
790
-
791
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
792
-    }
793
-
794
-    /**
795
-     * Return the link to the admin details for the object.
796
-     *
797
-     * @return string
798
-     */
799
-    public function get_admin_details_link()
800
-    {
801
-        EE_Registry::instance()->load_helper('URL');
802
-        EE_Registry::instance()->load_helper('MSG_Template');
803
-        switch ($this->STS_ID()) {
804
-            case EEM_Message::status_failed:
805
-            case EEM_Message::status_debug_only:
806
-                return EEH_MSG_Template::generate_error_display_trigger($this);
807
-                break;
808
-
809
-            case EEM_Message::status_sent:
810
-                return EEH_MSG_Template::generate_browser_trigger($this);
811
-                break;
812
-
813
-            default:
814
-                return '';
815
-        }
816
-    }
817
-
818
-    /**
819
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
820
-     *
821
-     * @return string
822
-     */
823
-    public function get_admin_edit_link()
824
-    {
825
-        return $this->get_admin_details_link();
826
-    }
827
-
828
-    /**
829
-     * Returns the link to a settings page for the object.
830
-     *
831
-     * @return string
832
-     */
833
-    public function get_admin_settings_link()
834
-    {
835
-        EE_Registry::instance()->load_helper('URL');
836
-        return EEH_URL::add_query_args_and_nonce(
837
-            array(
838
-                'page'   => 'espresso_messages',
839
-                'action' => 'settings',
840
-            ),
841
-            admin_url('admin.php')
842
-        );
843
-    }
844
-
845
-    /**
846
-     * Returns the link to the "overview" for the object (typically the "list table" view).
847
-     *
848
-     * @return string
849
-     */
850
-    public function get_admin_overview_link()
851
-    {
852
-        EE_Registry::instance()->load_helper('URL');
853
-        return EEH_URL::add_query_args_and_nonce(
854
-            array(
855
-                'page'   => 'espresso_messages',
856
-                'action' => 'default',
857
-            ),
858
-            admin_url('admin.php')
859
-        );
860
-    }
861
-
862
-
863
-    /**
864
-     * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
865
-     * it.
866
-     * Note this also SAVES the current message object to the db because it adds an error message to accompany the
867
-     * status.
868
-     *
869
-     */
870
-    public function set_messenger_is_executing()
871
-    {
872
-        $this->set_STS_ID(EEM_Message::status_messenger_executing);
873
-        $this->set_error_message(
874
-            esc_html__(
875
-                'A message with this status indicates that there was a problem that occurred while the message was being
13
+	/**
14
+	 * @deprecated 4.9.0  Added for backward compat with add-on's
15
+	 * @type null
16
+	 */
17
+	public $template_pack;
18
+
19
+	/**
20
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
21
+	 * @type null
22
+	 */
23
+	public $template_variation;
24
+
25
+	/**
26
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
27
+	 * @type string
28
+	 */
29
+	public $content = '';
30
+
31
+
32
+	/**
33
+	 * @type EE_messenger $_messenger
34
+	 */
35
+	protected $_messenger = null;
36
+
37
+	/**
38
+	 * @type EE_message_type $_message_type
39
+	 */
40
+	protected $_message_type = null;
41
+
42
+
43
+	/**
44
+	 * @param array  $props_n_values
45
+	 * @param string $timezone
46
+	 * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
47
+	 *                             format.
48
+	 * @return EE_Message
49
+	 */
50
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
51
+	{
52
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
53
+		// if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
+		if (! $has_object) {
55
+			EE_Registry::instance()->load_helper('URL');
56
+			$props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57
+		}
58
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
59
+	}
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values
64
+	 * @param string $timezone
65
+	 * @return EE_Message
66
+	 */
67
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
68
+	{
69
+		return new self($props_n_values, true, $timezone);
70
+	}
71
+
72
+
73
+	/**
74
+	 * Gets MSG_token
75
+	 *
76
+	 * @return int
77
+	 */
78
+	public function MSG_token()
79
+	{
80
+		return $this->get('MSG_token');
81
+	}
82
+
83
+
84
+	/**
85
+	 * Sets MSG_token
86
+	 *
87
+	 * @param int $MSG_token
88
+	 */
89
+	public function set_MSG_token($MSG_token)
90
+	{
91
+		$this->set('MSG_token', $MSG_token);
92
+	}
93
+
94
+
95
+	/**
96
+	 * Gets GRP_ID
97
+	 *
98
+	 * @return int
99
+	 */
100
+	public function GRP_ID()
101
+	{
102
+		return $this->get('GRP_ID');
103
+	}
104
+
105
+
106
+	/**
107
+	 * Sets GRP_ID
108
+	 *
109
+	 * @param int $GRP_ID
110
+	 */
111
+	public function set_GRP_ID($GRP_ID)
112
+	{
113
+		$this->set('GRP_ID', $GRP_ID);
114
+	}
115
+
116
+
117
+	/**
118
+	 * Gets TXN_ID
119
+	 *
120
+	 * @return int
121
+	 */
122
+	public function TXN_ID()
123
+	{
124
+		return $this->get('TXN_ID');
125
+	}
126
+
127
+
128
+	/**
129
+	 * Sets TXN_ID
130
+	 *
131
+	 * @param int $TXN_ID
132
+	 */
133
+	public function set_TXN_ID($TXN_ID)
134
+	{
135
+		$this->set('TXN_ID', $TXN_ID);
136
+	}
137
+
138
+
139
+	/**
140
+	 * Gets messenger
141
+	 *
142
+	 * @return string
143
+	 */
144
+	public function messenger()
145
+	{
146
+		return $this->get('MSG_messenger');
147
+	}
148
+
149
+
150
+	/**
151
+	 * Sets messenger
152
+	 *
153
+	 * @param string $messenger
154
+	 */
155
+	public function set_messenger($messenger)
156
+	{
157
+		$this->set('MSG_messenger', $messenger);
158
+	}
159
+
160
+
161
+	/**
162
+	 * Returns corresponding messenger object for the set messenger on this message
163
+	 *
164
+	 * @return EE_messenger | null
165
+	 */
166
+	public function messenger_object()
167
+	{
168
+		return $this->_messenger;
169
+	}
170
+
171
+
172
+	/**
173
+	 * Sets messenger
174
+	 *
175
+	 * @param EE_messenger $messenger
176
+	 */
177
+	public function set_messenger_object(EE_messenger $messenger)
178
+	{
179
+		$this->_messenger = $messenger;
180
+	}
181
+
182
+
183
+	/**
184
+	 * validates messenger
185
+	 *
186
+	 * @param bool $throw_exceptions
187
+	 * @return bool
188
+	 * @throws \EE_Error
189
+	 */
190
+	public function valid_messenger($throw_exceptions = false)
191
+	{
192
+		if ($this->_messenger instanceof EE_messenger) {
193
+			return true;
194
+		}
195
+		if ($throw_exceptions) {
196
+			throw new EE_Error(
197
+				sprintf(
198
+					__(
199
+						'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
200
+						'event_espresso'
201
+					),
202
+					$this->messenger()
203
+				)
204
+			);
205
+		}
206
+		return false;
207
+	}
208
+
209
+
210
+	/**
211
+	 * This returns the set localized label for the messenger on this message.
212
+	 * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
213
+	 * with this message.
214
+	 *
215
+	 * @param   bool $plural whether to return the plural label or not.
216
+	 * @return string
217
+	 */
218
+	public function messenger_label($plural = false)
219
+	{
220
+		$label_type = $plural ? 'plural' : 'singular';
221
+		$messenger = $this->messenger_object();
222
+		return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
223
+	}
224
+
225
+
226
+	/**
227
+	 * Gets message_type
228
+	 *
229
+	 * @return string
230
+	 */
231
+	public function message_type()
232
+	{
233
+		return $this->get('MSG_message_type');
234
+	}
235
+
236
+
237
+	/**
238
+	 * Sets message_type
239
+	 *
240
+	 * @param string $message_type
241
+	 */
242
+	public function set_message_type($message_type)
243
+	{
244
+		$this->set('MSG_message_type', $message_type);
245
+	}
246
+
247
+
248
+	/**
249
+	 * Returns the message type object for the set message type on this message
250
+	 *
251
+	 * @return EE_message_type | null
252
+	 */
253
+	public function message_type_object()
254
+	{
255
+		return $this->_message_type;
256
+	}
257
+
258
+
259
+	/**
260
+	 * Sets message_type
261
+	 *
262
+	 * @param EE_message_type $message_type
263
+	 * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
264
+	 *                                        the message type or not.
265
+	 */
266
+	public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
267
+	{
268
+		$this->_message_type = $message_type;
269
+		if ($set_priority) {
270
+			$this->set_priority($this->_message_type->get_priority());
271
+		}
272
+	}
273
+
274
+
275
+	/**
276
+	 * validates message_type
277
+	 *
278
+	 * @param bool $throw_exceptions
279
+	 * @return bool
280
+	 * @throws \EE_Error
281
+	 */
282
+	public function valid_message_type($throw_exceptions = false)
283
+	{
284
+		if ($this->_message_type instanceof EE_message_type) {
285
+			return true;
286
+		}
287
+		if ($throw_exceptions) {
288
+			throw new EE_Error(
289
+				sprintf(
290
+					__(
291
+						'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
292
+						'event_espresso'
293
+					),
294
+					$this->message_type()
295
+				)
296
+			);
297
+		}
298
+		return false;
299
+	}
300
+
301
+
302
+	/**
303
+	 * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
304
+	 *
305
+	 * @param bool $throw_exceptions
306
+	 * @return bool
307
+	 * @throws \EE_Error
308
+	 */
309
+	public function is_valid($throw_exceptions = false)
310
+	{
311
+		if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
312
+			return true;
313
+		}
314
+		return false;
315
+	}
316
+
317
+
318
+	/**
319
+	 * This validates whether the internal messenger and message type objects are valid for sending.
320
+	 * Three checks are done:
321
+	 * 1. There is a valid messenger object.
322
+	 * 2. There is a valid message type object.
323
+	 * 3. The message type object is active for the messenger.
324
+	 *
325
+	 * @throws EE_Error  But only if $throw_exceptions is set to true.
326
+	 * @param bool $throw_exceptions
327
+	 * @return bool
328
+	 */
329
+	public function is_valid_for_sending_or_generation($throw_exceptions = false)
330
+	{
331
+		$valid = false;
332
+		if ($this->is_valid($throw_exceptions)) {
333
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
334
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
335
+			$valid = $message_resource_manager->is_message_type_active_for_messenger(
336
+				$this->messenger(),
337
+				$this->message_type()
338
+			);
339
+			if (! $valid && $throw_exceptions) {
340
+				throw new EE_Error(
341
+					sprintf(
342
+						__(
343
+							'The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
344
+							'event_espresso'
345
+						),
346
+						$this->message_type(),
347
+						$this->messenger()
348
+					)
349
+				);
350
+			}
351
+		}
352
+		return $valid;
353
+	}
354
+
355
+
356
+	/**
357
+	 * This returns the set localized label for the message type on this message.
358
+	 * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
359
+	 * with this message.
360
+	 *
361
+	 * @param   bool $plural whether to return the plural label or not.
362
+	 * @return string
363
+	 */
364
+	public function message_type_label($plural = false)
365
+	{
366
+		$label_type = $plural ? 'plural' : 'singular';
367
+		$message_type = $this->message_type_object();
368
+		return $message_type instanceof EE_message_type
369
+			? $message_type->label[ $label_type ]
370
+			: str_replace(
371
+				'_',
372
+				' ',
373
+				$this->message_type()
374
+			);
375
+	}
376
+
377
+
378
+	/**
379
+	 * Gets context
380
+	 *
381
+	 * @return string
382
+	 */
383
+	public function context()
384
+	{
385
+		return $this->get('MSG_context');
386
+	}
387
+
388
+
389
+	/**
390
+	 * This returns the corresponding localized label for the given context slug, if possible from installed message
391
+	 * types. Otherwise, this will just return the set context slug on this object.
392
+	 *
393
+	 * @return string
394
+	 */
395
+	public function context_label()
396
+	{
397
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
398
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399
+		$contexts = $message_resource_manager->get_all_contexts();
400
+		return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
401
+	}
402
+
403
+
404
+	/**
405
+	 * Sets context
406
+	 *
407
+	 * @param string $context
408
+	 */
409
+	public function set_context($context)
410
+	{
411
+		$this->set('MSG_context', $context);
412
+	}
413
+
414
+
415
+	/**
416
+	 * Gets recipient_ID
417
+	 *
418
+	 * @return int
419
+	 */
420
+	public function recipient_ID()
421
+	{
422
+		return $this->get('MSG_recipient_ID');
423
+	}
424
+
425
+
426
+	/**
427
+	 * Sets recipient_ID
428
+	 *
429
+	 * @param string $recipient_ID
430
+	 */
431
+	public function set_recipient_ID($recipient_ID)
432
+	{
433
+		$this->set('MSG_recipient_ID', $recipient_ID);
434
+	}
435
+
436
+
437
+	/**
438
+	 * Gets recipient_type
439
+	 *
440
+	 * @return string
441
+	 */
442
+	public function recipient_type()
443
+	{
444
+		return $this->get('MSG_recipient_type');
445
+	}
446
+
447
+
448
+	/**
449
+	 * Return the related object matching the recipient type and ID.
450
+	 *
451
+	 * @return EE_Base_Class | null
452
+	 */
453
+	public function recipient_object()
454
+	{
455
+		if (! $this->recipient_type() || ! $this->recipient_ID()) {
456
+			return null;
457
+		}
458
+
459
+		return $this->get_first_related($this->recipient_type());
460
+	}
461
+
462
+
463
+	/**
464
+	 * Sets recipient_type
465
+	 *
466
+	 * @param string $recipient_type
467
+	 */
468
+	public function set_recipient_type($recipient_type)
469
+	{
470
+		$this->set('MSG_recipient_type', $recipient_type);
471
+	}
472
+
473
+
474
+	/**
475
+	 * Gets content
476
+	 *
477
+	 * @return string
478
+	 */
479
+	public function content()
480
+	{
481
+		return $this->get('MSG_content');
482
+	}
483
+
484
+
485
+	/**
486
+	 * Sets content
487
+	 *
488
+	 * @param string $content
489
+	 */
490
+	public function set_content($content)
491
+	{
492
+		$this->set('MSG_content', $content);
493
+	}
494
+
495
+
496
+	/**
497
+	 * Gets subject
498
+	 *
499
+	 * @return string
500
+	 */
501
+	public function subject()
502
+	{
503
+		return $this->get('MSG_subject');
504
+	}
505
+
506
+
507
+	/**
508
+	 * Sets subject
509
+	 *
510
+	 * @param string $subject
511
+	 */
512
+	public function set_subject($subject)
513
+	{
514
+		$this->set('MSG_subject', $subject);
515
+	}
516
+
517
+
518
+	/**
519
+	 * Gets to
520
+	 *
521
+	 * @return string
522
+	 */
523
+	public function to()
524
+	{
525
+		$to = $this->get('MSG_to');
526
+		return empty($to) ? __('No recipient', 'event_espresso') : $to;
527
+	}
528
+
529
+
530
+	/**
531
+	 * Sets to
532
+	 *
533
+	 * @param string $to
534
+	 */
535
+	public function set_to($to)
536
+	{
537
+		$this->set('MSG_to', $to);
538
+	}
539
+
540
+
541
+	/**
542
+	 * Gets from
543
+	 *
544
+	 * @return string
545
+	 */
546
+	public function from()
547
+	{
548
+		return $this->get('MSG_from');
549
+	}
550
+
551
+
552
+	/**
553
+	 * Sets from
554
+	 *
555
+	 * @param string $from
556
+	 */
557
+	public function set_from($from)
558
+	{
559
+		$this->set('MSG_from', $from);
560
+	}
561
+
562
+
563
+	/**
564
+	 * Gets priority
565
+	 *
566
+	 * @return int
567
+	 */
568
+	public function priority()
569
+	{
570
+		return $this->get('MSG_priority');
571
+	}
572
+
573
+
574
+	/**
575
+	 * Sets priority
576
+	 * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
577
+	 * this method calls the send_now method to verify that.
578
+	 *
579
+	 * @param int $priority
580
+	 */
581
+	public function set_priority($priority)
582
+	{
583
+		$priority = $this->send_now() ? EEM_Message::priority_high : $priority;
584
+		parent::set('MSG_priority', $priority);
585
+	}
586
+
587
+
588
+	/**
589
+	 * Overrides parent::set method so we can capture any sets for priority.
590
+	 *
591
+	 * @see parent::set() for phpdocs
592
+	 * @param string $field_name
593
+	 * @param mixed  $field_value
594
+	 * @param bool   $use_default
595
+	 * @throws EE_Error
596
+	 */
597
+	public function set($field_name, $field_value, $use_default = false)
598
+	{
599
+		if ($field_name === 'MSG_priority') {
600
+			$this->set_priority($field_value);
601
+		}
602
+		parent::set($field_name, $field_value, $use_default);
603
+	}
604
+
605
+
606
+	/**
607
+	 * @return bool
608
+	 * @throws \EE_Error
609
+	 */
610
+	public function send_now()
611
+	{
612
+		$send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high
613
+			: $this->priority();
614
+		return $send_now === EEM_Message::priority_high ? true : false;
615
+	}
616
+
617
+
618
+	/**
619
+	 * Gets STS_ID
620
+	 *
621
+	 * @return string
622
+	 */
623
+	public function STS_ID()
624
+	{
625
+		return $this->get('STS_ID');
626
+	}
627
+
628
+
629
+	/**
630
+	 * Sets STS_ID
631
+	 *
632
+	 * @param string $STS_ID
633
+	 */
634
+	public function set_STS_ID($STS_ID)
635
+	{
636
+		$this->set('STS_ID', $STS_ID);
637
+	}
638
+
639
+
640
+	/**
641
+	 * Gets created
642
+	 *
643
+	 * @return string
644
+	 */
645
+	public function created()
646
+	{
647
+		return $this->get('MSG_created');
648
+	}
649
+
650
+
651
+	/**
652
+	 * Sets created
653
+	 *
654
+	 * @param string $created
655
+	 */
656
+	public function set_created($created)
657
+	{
658
+		$this->set('MSG_created', $created);
659
+	}
660
+
661
+
662
+	/**
663
+	 * Gets modified
664
+	 *
665
+	 * @return string
666
+	 */
667
+	public function modified()
668
+	{
669
+		return $this->get('MSG_modified');
670
+	}
671
+
672
+
673
+	/**
674
+	 * Sets modified
675
+	 *
676
+	 * @param string $modified
677
+	 */
678
+	public function set_modified($modified)
679
+	{
680
+		$this->set('MSG_modified', $modified);
681
+	}
682
+
683
+
684
+	/**
685
+	 * Sets generation data for this message.
686
+	 *
687
+	 * @param mixed $data
688
+	 */
689
+	public function set_generation_data($data)
690
+	{
691
+		$this->set_field_or_extra_meta('MSG_generation_data', $data);
692
+	}
693
+
694
+
695
+	/**
696
+	 * Returns any set generation data for this message.
697
+	 *
698
+	 * @return mixed|null
699
+	 */
700
+	public function get_generation_data()
701
+	{
702
+		return $this->get_field_or_extra_meta('MSG_generation_data');
703
+	}
704
+
705
+
706
+	/**
707
+	 * Gets any error message.
708
+	 *
709
+	 * @return mixed|null
710
+	 */
711
+	public function error_message()
712
+	{
713
+		return $this->get_field_or_extra_meta('MSG_error');
714
+	}
715
+
716
+
717
+	/**
718
+	 * Sets an error message.
719
+	 *
720
+	 * @param $message
721
+	 * @return bool|int
722
+	 */
723
+	public function set_error_message($message)
724
+	{
725
+		return $this->set_field_or_extra_meta('MSG_error', $message);
726
+	}
727
+
728
+
729
+	/**
730
+	 * This retrieves the associated template pack with this message.
731
+	 *
732
+	 * @return EE_Messages_Template_Pack | null
733
+	 */
734
+	public function get_template_pack()
735
+	{
736
+		/**
737
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738
+		 */
739
+		if (! empty($this->template_pack)) {
740
+			return $this->template_pack;
741
+		}
742
+		/** @type EE_Message_Template_Group $grp */
743
+		$grp = $this->get_first_related('Message_Template_Group');
744
+		// if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
+		if (! $grp instanceof EE_Message_Template_Group) {
746
+			$grp = EEM_Message_Template_Group::instance()->get_one(
747
+				array(
748
+					array(
749
+						'MTP_messenger'    => $this->messenger(),
750
+						'MTP_message_type' => $this->message_type(),
751
+						'MTP_is_global'    => true,
752
+					),
753
+				)
754
+			);
755
+		}
756
+
757
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
758
+	}
759
+
760
+
761
+	/**
762
+	 * Retrieves the variation used for generating this message.
763
+	 *
764
+	 * @return string
765
+	 */
766
+	public function get_template_pack_variation()
767
+	{
768
+		/**
769
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770
+		 */
771
+		if (! empty($this->template_variation)) {
772
+			return $this->template_variation;
773
+		}
774
+
775
+		/** @type EE_Message_Template_Group $grp */
776
+		$grp = $this->get_first_related('Message_Template_Group');
777
+
778
+		// if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
+		if (! $grp instanceof EE_Message_Template_Group) {
780
+			$grp = EEM_Message_Template_Group::instance()->get_one(
781
+				array(
782
+					array(
783
+						'MTP_messenger'    => $this->messenger(),
784
+						'MTP_message_type' => $this->message_type(),
785
+						'MTP_is_global'    => true,
786
+					),
787
+				)
788
+			);
789
+		}
790
+
791
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
792
+	}
793
+
794
+	/**
795
+	 * Return the link to the admin details for the object.
796
+	 *
797
+	 * @return string
798
+	 */
799
+	public function get_admin_details_link()
800
+	{
801
+		EE_Registry::instance()->load_helper('URL');
802
+		EE_Registry::instance()->load_helper('MSG_Template');
803
+		switch ($this->STS_ID()) {
804
+			case EEM_Message::status_failed:
805
+			case EEM_Message::status_debug_only:
806
+				return EEH_MSG_Template::generate_error_display_trigger($this);
807
+				break;
808
+
809
+			case EEM_Message::status_sent:
810
+				return EEH_MSG_Template::generate_browser_trigger($this);
811
+				break;
812
+
813
+			default:
814
+				return '';
815
+		}
816
+	}
817
+
818
+	/**
819
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
820
+	 *
821
+	 * @return string
822
+	 */
823
+	public function get_admin_edit_link()
824
+	{
825
+		return $this->get_admin_details_link();
826
+	}
827
+
828
+	/**
829
+	 * Returns the link to a settings page for the object.
830
+	 *
831
+	 * @return string
832
+	 */
833
+	public function get_admin_settings_link()
834
+	{
835
+		EE_Registry::instance()->load_helper('URL');
836
+		return EEH_URL::add_query_args_and_nonce(
837
+			array(
838
+				'page'   => 'espresso_messages',
839
+				'action' => 'settings',
840
+			),
841
+			admin_url('admin.php')
842
+		);
843
+	}
844
+
845
+	/**
846
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
847
+	 *
848
+	 * @return string
849
+	 */
850
+	public function get_admin_overview_link()
851
+	{
852
+		EE_Registry::instance()->load_helper('URL');
853
+		return EEH_URL::add_query_args_and_nonce(
854
+			array(
855
+				'page'   => 'espresso_messages',
856
+				'action' => 'default',
857
+			),
858
+			admin_url('admin.php')
859
+		);
860
+	}
861
+
862
+
863
+	/**
864
+	 * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
865
+	 * it.
866
+	 * Note this also SAVES the current message object to the db because it adds an error message to accompany the
867
+	 * status.
868
+	 *
869
+	 */
870
+	public function set_messenger_is_executing()
871
+	{
872
+		$this->set_STS_ID(EEM_Message::status_messenger_executing);
873
+		$this->set_error_message(
874
+			esc_html__(
875
+				'A message with this status indicates that there was a problem that occurred while the message was being
876 876
                 processed by the messenger.  It is still possible that the message was sent successfully, but at some
877 877
                 point during the processing there was a failure.  This usually is indicative of a timeout issue with PHP 
878 878
                 or memory limits being reached.  If you see this repeatedly you may want to consider upgrading the memory 
879 879
                 available to PHP on your server.',
880
-                'event_espresso'
881
-            )
882
-        );
883
-    }
880
+				'event_espresso'
881
+			)
882
+		);
883
+	}
884 884
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
     {
52 52
         $has_object = parent::_check_for_object($props_n_values, __CLASS__);
53 53
         // if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
54
-        if (! $has_object) {
54
+        if ( ! $has_object) {
55 55
             EE_Registry::instance()->load_helper('URL');
56 56
             $props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
57 57
         }
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
     {
220 220
         $label_type = $plural ? 'plural' : 'singular';
221 221
         $messenger = $this->messenger_object();
222
-        return $messenger instanceof EE_messenger ? $messenger->label[ $label_type ] : $this->messenger();
222
+        return $messenger instanceof EE_messenger ? $messenger->label[$label_type] : $this->messenger();
223 223
     }
224 224
 
225 225
 
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
                 $this->messenger(),
337 337
                 $this->message_type()
338 338
             );
339
-            if (! $valid && $throw_exceptions) {
339
+            if ( ! $valid && $throw_exceptions) {
340 340
                 throw new EE_Error(
341 341
                     sprintf(
342 342
                         __(
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
         $label_type = $plural ? 'plural' : 'singular';
367 367
         $message_type = $this->message_type_object();
368 368
         return $message_type instanceof EE_message_type
369
-            ? $message_type->label[ $label_type ]
369
+            ? $message_type->label[$label_type]
370 370
             : str_replace(
371 371
                 '_',
372 372
                 ' ',
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
         /** @type EE_Message_Resource_Manager $message_resource_manager */
398 398
         $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
399 399
         $contexts = $message_resource_manager->get_all_contexts();
400
-        return isset($contexts[ $this->context() ]) ? $contexts[ $this->context() ] : $this->context();
400
+        return isset($contexts[$this->context()]) ? $contexts[$this->context()] : $this->context();
401 401
     }
402 402
 
403 403
 
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
      */
453 453
     public function recipient_object()
454 454
     {
455
-        if (! $this->recipient_type() || ! $this->recipient_ID()) {
455
+        if ( ! $this->recipient_type() || ! $this->recipient_ID()) {
456 456
             return null;
457 457
         }
458 458
 
@@ -736,13 +736,13 @@  discard block
 block discarded – undo
736 736
         /**
737 737
          * This is deprecated functionality that will be removed eventually but included here now for backward compat.
738 738
          */
739
-        if (! empty($this->template_pack)) {
739
+        if ( ! empty($this->template_pack)) {
740 740
             return $this->template_pack;
741 741
         }
742 742
         /** @type EE_Message_Template_Group $grp */
743 743
         $grp = $this->get_first_related('Message_Template_Group');
744 744
         // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
745
-        if (! $grp instanceof EE_Message_Template_Group) {
745
+        if ( ! $grp instanceof EE_Message_Template_Group) {
746 746
             $grp = EEM_Message_Template_Group::instance()->get_one(
747 747
                 array(
748 748
                     array(
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
         /**
769 769
          * This is deprecated functionality that will be removed eventually but included here now for backward compat.
770 770
          */
771
-        if (! empty($this->template_variation)) {
771
+        if ( ! empty($this->template_variation)) {
772 772
             return $this->template_variation;
773 773
         }
774 774
 
@@ -776,7 +776,7 @@  discard block
 block discarded – undo
776 776
         $grp = $this->get_first_related('Message_Template_Group');
777 777
 
778 778
         // if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
779
-        if (! $grp instanceof EE_Message_Template_Group) {
779
+        if ( ! $grp instanceof EE_Message_Template_Group) {
780 780
             $grp = EEM_Message_Template_Group::instance()->get_one(
781 781
                 array(
782 782
                     array(
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Queue.lib.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -603,7 +603,7 @@
 block discarded – undo
603 603
      * @param EE_Message      $message
604 604
      * @param EE_messenger    $messenger
605 605
      * @param EE_message_type $message_type
606
-     * @param                 $test_send
606
+     * @param                 boolean $test_send
607 607
      * @return bool   true means all went well, false means, not so much.
608 608
      */
609 609
     protected function _do_preview(
Please login to merge, or discard this patch.
Indentation   +690 added lines, -690 removed lines patch added patch discarded remove patch
@@ -14,694 +14,694 @@
 block discarded – undo
14 14
 {
15 15
 
16 16
 
17
-    /**
18
-     * @type    string  reference for sending action
19
-     */
20
-    const action_sending = 'sending';
21
-
22
-    /**
23
-     * @type    string  reference for generation action
24
-     */
25
-    const action_generating = 'generation';
26
-
27
-
28
-    /**
29
-     * @type EE_Message_Repository $_message_repository
30
-     */
31
-    protected $_message_repository;
32
-
33
-    /**
34
-     * Sets the limit of how many messages are generated per process.
35
-     *
36
-     * @type int
37
-     */
38
-    protected $_batch_count;
39
-
40
-
41
-    /**
42
-     * This is an array of cached queue items being stored in this object.
43
-     * The array keys will be the ID of the EE_Message in the db if saved.  If the EE_Message
44
-     * is not saved to the db then its key will be an increment of "UNS" (i.e. UNS1, UNS2 etc.)
45
-     *
46
-     * @type EE_Message[]
47
-     */
48
-    protected $_cached_queue_items;
49
-
50
-    /**
51
-     * Tracks the number of unsaved queue items.
52
-     *
53
-     * @type int
54
-     */
55
-    protected $_unsaved_count = 0;
56
-
57
-    /**
58
-     * used to record if a do_messenger_hooks has already been called for a message type.  This prevents multiple
59
-     * hooks getting fired if users have setup their action/filter hooks to prevent duplicate calls.
60
-     *
61
-     * @type array
62
-     */
63
-    protected $_did_hook = array();
64
-
65
-
66
-    /**
67
-     * Constructor.
68
-     * Setup all the initial properties and load a EE_Message_Repository.
69
-     *
70
-     * @param \EE_Message_Repository $message_repository
71
-     */
72
-    public function __construct(EE_Message_Repository $message_repository)
73
-    {
74
-        $this->_batch_count        = apply_filters('FHEE__EE_Messages_Queue___batch_count', 50);
75
-        $this->_message_repository = $message_repository;
76
-    }
77
-
78
-
79
-    /**
80
-     * Add a EE_Message object to the queue
81
-     *
82
-     * @param EE_Message $message
83
-     * @param array      $data         This will be an array of data to attach to the object in the repository.  If the
84
-     *                                 object is persisted, this data will be saved on an extra_meta object related to
85
-     *                                 EE_Message.
86
-     * @param  bool      $preview      Whether this EE_Message represents a preview or not.
87
-     * @param  bool      $test_send    This indicates whether to do a test send instead of actual send. A test send will
88
-     *                                 use the messenger send method but typically is based on preview data.
89
-     * @return bool          Whether the message was successfully added to the repository or not.
90
-     */
91
-    public function add(EE_Message $message, $data = array(), $preview = false, $test_send = false)
92
-    {
93
-        $data['preview']   = $preview;
94
-        $data['test_send'] = $test_send;
95
-        return $this->_message_repository->add($message, $data);
96
-    }
97
-
98
-
99
-    /**
100
-     * Removes EE_Message from _queue that matches the given EE_Message if the pointer is on a matching EE_Message
101
-     *
102
-     * @param EE_Message $message The message to detach from the queue
103
-     * @param bool       $persist This flag indicates whether to attempt to delete the object from the db as well.
104
-     * @return bool
105
-     */
106
-    public function remove(EE_Message $message, $persist = false)
107
-    {
108
-        if ($persist && $this->_message_repository->current() !== $message) {
109
-            // get pointer on right message
110
-            if ($this->_message_repository->has($message)) {
111
-                $this->_message_repository->rewind();
112
-                while ($this->_message_repository->valid()) {
113
-                    if ($this->_message_repository->current() === $message) {
114
-                        break;
115
-                    }
116
-                    $this->_message_repository->next();
117
-                }
118
-            } else {
119
-                return false;
120
-            }
121
-        }
122
-        return $persist ? $this->_message_repository->delete() : $this->_message_repository->remove($message);
123
-    }
124
-
125
-
126
-    /**
127
-     * Persists all queued EE_Message objects to the db.
128
-     *
129
-     * @param bool $do_hooks_only       @see EE_Message_Repository::saveAll
130
-     * @return array @see EE_Messages_Repository::saveAll() for return values.
131
-     */
132
-    public function save($do_hooks_only = false)
133
-    {
134
-        return $this->_message_repository->saveAll($do_hooks_only);
135
-    }
136
-
137
-
138
-    /**
139
-     * @return EE_Message_Repository
140
-     */
141
-    public function get_message_repository()
142
-    {
143
-        return $this->_message_repository;
144
-    }
145
-
146
-
147
-    /**
148
-     * This does the following things:
149
-     * 1. Checks if there is a lock on generation (prevents race conditions).  If there is a lock then exits (return
150
-     * false).
151
-     * 2. If no lock, sets lock, then retrieves a batch of non-generated EE_Message objects and adds to queue
152
-     * 3. Returns bool.  True = batch ready.  False = no batch ready (or nothing available for generation).
153
-     * Note: Callers should make sure they release the lock otherwise batch generation will be prevented from
154
-     * continuing. The lock is on a transient that is set to expire after one hour as a fallback in case locks are not
155
-     * removed.
156
-     *
157
-     * @return bool  true if successfully retrieved batch, false no batch ready.
158
-     */
159
-    public function get_batch_to_generate()
160
-    {
161
-        if ($this->is_locked(EE_Messages_Queue::action_generating)) {
162
-            return false;
163
-        }
164
-
165
-        // lock batch generation to prevent race conditions.
166
-        $this->lock_queue(EE_Messages_Queue::action_generating);
167
-
168
-        $query_args = array(
169
-            // key 0 = where conditions
170
-            0          => array('STS_ID' => EEM_Message::status_incomplete),
171
-            'order_by' => $this->_get_priority_orderby(),
172
-            'limit'    => $this->_batch_count,
173
-        );
174
-        $messages   = EEM_Message::instance()->get_all($query_args);
175
-
176
-        if (! $messages) {
177
-            return false; // nothing to generate
178
-        }
179
-
180
-        foreach ($messages as $message) {
181
-            if ($message instanceof EE_Message) {
182
-                $data = $message->all_extra_meta_array();
183
-                $this->add($message, $data);
184
-            }
185
-        }
186
-        return true;
187
-    }
188
-
189
-
190
-    /**
191
-     * This does the following things:
192
-     * 1. Checks if there is a lock on sending (prevents race conditions).  If there is a lock then exits (return
193
-     * false).
194
-     * 2. Grabs the allowed number of messages to send for the rate_limit.  If cannot send any more messages, then
195
-     * return false.
196
-     * 2. If no lock, sets lock, then retrieves a batch of EE_Message objects, adds to queue and triggers execution.
197
-     * 3. On success or unsuccessful send, sets status appropriately.
198
-     * 4. Saves messages via the queue
199
-     * 5. Releases lock.
200
-     *
201
-     * @return bool  true on success, false if something preventing sending (i.e. lock set).  Note: true does not
202
-     *               necessarily mean that all messages were successfully sent.  It just means that this method
203
-     *               successfully completed. On true, client may want to call $this->count_STS_in_queue(
204
-     *               EEM_Message::status_failed ) to see if any failed EE_Message objects.  Each failed message object
205
-     *               will also have a saved error message on it to assist with notifying user.
206
-     */
207
-    public function get_to_send_batch_and_send()
208
-    {
209
-        $rate_limit = $this->get_rate_limit();
210
-        if ($rate_limit < 1
211
-            || $this->is_locked(EE_Messages_Queue::action_sending)) {
212
-            return false;
213
-        }
214
-
215
-        $this->lock_queue(EE_Messages_Queue::action_sending);
216
-
217
-        $batch = $this->_batch_count < $rate_limit ? $this->_batch_count : $rate_limit;
218
-
219
-        $query_args = array(
220
-            // key 0 = where conditions
221
-            0          => array('STS_ID' => array('IN', EEM_Message::instance()->stati_indicating_to_send())),
222
-            'order_by' => $this->_get_priority_orderby(),
223
-            'limit'    => $batch,
224
-        );
225
-
226
-        $messages_to_send = EEM_Message::instance()->get_all($query_args);
227
-
228
-
229
-        // any to send?
230
-        if (! $messages_to_send) {
231
-            $this->unlock_queue(EE_Messages_Queue::action_sending);
232
-            return false;
233
-        }
234
-
235
-        $queue_count = 0;
236
-
237
-        // add to queue.
238
-        foreach ($messages_to_send as $message) {
239
-            if ($message instanceof EE_Message) {
240
-                $queue_count++;
241
-                $this->add($message);
242
-            }
243
-        }
244
-
245
-        // send messages  (this also updates the rate limit)
246
-        $this->execute();
247
-
248
-        // release lock
249
-        $this->unlock_queue(EE_Messages_Queue::action_sending);
250
-        // update rate limit
251
-        $this->set_rate_limit($queue_count);
252
-        return true;
253
-    }
254
-
255
-
256
-    /**
257
-     * Locks the queue so that no other queues can call the "batch" methods.
258
-     *
259
-     * @param   string $type The type of queue being locked.
260
-     */
261
-    public function lock_queue($type = EE_Messages_Queue::action_generating)
262
-    {
263
-        update_option($this->_get_lock_key($type), $this->_get_lock_expiry($type));
264
-    }
265
-
266
-
267
-    /**
268
-     * Unlocks the queue so that batch methods can be used.
269
-     *
270
-     * @param   string $type The type of queue being unlocked.
271
-     */
272
-    public function unlock_queue($type = EE_Messages_Queue::action_generating)
273
-    {
274
-        delete_option($this->_get_lock_key($type));
275
-    }
276
-
277
-
278
-    /**
279
-     * Retrieve the key used for the lock transient.
280
-     *
281
-     * @param string $type The type of lock.
282
-     * @return string
283
-     */
284
-    protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
285
-    {
286
-        return '_ee_lock_' . $type;
287
-    }
288
-
289
-
290
-    /**
291
-     * Retrieve the expiry time for the lock transient.
292
-     *
293
-     * @param string $type The type of lock
294
-     * @return int   time to expiry in seconds.
295
-     */
296
-    protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
297
-    {
298
-        return time() + (int) apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
299
-    }
300
-
301
-
302
-    /**
303
-     * Returns the key used for rate limit transient.
304
-     *
305
-     * @return string
306
-     */
307
-    protected function _get_rate_limit_key()
308
-    {
309
-        return '_ee_rate_limit';
310
-    }
311
-
312
-
313
-    /**
314
-     * Returns the rate limit expiry time.
315
-     *
316
-     * @return int
317
-     */
318
-    protected function _get_rate_limit_expiry()
319
-    {
320
-        return time() + (int) apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
321
-    }
322
-
323
-
324
-    /**
325
-     * Returns the default rate limit for sending messages.
326
-     *
327
-     * @return int
328
-     */
329
-    protected function _default_rate_limit()
330
-    {
331
-        return (int) apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
332
-    }
333
-
334
-
335
-    /**
336
-     * Return the orderby array for priority.
337
-     *
338
-     * @return array
339
-     */
340
-    protected function _get_priority_orderby()
341
-    {
342
-        return array(
343
-            'MSG_priority' => 'ASC',
344
-            'MSG_modified' => 'DESC',
345
-        );
346
-    }
347
-
348
-
349
-    /**
350
-     * Returns whether batch methods are "locked" or not, and if models an currently be used to query the database.
351
-     * Return true when batch methods should not be used; returns false when they can be.
352
-     *
353
-     * @param  string $type The type of lock being checked for.
354
-     * @return bool
355
-     */
356
-    public function is_locked($type = EE_Messages_Queue::action_generating)
357
-    {
358
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
359
-            return true;
360
-        }
361
-        $lock = (int) get_option($this->_get_lock_key($type), 0);
362
-        /**
363
-         * This filters the default is_locked behaviour.
364
-         */
365
-        $is_locked = filter_var(
366
-            apply_filters(
367
-                'FHEE__EE_Messages_Queue__is_locked',
368
-                $lock > time(),
369
-                $this
370
-            ),
371
-            FILTER_VALIDATE_BOOLEAN
372
-        );
373
-
374
-        /**
375
-         * @see usage of this filter in EE_Messages_Queue::initiate_request_by_priority() method.
376
-         *            Also implemented here because messages processed on the same request should not have any locks applied.
377
-         */
378
-        if (apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
379
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
380
-        ) {
381
-            $is_locked = false;
382
-        }
383
-
384
-
385
-        return $is_locked;
386
-    }
387
-
388
-
389
-    /**
390
-     * Retrieves the rate limit that may be cached as a transient.
391
-     * If the rate limit is not set, then this sets the default rate limit and expiry and returns it.
392
-     *
393
-     * @param bool $return_expiry  If true then return the expiry time not the rate_limit.
394
-     * @return int
395
-     */
396
-    protected function get_rate_limit($return_expiry = false)
397
-    {
398
-        $stored_rate_info = get_option($this->_get_rate_limit_key(), array());
399
-        $rate_limit = isset($stored_rate_info[0])
400
-            ? (int) $stored_rate_info[0]
401
-            : 0;
402
-        $expiry = isset($stored_rate_info[1])
403
-            ? (int) $stored_rate_info[1]
404
-            : 0;
405
-        // set the default for tracking?
406
-        if (empty($stored_rate_info) || time() > $expiry) {
407
-            $expiry = $this->_get_rate_limit_expiry();
408
-            $rate_limit = $this->_default_rate_limit();
409
-            update_option($this->_get_rate_limit_key(), array($rate_limit, $expiry));
410
-        }
411
-        return $return_expiry ? $expiry : $rate_limit;
412
-    }
413
-
414
-
415
-    /**
416
-     * This updates existing rate limit with the new limit which is the old minus the batch.
417
-     *
418
-     * @param int $batch_completed This sets the new rate limit based on the given batch that was completed.
419
-     */
420
-    protected function set_rate_limit($batch_completed)
421
-    {
422
-        // first get the most up to date rate limit (in case its expired and reset)
423
-        $rate_limit = $this->get_rate_limit();
424
-        $expiry = $this->get_rate_limit(true);
425
-        $new_limit  = $rate_limit - $batch_completed;
426
-        // updating the transient option directly to avoid resetting the expiry.
427
-
428
-        update_option($this->_get_rate_limit_key(), array($new_limit, $expiry));
429
-    }
430
-
431
-
432
-    /**
433
-     * This method checks the queue for ANY EE_Message objects with a priority matching the given priority passed in.
434
-     * If that exists, then we immediately initiate a non-blocking request to do the requested action type.
435
-     * Note: Keep in mind that there is the possibility that the request will not execute if there is already another
436
-     * request running on a queue for the given task.
437
-     *
438
-     * @param string $task     This indicates what type of request is going to be initiated.
439
-     * @param int    $priority This indicates the priority that triggers initiating the request.
440
-     */
441
-    public function initiate_request_by_priority($task = 'generate', $priority = EEM_Message::priority_high)
442
-    {
443
-        // determine what status is matched with the priority as part of the trigger conditions.
444
-        $status = $task == 'generate'
445
-            ? EEM_Message::status_incomplete
446
-            : EEM_Message::instance()->stati_indicating_to_send();
447
-        // always make sure we save because either this will get executed immediately on a separate request
448
-        // or remains in the queue for the regularly scheduled queue batch.
449
-        $this->save();
450
-        /**
451
-         * This filter/option allows users to override processing of messages on separate requests and instead have everything
452
-         * happen on the same request.  If this is utilized remember:
453
-         * - message priorities don't matter
454
-         * - existing unprocessed messages in the queue will not get processed unless manually triggered.
455
-         * - things will be perceived to take longer to happen for end users (i.e. registrations) because of the additional
456
-         *   processing happening on the same request.
457
-         * - any race condition protection (locks) are removed because they don't apply when things are processed on
458
-         *   the same request.
459
-         */
460
-        if (apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
461
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
462
-        ) {
463
-            $messages_processor = EE_Registry::instance()->load_lib('Messages_Processor');
464
-            if ($messages_processor instanceof EE_Messages_Processor) {
465
-                return $messages_processor->process_immediately_from_queue($this);
466
-            }
467
-            // if we get here then that means the messages processor couldn't be loaded so messages will just remain
468
-            // queued for manual triggering by end user.
469
-        }
470
-
471
-        if ($this->_message_repository->count_by_priority_and_status($priority, $status)) {
472
-            EE_Messages_Scheduler::initiate_scheduled_non_blocking_request($task);
473
-        }
474
-    }
475
-
476
-
477
-    /**
478
-     *  Loops through the EE_Message objects in the _queue and calls the messenger send methods for each message.
479
-     *
480
-     * @param   bool     $save                    Used to indicate whether to save the message queue after sending
481
-     *                                            (default will save).
482
-     * @param   mixed    $sending_messenger       (optional) When the sending messenger is different than
483
-     *                                            what is on the EE_Message object in the queue.
484
-     *                                            For instance, showing the browser view of an email message,
485
-     *                                            or giving a pdf generated view of an html document.
486
-     *                                            This should be an instance of EE_messenger but if you call this
487
-     *                                            method
488
-     *                                            intending it to be a sending messenger but a valid one could not be
489
-     *                                            retrieved then send in an instance of EE_Error that contains the
490
-     *                                            related error message.
491
-     * @param   bool|int $by_priority             When set, this indicates that only messages
492
-     *                                            matching the given priority should be executed.
493
-     * @return int        Number of messages sent.  Note, 0 does not mean that no messages were processed.
494
-     *                                            Also, if the messenger is an request type messenger (or a preview),
495
-     *                                            its entirely possible that the messenger will exit before
496
-     */
497
-    public function execute($save = true, $sending_messenger = null, $by_priority = false)
498
-    {
499
-        $messages_sent   = 0;
500
-        $this->_did_hook = array();
501
-        $this->_message_repository->rewind();
502
-
503
-        while ($this->_message_repository->valid()) {
504
-            $error_messages = array();
505
-            /** @type EE_Message $message */
506
-            $message = $this->_message_repository->current();
507
-            // only process things that are queued for sending
508
-            if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
509
-                $this->_message_repository->next();
510
-                continue;
511
-            }
512
-            // if $by_priority is set and does not match then continue;
513
-            if ($by_priority && $by_priority != $message->priority()) {
514
-                $this->_message_repository->next();
515
-                continue;
516
-            }
517
-            // error checking
518
-            if (! $message->valid_messenger()) {
519
-                $error_messages[] = sprintf(
520
-                    __('The %s messenger is not active at time of sending.', 'event_espresso'),
521
-                    $message->messenger()
522
-                );
523
-            }
524
-            if (! $message->valid_message_type()) {
525
-                $error_messages[] = sprintf(
526
-                    __('The %s message type is not active at the time of sending.', 'event_espresso'),
527
-                    $message->message_type()
528
-                );
529
-            }
530
-            // if there was supposed to be a sending messenger for this message, but it was invalid/inactive,
531
-            // then it will instead be an EE_Error object, so let's check for that
532
-            if ($sending_messenger instanceof EE_Error) {
533
-                $error_messages[] = $sending_messenger->getMessage();
534
-            }
535
-            // if there are no errors, then let's process the message
536
-            if (empty($error_messages)) {
537
-                if ($save) {
538
-                    $message->set_messenger_is_executing();
539
-                }
540
-                if ($this->_process_message($message, $sending_messenger)) {
541
-                    $messages_sent++;
542
-                }
543
-            }
544
-            $this->_set_error_message($message, $error_messages);
545
-            // add modified time
546
-            $message->set_modified(time());
547
-            // we save each message after its processed to make sure its status persists in case PHP times-out or runs
548
-            // out of memory. @see https://events.codebasehq.com/projects/event-espresso/tickets/10281
549
-            if ($save) {
550
-                $message->save();
551
-            }
552
-
553
-            $this->_message_repository->next();
554
-        }
555
-        if ($save) {
556
-            $this->save(true);
557
-        }
558
-        return $messages_sent;
559
-    }
560
-
561
-
562
-    /**
563
-     * _process_message
564
-     *
565
-     * @param EE_Message $message
566
-     * @param mixed      $sending_messenger (optional)
567
-     * @return bool
568
-     */
569
-    protected function _process_message(EE_Message $message, $sending_messenger = null)
570
-    {
571
-        // these *should* have been validated in the execute() method above
572
-        $messenger    = $message->messenger_object();
573
-        $message_type = $message->message_type_object();
574
-        // do actions for sending messenger if it differs from generating messenger and swap values.
575
-        if ($sending_messenger instanceof EE_messenger
576
-            && $messenger instanceof EE_messenger
577
-            && $sending_messenger->name != $messenger->name
578
-        ) {
579
-            $messenger->do_secondary_messenger_hooks($sending_messenger->name);
580
-            $messenger = $sending_messenger;
581
-        }
582
-        // send using messenger, but double check objects
583
-        if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
584
-            // set hook for message type (but only if not using another messenger to send).
585
-            if (! isset($this->_did_hook[ $message_type->name ])) {
586
-                $message_type->do_messenger_hooks($messenger);
587
-                $this->_did_hook[ $message_type->name ] = 1;
588
-            }
589
-            // if preview then use preview method
590
-            return $this->_message_repository->is_preview()
591
-                ? $this->_do_preview($message, $messenger, $message_type, $this->_message_repository->is_test_send())
592
-                : $this->_do_send($message, $messenger, $message_type);
593
-        }
594
-        return false;
595
-    }
596
-
597
-
598
-    /**
599
-     * The intention of this method is to count how many EE_Message objects
600
-     * are in the queue with a given status.
601
-     * Example usage:
602
-     * After a caller calls the "EE_Message_Queue::execute()" method, the caller can check if there were any failed
603
-     * sends by calling $queue->count_STS_in_queue( EEM_Message_Queue::status_failed ).
604
-     *
605
-     * @param array|string $status Stati to check for in queue
606
-     * @return int  Count of EE_Message's matching the given status.
607
-     */
608
-    public function count_STS_in_queue($status)
609
-    {
610
-        $count  = 0;
611
-        $status = is_array($status) ? $status : array($status);
612
-        $this->_message_repository->rewind();
613
-        foreach ($this->_message_repository as $message) {
614
-            if (in_array($message->STS_ID(), $status)) {
615
-                $count++;
616
-            }
617
-        }
618
-        return $count;
619
-    }
620
-
621
-
622
-    /**
623
-     * Executes the get_preview method on the provided messenger.
624
-     *
625
-     * @param EE_Message      $message
626
-     * @param EE_messenger    $messenger
627
-     * @param EE_message_type $message_type
628
-     * @param                 $test_send
629
-     * @return bool   true means all went well, false means, not so much.
630
-     */
631
-    protected function _do_preview(
632
-        EE_Message $message,
633
-        EE_messenger $messenger,
634
-        EE_message_type $message_type,
635
-        $test_send
636
-    ) {
637
-        if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
638
-            if (! $test_send) {
639
-                $message->set_content($preview);
640
-            }
641
-            $message->set_STS_ID(EEM_Message::status_sent);
642
-            return true;
643
-        } else {
644
-            $message->set_STS_ID(EEM_Message::status_failed);
645
-            return false;
646
-        }
647
-    }
648
-
649
-
650
-    /**
651
-     * Executes the send method on the provided messenger
652
-     * EE_Messengers are expected to:
653
-     * - return true if the send was successful.
654
-     * - return false if the send was unsuccessful but can be tried again.
655
-     * - throw an Exception if the send was unsuccessful and cannot be tried again.
656
-     *
657
-     * @param EE_Message      $message
658
-     * @param EE_messenger    $messenger
659
-     * @param EE_message_type $message_type
660
-     * @return bool true means all went well, false means, not so much.
661
-     */
662
-    protected function _do_send(EE_Message $message, EE_messenger $messenger, EE_message_type $message_type)
663
-    {
664
-        try {
665
-            if ($messenger->send_message($message, $message_type)) {
666
-                $message->set_STS_ID(EEM_Message::status_sent);
667
-                return true;
668
-            } else {
669
-                $message->set_STS_ID(EEM_Message::status_retry);
670
-                return false;
671
-            }
672
-        } catch (SendMessageException $e) {
673
-            $message->set_STS_ID(EEM_Message::status_failed);
674
-            $message->set_error_message($e->getMessage());
675
-            return false;
676
-        }
677
-    }
678
-
679
-
680
-    /**
681
-     * This sets any necessary error messages on the message object and its status to failed.
682
-     *
683
-     * @param EE_Message $message
684
-     * @param array      $error_messages the response from the messenger.
685
-     */
686
-    protected function _set_error_message(EE_Message $message, $error_messages)
687
-    {
688
-        $error_messages = (array) $error_messages;
689
-        if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
690
-            $notices          = EE_Error::has_notices();
691
-            $error_messages[] = __(
692
-                'Messenger and Message Type were valid and active, but the messenger send method failed.',
693
-                'event_espresso'
694
-            );
695
-            if ($notices === 1) {
696
-                $notices           = EE_Error::get_vanilla_notices();
697
-                $notices['errors'] = isset($notices['errors']) ? $notices['errors'] : array();
698
-                $error_messages[]  = implode("\n", $notices['errors']);
699
-            }
700
-        }
701
-        if (count($error_messages) > 0) {
702
-            $msg = __('Message was not executed successfully.', 'event_espresso');
703
-            $msg = $msg . "\n" . implode("\n", $error_messages);
704
-            $message->set_error_message($msg);
705
-        }
706
-    }
17
+	/**
18
+	 * @type    string  reference for sending action
19
+	 */
20
+	const action_sending = 'sending';
21
+
22
+	/**
23
+	 * @type    string  reference for generation action
24
+	 */
25
+	const action_generating = 'generation';
26
+
27
+
28
+	/**
29
+	 * @type EE_Message_Repository $_message_repository
30
+	 */
31
+	protected $_message_repository;
32
+
33
+	/**
34
+	 * Sets the limit of how many messages are generated per process.
35
+	 *
36
+	 * @type int
37
+	 */
38
+	protected $_batch_count;
39
+
40
+
41
+	/**
42
+	 * This is an array of cached queue items being stored in this object.
43
+	 * The array keys will be the ID of the EE_Message in the db if saved.  If the EE_Message
44
+	 * is not saved to the db then its key will be an increment of "UNS" (i.e. UNS1, UNS2 etc.)
45
+	 *
46
+	 * @type EE_Message[]
47
+	 */
48
+	protected $_cached_queue_items;
49
+
50
+	/**
51
+	 * Tracks the number of unsaved queue items.
52
+	 *
53
+	 * @type int
54
+	 */
55
+	protected $_unsaved_count = 0;
56
+
57
+	/**
58
+	 * used to record if a do_messenger_hooks has already been called for a message type.  This prevents multiple
59
+	 * hooks getting fired if users have setup their action/filter hooks to prevent duplicate calls.
60
+	 *
61
+	 * @type array
62
+	 */
63
+	protected $_did_hook = array();
64
+
65
+
66
+	/**
67
+	 * Constructor.
68
+	 * Setup all the initial properties and load a EE_Message_Repository.
69
+	 *
70
+	 * @param \EE_Message_Repository $message_repository
71
+	 */
72
+	public function __construct(EE_Message_Repository $message_repository)
73
+	{
74
+		$this->_batch_count        = apply_filters('FHEE__EE_Messages_Queue___batch_count', 50);
75
+		$this->_message_repository = $message_repository;
76
+	}
77
+
78
+
79
+	/**
80
+	 * Add a EE_Message object to the queue
81
+	 *
82
+	 * @param EE_Message $message
83
+	 * @param array      $data         This will be an array of data to attach to the object in the repository.  If the
84
+	 *                                 object is persisted, this data will be saved on an extra_meta object related to
85
+	 *                                 EE_Message.
86
+	 * @param  bool      $preview      Whether this EE_Message represents a preview or not.
87
+	 * @param  bool      $test_send    This indicates whether to do a test send instead of actual send. A test send will
88
+	 *                                 use the messenger send method but typically is based on preview data.
89
+	 * @return bool          Whether the message was successfully added to the repository or not.
90
+	 */
91
+	public function add(EE_Message $message, $data = array(), $preview = false, $test_send = false)
92
+	{
93
+		$data['preview']   = $preview;
94
+		$data['test_send'] = $test_send;
95
+		return $this->_message_repository->add($message, $data);
96
+	}
97
+
98
+
99
+	/**
100
+	 * Removes EE_Message from _queue that matches the given EE_Message if the pointer is on a matching EE_Message
101
+	 *
102
+	 * @param EE_Message $message The message to detach from the queue
103
+	 * @param bool       $persist This flag indicates whether to attempt to delete the object from the db as well.
104
+	 * @return bool
105
+	 */
106
+	public function remove(EE_Message $message, $persist = false)
107
+	{
108
+		if ($persist && $this->_message_repository->current() !== $message) {
109
+			// get pointer on right message
110
+			if ($this->_message_repository->has($message)) {
111
+				$this->_message_repository->rewind();
112
+				while ($this->_message_repository->valid()) {
113
+					if ($this->_message_repository->current() === $message) {
114
+						break;
115
+					}
116
+					$this->_message_repository->next();
117
+				}
118
+			} else {
119
+				return false;
120
+			}
121
+		}
122
+		return $persist ? $this->_message_repository->delete() : $this->_message_repository->remove($message);
123
+	}
124
+
125
+
126
+	/**
127
+	 * Persists all queued EE_Message objects to the db.
128
+	 *
129
+	 * @param bool $do_hooks_only       @see EE_Message_Repository::saveAll
130
+	 * @return array @see EE_Messages_Repository::saveAll() for return values.
131
+	 */
132
+	public function save($do_hooks_only = false)
133
+	{
134
+		return $this->_message_repository->saveAll($do_hooks_only);
135
+	}
136
+
137
+
138
+	/**
139
+	 * @return EE_Message_Repository
140
+	 */
141
+	public function get_message_repository()
142
+	{
143
+		return $this->_message_repository;
144
+	}
145
+
146
+
147
+	/**
148
+	 * This does the following things:
149
+	 * 1. Checks if there is a lock on generation (prevents race conditions).  If there is a lock then exits (return
150
+	 * false).
151
+	 * 2. If no lock, sets lock, then retrieves a batch of non-generated EE_Message objects and adds to queue
152
+	 * 3. Returns bool.  True = batch ready.  False = no batch ready (or nothing available for generation).
153
+	 * Note: Callers should make sure they release the lock otherwise batch generation will be prevented from
154
+	 * continuing. The lock is on a transient that is set to expire after one hour as a fallback in case locks are not
155
+	 * removed.
156
+	 *
157
+	 * @return bool  true if successfully retrieved batch, false no batch ready.
158
+	 */
159
+	public function get_batch_to_generate()
160
+	{
161
+		if ($this->is_locked(EE_Messages_Queue::action_generating)) {
162
+			return false;
163
+		}
164
+
165
+		// lock batch generation to prevent race conditions.
166
+		$this->lock_queue(EE_Messages_Queue::action_generating);
167
+
168
+		$query_args = array(
169
+			// key 0 = where conditions
170
+			0          => array('STS_ID' => EEM_Message::status_incomplete),
171
+			'order_by' => $this->_get_priority_orderby(),
172
+			'limit'    => $this->_batch_count,
173
+		);
174
+		$messages   = EEM_Message::instance()->get_all($query_args);
175
+
176
+		if (! $messages) {
177
+			return false; // nothing to generate
178
+		}
179
+
180
+		foreach ($messages as $message) {
181
+			if ($message instanceof EE_Message) {
182
+				$data = $message->all_extra_meta_array();
183
+				$this->add($message, $data);
184
+			}
185
+		}
186
+		return true;
187
+	}
188
+
189
+
190
+	/**
191
+	 * This does the following things:
192
+	 * 1. Checks if there is a lock on sending (prevents race conditions).  If there is a lock then exits (return
193
+	 * false).
194
+	 * 2. Grabs the allowed number of messages to send for the rate_limit.  If cannot send any more messages, then
195
+	 * return false.
196
+	 * 2. If no lock, sets lock, then retrieves a batch of EE_Message objects, adds to queue and triggers execution.
197
+	 * 3. On success or unsuccessful send, sets status appropriately.
198
+	 * 4. Saves messages via the queue
199
+	 * 5. Releases lock.
200
+	 *
201
+	 * @return bool  true on success, false if something preventing sending (i.e. lock set).  Note: true does not
202
+	 *               necessarily mean that all messages were successfully sent.  It just means that this method
203
+	 *               successfully completed. On true, client may want to call $this->count_STS_in_queue(
204
+	 *               EEM_Message::status_failed ) to see if any failed EE_Message objects.  Each failed message object
205
+	 *               will also have a saved error message on it to assist with notifying user.
206
+	 */
207
+	public function get_to_send_batch_and_send()
208
+	{
209
+		$rate_limit = $this->get_rate_limit();
210
+		if ($rate_limit < 1
211
+			|| $this->is_locked(EE_Messages_Queue::action_sending)) {
212
+			return false;
213
+		}
214
+
215
+		$this->lock_queue(EE_Messages_Queue::action_sending);
216
+
217
+		$batch = $this->_batch_count < $rate_limit ? $this->_batch_count : $rate_limit;
218
+
219
+		$query_args = array(
220
+			// key 0 = where conditions
221
+			0          => array('STS_ID' => array('IN', EEM_Message::instance()->stati_indicating_to_send())),
222
+			'order_by' => $this->_get_priority_orderby(),
223
+			'limit'    => $batch,
224
+		);
225
+
226
+		$messages_to_send = EEM_Message::instance()->get_all($query_args);
227
+
228
+
229
+		// any to send?
230
+		if (! $messages_to_send) {
231
+			$this->unlock_queue(EE_Messages_Queue::action_sending);
232
+			return false;
233
+		}
234
+
235
+		$queue_count = 0;
236
+
237
+		// add to queue.
238
+		foreach ($messages_to_send as $message) {
239
+			if ($message instanceof EE_Message) {
240
+				$queue_count++;
241
+				$this->add($message);
242
+			}
243
+		}
244
+
245
+		// send messages  (this also updates the rate limit)
246
+		$this->execute();
247
+
248
+		// release lock
249
+		$this->unlock_queue(EE_Messages_Queue::action_sending);
250
+		// update rate limit
251
+		$this->set_rate_limit($queue_count);
252
+		return true;
253
+	}
254
+
255
+
256
+	/**
257
+	 * Locks the queue so that no other queues can call the "batch" methods.
258
+	 *
259
+	 * @param   string $type The type of queue being locked.
260
+	 */
261
+	public function lock_queue($type = EE_Messages_Queue::action_generating)
262
+	{
263
+		update_option($this->_get_lock_key($type), $this->_get_lock_expiry($type));
264
+	}
265
+
266
+
267
+	/**
268
+	 * Unlocks the queue so that batch methods can be used.
269
+	 *
270
+	 * @param   string $type The type of queue being unlocked.
271
+	 */
272
+	public function unlock_queue($type = EE_Messages_Queue::action_generating)
273
+	{
274
+		delete_option($this->_get_lock_key($type));
275
+	}
276
+
277
+
278
+	/**
279
+	 * Retrieve the key used for the lock transient.
280
+	 *
281
+	 * @param string $type The type of lock.
282
+	 * @return string
283
+	 */
284
+	protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
285
+	{
286
+		return '_ee_lock_' . $type;
287
+	}
288
+
289
+
290
+	/**
291
+	 * Retrieve the expiry time for the lock transient.
292
+	 *
293
+	 * @param string $type The type of lock
294
+	 * @return int   time to expiry in seconds.
295
+	 */
296
+	protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
297
+	{
298
+		return time() + (int) apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
299
+	}
300
+
301
+
302
+	/**
303
+	 * Returns the key used for rate limit transient.
304
+	 *
305
+	 * @return string
306
+	 */
307
+	protected function _get_rate_limit_key()
308
+	{
309
+		return '_ee_rate_limit';
310
+	}
311
+
312
+
313
+	/**
314
+	 * Returns the rate limit expiry time.
315
+	 *
316
+	 * @return int
317
+	 */
318
+	protected function _get_rate_limit_expiry()
319
+	{
320
+		return time() + (int) apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
321
+	}
322
+
323
+
324
+	/**
325
+	 * Returns the default rate limit for sending messages.
326
+	 *
327
+	 * @return int
328
+	 */
329
+	protected function _default_rate_limit()
330
+	{
331
+		return (int) apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
332
+	}
333
+
334
+
335
+	/**
336
+	 * Return the orderby array for priority.
337
+	 *
338
+	 * @return array
339
+	 */
340
+	protected function _get_priority_orderby()
341
+	{
342
+		return array(
343
+			'MSG_priority' => 'ASC',
344
+			'MSG_modified' => 'DESC',
345
+		);
346
+	}
347
+
348
+
349
+	/**
350
+	 * Returns whether batch methods are "locked" or not, and if models an currently be used to query the database.
351
+	 * Return true when batch methods should not be used; returns false when they can be.
352
+	 *
353
+	 * @param  string $type The type of lock being checked for.
354
+	 * @return bool
355
+	 */
356
+	public function is_locked($type = EE_Messages_Queue::action_generating)
357
+	{
358
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
359
+			return true;
360
+		}
361
+		$lock = (int) get_option($this->_get_lock_key($type), 0);
362
+		/**
363
+		 * This filters the default is_locked behaviour.
364
+		 */
365
+		$is_locked = filter_var(
366
+			apply_filters(
367
+				'FHEE__EE_Messages_Queue__is_locked',
368
+				$lock > time(),
369
+				$this
370
+			),
371
+			FILTER_VALIDATE_BOOLEAN
372
+		);
373
+
374
+		/**
375
+		 * @see usage of this filter in EE_Messages_Queue::initiate_request_by_priority() method.
376
+		 *            Also implemented here because messages processed on the same request should not have any locks applied.
377
+		 */
378
+		if (apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
379
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
380
+		) {
381
+			$is_locked = false;
382
+		}
383
+
384
+
385
+		return $is_locked;
386
+	}
387
+
388
+
389
+	/**
390
+	 * Retrieves the rate limit that may be cached as a transient.
391
+	 * If the rate limit is not set, then this sets the default rate limit and expiry and returns it.
392
+	 *
393
+	 * @param bool $return_expiry  If true then return the expiry time not the rate_limit.
394
+	 * @return int
395
+	 */
396
+	protected function get_rate_limit($return_expiry = false)
397
+	{
398
+		$stored_rate_info = get_option($this->_get_rate_limit_key(), array());
399
+		$rate_limit = isset($stored_rate_info[0])
400
+			? (int) $stored_rate_info[0]
401
+			: 0;
402
+		$expiry = isset($stored_rate_info[1])
403
+			? (int) $stored_rate_info[1]
404
+			: 0;
405
+		// set the default for tracking?
406
+		if (empty($stored_rate_info) || time() > $expiry) {
407
+			$expiry = $this->_get_rate_limit_expiry();
408
+			$rate_limit = $this->_default_rate_limit();
409
+			update_option($this->_get_rate_limit_key(), array($rate_limit, $expiry));
410
+		}
411
+		return $return_expiry ? $expiry : $rate_limit;
412
+	}
413
+
414
+
415
+	/**
416
+	 * This updates existing rate limit with the new limit which is the old minus the batch.
417
+	 *
418
+	 * @param int $batch_completed This sets the new rate limit based on the given batch that was completed.
419
+	 */
420
+	protected function set_rate_limit($batch_completed)
421
+	{
422
+		// first get the most up to date rate limit (in case its expired and reset)
423
+		$rate_limit = $this->get_rate_limit();
424
+		$expiry = $this->get_rate_limit(true);
425
+		$new_limit  = $rate_limit - $batch_completed;
426
+		// updating the transient option directly to avoid resetting the expiry.
427
+
428
+		update_option($this->_get_rate_limit_key(), array($new_limit, $expiry));
429
+	}
430
+
431
+
432
+	/**
433
+	 * This method checks the queue for ANY EE_Message objects with a priority matching the given priority passed in.
434
+	 * If that exists, then we immediately initiate a non-blocking request to do the requested action type.
435
+	 * Note: Keep in mind that there is the possibility that the request will not execute if there is already another
436
+	 * request running on a queue for the given task.
437
+	 *
438
+	 * @param string $task     This indicates what type of request is going to be initiated.
439
+	 * @param int    $priority This indicates the priority that triggers initiating the request.
440
+	 */
441
+	public function initiate_request_by_priority($task = 'generate', $priority = EEM_Message::priority_high)
442
+	{
443
+		// determine what status is matched with the priority as part of the trigger conditions.
444
+		$status = $task == 'generate'
445
+			? EEM_Message::status_incomplete
446
+			: EEM_Message::instance()->stati_indicating_to_send();
447
+		// always make sure we save because either this will get executed immediately on a separate request
448
+		// or remains in the queue for the regularly scheduled queue batch.
449
+		$this->save();
450
+		/**
451
+		 * This filter/option allows users to override processing of messages on separate requests and instead have everything
452
+		 * happen on the same request.  If this is utilized remember:
453
+		 * - message priorities don't matter
454
+		 * - existing unprocessed messages in the queue will not get processed unless manually triggered.
455
+		 * - things will be perceived to take longer to happen for end users (i.e. registrations) because of the additional
456
+		 *   processing happening on the same request.
457
+		 * - any race condition protection (locks) are removed because they don't apply when things are processed on
458
+		 *   the same request.
459
+		 */
460
+		if (apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
461
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
462
+		) {
463
+			$messages_processor = EE_Registry::instance()->load_lib('Messages_Processor');
464
+			if ($messages_processor instanceof EE_Messages_Processor) {
465
+				return $messages_processor->process_immediately_from_queue($this);
466
+			}
467
+			// if we get here then that means the messages processor couldn't be loaded so messages will just remain
468
+			// queued for manual triggering by end user.
469
+		}
470
+
471
+		if ($this->_message_repository->count_by_priority_and_status($priority, $status)) {
472
+			EE_Messages_Scheduler::initiate_scheduled_non_blocking_request($task);
473
+		}
474
+	}
475
+
476
+
477
+	/**
478
+	 *  Loops through the EE_Message objects in the _queue and calls the messenger send methods for each message.
479
+	 *
480
+	 * @param   bool     $save                    Used to indicate whether to save the message queue after sending
481
+	 *                                            (default will save).
482
+	 * @param   mixed    $sending_messenger       (optional) When the sending messenger is different than
483
+	 *                                            what is on the EE_Message object in the queue.
484
+	 *                                            For instance, showing the browser view of an email message,
485
+	 *                                            or giving a pdf generated view of an html document.
486
+	 *                                            This should be an instance of EE_messenger but if you call this
487
+	 *                                            method
488
+	 *                                            intending it to be a sending messenger but a valid one could not be
489
+	 *                                            retrieved then send in an instance of EE_Error that contains the
490
+	 *                                            related error message.
491
+	 * @param   bool|int $by_priority             When set, this indicates that only messages
492
+	 *                                            matching the given priority should be executed.
493
+	 * @return int        Number of messages sent.  Note, 0 does not mean that no messages were processed.
494
+	 *                                            Also, if the messenger is an request type messenger (or a preview),
495
+	 *                                            its entirely possible that the messenger will exit before
496
+	 */
497
+	public function execute($save = true, $sending_messenger = null, $by_priority = false)
498
+	{
499
+		$messages_sent   = 0;
500
+		$this->_did_hook = array();
501
+		$this->_message_repository->rewind();
502
+
503
+		while ($this->_message_repository->valid()) {
504
+			$error_messages = array();
505
+			/** @type EE_Message $message */
506
+			$message = $this->_message_repository->current();
507
+			// only process things that are queued for sending
508
+			if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
509
+				$this->_message_repository->next();
510
+				continue;
511
+			}
512
+			// if $by_priority is set and does not match then continue;
513
+			if ($by_priority && $by_priority != $message->priority()) {
514
+				$this->_message_repository->next();
515
+				continue;
516
+			}
517
+			// error checking
518
+			if (! $message->valid_messenger()) {
519
+				$error_messages[] = sprintf(
520
+					__('The %s messenger is not active at time of sending.', 'event_espresso'),
521
+					$message->messenger()
522
+				);
523
+			}
524
+			if (! $message->valid_message_type()) {
525
+				$error_messages[] = sprintf(
526
+					__('The %s message type is not active at the time of sending.', 'event_espresso'),
527
+					$message->message_type()
528
+				);
529
+			}
530
+			// if there was supposed to be a sending messenger for this message, but it was invalid/inactive,
531
+			// then it will instead be an EE_Error object, so let's check for that
532
+			if ($sending_messenger instanceof EE_Error) {
533
+				$error_messages[] = $sending_messenger->getMessage();
534
+			}
535
+			// if there are no errors, then let's process the message
536
+			if (empty($error_messages)) {
537
+				if ($save) {
538
+					$message->set_messenger_is_executing();
539
+				}
540
+				if ($this->_process_message($message, $sending_messenger)) {
541
+					$messages_sent++;
542
+				}
543
+			}
544
+			$this->_set_error_message($message, $error_messages);
545
+			// add modified time
546
+			$message->set_modified(time());
547
+			// we save each message after its processed to make sure its status persists in case PHP times-out or runs
548
+			// out of memory. @see https://events.codebasehq.com/projects/event-espresso/tickets/10281
549
+			if ($save) {
550
+				$message->save();
551
+			}
552
+
553
+			$this->_message_repository->next();
554
+		}
555
+		if ($save) {
556
+			$this->save(true);
557
+		}
558
+		return $messages_sent;
559
+	}
560
+
561
+
562
+	/**
563
+	 * _process_message
564
+	 *
565
+	 * @param EE_Message $message
566
+	 * @param mixed      $sending_messenger (optional)
567
+	 * @return bool
568
+	 */
569
+	protected function _process_message(EE_Message $message, $sending_messenger = null)
570
+	{
571
+		// these *should* have been validated in the execute() method above
572
+		$messenger    = $message->messenger_object();
573
+		$message_type = $message->message_type_object();
574
+		// do actions for sending messenger if it differs from generating messenger and swap values.
575
+		if ($sending_messenger instanceof EE_messenger
576
+			&& $messenger instanceof EE_messenger
577
+			&& $sending_messenger->name != $messenger->name
578
+		) {
579
+			$messenger->do_secondary_messenger_hooks($sending_messenger->name);
580
+			$messenger = $sending_messenger;
581
+		}
582
+		// send using messenger, but double check objects
583
+		if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
584
+			// set hook for message type (but only if not using another messenger to send).
585
+			if (! isset($this->_did_hook[ $message_type->name ])) {
586
+				$message_type->do_messenger_hooks($messenger);
587
+				$this->_did_hook[ $message_type->name ] = 1;
588
+			}
589
+			// if preview then use preview method
590
+			return $this->_message_repository->is_preview()
591
+				? $this->_do_preview($message, $messenger, $message_type, $this->_message_repository->is_test_send())
592
+				: $this->_do_send($message, $messenger, $message_type);
593
+		}
594
+		return false;
595
+	}
596
+
597
+
598
+	/**
599
+	 * The intention of this method is to count how many EE_Message objects
600
+	 * are in the queue with a given status.
601
+	 * Example usage:
602
+	 * After a caller calls the "EE_Message_Queue::execute()" method, the caller can check if there were any failed
603
+	 * sends by calling $queue->count_STS_in_queue( EEM_Message_Queue::status_failed ).
604
+	 *
605
+	 * @param array|string $status Stati to check for in queue
606
+	 * @return int  Count of EE_Message's matching the given status.
607
+	 */
608
+	public function count_STS_in_queue($status)
609
+	{
610
+		$count  = 0;
611
+		$status = is_array($status) ? $status : array($status);
612
+		$this->_message_repository->rewind();
613
+		foreach ($this->_message_repository as $message) {
614
+			if (in_array($message->STS_ID(), $status)) {
615
+				$count++;
616
+			}
617
+		}
618
+		return $count;
619
+	}
620
+
621
+
622
+	/**
623
+	 * Executes the get_preview method on the provided messenger.
624
+	 *
625
+	 * @param EE_Message      $message
626
+	 * @param EE_messenger    $messenger
627
+	 * @param EE_message_type $message_type
628
+	 * @param                 $test_send
629
+	 * @return bool   true means all went well, false means, not so much.
630
+	 */
631
+	protected function _do_preview(
632
+		EE_Message $message,
633
+		EE_messenger $messenger,
634
+		EE_message_type $message_type,
635
+		$test_send
636
+	) {
637
+		if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
638
+			if (! $test_send) {
639
+				$message->set_content($preview);
640
+			}
641
+			$message->set_STS_ID(EEM_Message::status_sent);
642
+			return true;
643
+		} else {
644
+			$message->set_STS_ID(EEM_Message::status_failed);
645
+			return false;
646
+		}
647
+	}
648
+
649
+
650
+	/**
651
+	 * Executes the send method on the provided messenger
652
+	 * EE_Messengers are expected to:
653
+	 * - return true if the send was successful.
654
+	 * - return false if the send was unsuccessful but can be tried again.
655
+	 * - throw an Exception if the send was unsuccessful and cannot be tried again.
656
+	 *
657
+	 * @param EE_Message      $message
658
+	 * @param EE_messenger    $messenger
659
+	 * @param EE_message_type $message_type
660
+	 * @return bool true means all went well, false means, not so much.
661
+	 */
662
+	protected function _do_send(EE_Message $message, EE_messenger $messenger, EE_message_type $message_type)
663
+	{
664
+		try {
665
+			if ($messenger->send_message($message, $message_type)) {
666
+				$message->set_STS_ID(EEM_Message::status_sent);
667
+				return true;
668
+			} else {
669
+				$message->set_STS_ID(EEM_Message::status_retry);
670
+				return false;
671
+			}
672
+		} catch (SendMessageException $e) {
673
+			$message->set_STS_ID(EEM_Message::status_failed);
674
+			$message->set_error_message($e->getMessage());
675
+			return false;
676
+		}
677
+	}
678
+
679
+
680
+	/**
681
+	 * This sets any necessary error messages on the message object and its status to failed.
682
+	 *
683
+	 * @param EE_Message $message
684
+	 * @param array      $error_messages the response from the messenger.
685
+	 */
686
+	protected function _set_error_message(EE_Message $message, $error_messages)
687
+	{
688
+		$error_messages = (array) $error_messages;
689
+		if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
690
+			$notices          = EE_Error::has_notices();
691
+			$error_messages[] = __(
692
+				'Messenger and Message Type were valid and active, but the messenger send method failed.',
693
+				'event_espresso'
694
+			);
695
+			if ($notices === 1) {
696
+				$notices           = EE_Error::get_vanilla_notices();
697
+				$notices['errors'] = isset($notices['errors']) ? $notices['errors'] : array();
698
+				$error_messages[]  = implode("\n", $notices['errors']);
699
+			}
700
+		}
701
+		if (count($error_messages) > 0) {
702
+			$msg = __('Message was not executed successfully.', 'event_espresso');
703
+			$msg = $msg . "\n" . implode("\n", $error_messages);
704
+			$message->set_error_message($msg);
705
+		}
706
+	}
707 707
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -171,9 +171,9 @@  discard block
 block discarded – undo
171 171
             'order_by' => $this->_get_priority_orderby(),
172 172
             'limit'    => $this->_batch_count,
173 173
         );
174
-        $messages   = EEM_Message::instance()->get_all($query_args);
174
+        $messages = EEM_Message::instance()->get_all($query_args);
175 175
 
176
-        if (! $messages) {
176
+        if ( ! $messages) {
177 177
             return false; // nothing to generate
178 178
         }
179 179
 
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 
228 228
 
229 229
         // any to send?
230
-        if (! $messages_to_send) {
230
+        if ( ! $messages_to_send) {
231 231
             $this->unlock_queue(EE_Messages_Queue::action_sending);
232 232
             return false;
233 233
         }
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
      */
284 284
     protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
285 285
     {
286
-        return '_ee_lock_' . $type;
286
+        return '_ee_lock_'.$type;
287 287
     }
288 288
 
289 289
 
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
      */
356 356
     public function is_locked($type = EE_Messages_Queue::action_generating)
357 357
     {
358
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
358
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
359 359
             return true;
360 360
         }
361 361
         $lock = (int) get_option($this->_get_lock_key($type), 0);
@@ -505,7 +505,7 @@  discard block
 block discarded – undo
505 505
             /** @type EE_Message $message */
506 506
             $message = $this->_message_repository->current();
507 507
             // only process things that are queued for sending
508
-            if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
508
+            if ( ! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
509 509
                 $this->_message_repository->next();
510 510
                 continue;
511 511
             }
@@ -515,13 +515,13 @@  discard block
 block discarded – undo
515 515
                 continue;
516 516
             }
517 517
             // error checking
518
-            if (! $message->valid_messenger()) {
518
+            if ( ! $message->valid_messenger()) {
519 519
                 $error_messages[] = sprintf(
520 520
                     __('The %s messenger is not active at time of sending.', 'event_espresso'),
521 521
                     $message->messenger()
522 522
                 );
523 523
             }
524
-            if (! $message->valid_message_type()) {
524
+            if ( ! $message->valid_message_type()) {
525 525
                 $error_messages[] = sprintf(
526 526
                     __('The %s message type is not active at the time of sending.', 'event_espresso'),
527 527
                     $message->message_type()
@@ -582,9 +582,9 @@  discard block
 block discarded – undo
582 582
         // send using messenger, but double check objects
583 583
         if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
584 584
             // set hook for message type (but only if not using another messenger to send).
585
-            if (! isset($this->_did_hook[ $message_type->name ])) {
585
+            if ( ! isset($this->_did_hook[$message_type->name])) {
586 586
                 $message_type->do_messenger_hooks($messenger);
587
-                $this->_did_hook[ $message_type->name ] = 1;
587
+                $this->_did_hook[$message_type->name] = 1;
588 588
             }
589 589
             // if preview then use preview method
590 590
             return $this->_message_repository->is_preview()
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
         $test_send
636 636
     ) {
637 637
         if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
638
-            if (! $test_send) {
638
+            if ( ! $test_send) {
639 639
                 $message->set_content($preview);
640 640
             }
641 641
             $message->set_STS_ID(EEM_Message::status_sent);
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
         }
701 701
         if (count($error_messages) > 0) {
702 702
             $msg = __('Message was not executed successfully.', 'event_espresso');
703
-            $msg = $msg . "\n" . implode("\n", $error_messages);
703
+            $msg = $msg."\n".implode("\n", $error_messages);
704 704
             $message->set_error_message($msg);
705 705
         }
706 706
     }
Please login to merge, or discard this patch.
core/db_models/fields/EE_Field_With_Model_Name.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -70,10 +70,10 @@
 block discarded – undo
70 70
         $model_names = array();
71 71
         if (is_array($this->_model_name_pointed_to)) {
72 72
             foreach ($this->_model_name_pointed_to as $model_name) {
73
-                $model_names[] = "EE_" . $model_name;
73
+                $model_names[] = "EE_".$model_name;
74 74
             }
75 75
         } else {
76
-            $model_names = array("EE_" . $this->_model_name_pointed_to);
76
+            $model_names = array("EE_".$this->_model_name_pointed_to);
77 77
         }
78 78
         return $model_names;
79 79
     }
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -8,88 +8,88 @@
 block discarded – undo
8 8
  */
9 9
 abstract class EE_Field_With_Model_Name extends EE_Model_Field_Base
10 10
 {
11
-    /**
12
-     * Usually the name of a single model. However, as in the case for custom post types,
13
-     * it can actually be an array of models
14
-     *
15
-     * @var string or array
16
-     */
17
-    protected $_model_name_pointed_to;
11
+	/**
12
+	 * Usually the name of a single model. However, as in the case for custom post types,
13
+	 * it can actually be an array of models
14
+	 *
15
+	 * @var string or array
16
+	 */
17
+	protected $_model_name_pointed_to;
18 18
 
19
-    /**
20
-     * @param string  $table_column  name fo column for field
21
-     * @param string  $nicename      should eb internationalized with __('blah','event_espresso')
22
-     * @param boolean $nullable
23
-     * @param mixed   $default_value if this is a integer field, it shoudl be an int. if it's a string field, it shoul
24
-     *                               dbe a string
25
-     * @param string  $model_name    eg 'Event','Answer','Term', etc. Basically its the model class's name without the
26
-     *                               "EEM_"
27
-     */
28
-    public function __construct($table_column, $nicename, $nullable, $default_value, $model_name)
29
-    {
30
-        $this->_model_name_pointed_to = $model_name;
31
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
32
-    }
19
+	/**
20
+	 * @param string  $table_column  name fo column for field
21
+	 * @param string  $nicename      should eb internationalized with __('blah','event_espresso')
22
+	 * @param boolean $nullable
23
+	 * @param mixed   $default_value if this is a integer field, it shoudl be an int. if it's a string field, it shoul
24
+	 *                               dbe a string
25
+	 * @param string  $model_name    eg 'Event','Answer','Term', etc. Basically its the model class's name without the
26
+	 *                               "EEM_"
27
+	 */
28
+	public function __construct($table_column, $nicename, $nullable, $default_value, $model_name)
29
+	{
30
+		$this->_model_name_pointed_to = $model_name;
31
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
32
+	}
33 33
 
34
-    /**
35
-     * Returns the name of the model(s) pointed to
36
-     *
37
-     * @deprecated since version 4.6.7
38
-     * @return mixed string or array of strings
39
-     */
40
-    public function get_model_name_pointed_to()
41
-    {
42
-        EE_Error::doing_it_wrong(
43
-            'get_model_name_pointed_to',
44
-            __(
45
-                'This method has been deprecated in favour of instead using get_model_names_pointed_to, which consistently returns an array',
46
-                'event_espresso'
47
-            ),
48
-            '4.6.7'
49
-        );
50
-        return $this->_model_name_pointed_to;
51
-    }
34
+	/**
35
+	 * Returns the name of the model(s) pointed to
36
+	 *
37
+	 * @deprecated since version 4.6.7
38
+	 * @return mixed string or array of strings
39
+	 */
40
+	public function get_model_name_pointed_to()
41
+	{
42
+		EE_Error::doing_it_wrong(
43
+			'get_model_name_pointed_to',
44
+			__(
45
+				'This method has been deprecated in favour of instead using get_model_names_pointed_to, which consistently returns an array',
46
+				'event_espresso'
47
+			),
48
+			'4.6.7'
49
+		);
50
+		return $this->_model_name_pointed_to;
51
+	}
52 52
 
53
-    /**
54
-     * Gets the model names pointed to by this field, always as an array
55
-     * (even if there's only one)
56
-     *
57
-     * @return array of model names pointed to by this field
58
-     */
59
-    public function get_model_names_pointed_to()
60
-    {
61
-        if (is_array($this->_model_name_pointed_to)) {
62
-            return $this->_model_name_pointed_to;
63
-        } else {
64
-            return array($this->_model_name_pointed_to);
65
-        }
66
-    }
53
+	/**
54
+	 * Gets the model names pointed to by this field, always as an array
55
+	 * (even if there's only one)
56
+	 *
57
+	 * @return array of model names pointed to by this field
58
+	 */
59
+	public function get_model_names_pointed_to()
60
+	{
61
+		if (is_array($this->_model_name_pointed_to)) {
62
+			return $this->_model_name_pointed_to;
63
+		} else {
64
+			return array($this->_model_name_pointed_to);
65
+		}
66
+	}
67 67
 
68
-    /**
69
-     * Returns the model's classname (eg EE_Event instead of just Event)
70
-     *
71
-     * @return array
72
-     */
73
-    public function get_model_class_names_pointed_to()
74
-    {
75
-        $model_names = array();
76
-        if (is_array($this->_model_name_pointed_to)) {
77
-            foreach ($this->_model_name_pointed_to as $model_name) {
78
-                $model_names[] = "EE_" . $model_name;
79
-            }
80
-        } else {
81
-            $model_names = array("EE_" . $this->_model_name_pointed_to);
82
-        }
83
-        return $model_names;
84
-    }
68
+	/**
69
+	 * Returns the model's classname (eg EE_Event instead of just Event)
70
+	 *
71
+	 * @return array
72
+	 */
73
+	public function get_model_class_names_pointed_to()
74
+	{
75
+		$model_names = array();
76
+		if (is_array($this->_model_name_pointed_to)) {
77
+			foreach ($this->_model_name_pointed_to as $model_name) {
78
+				$model_names[] = "EE_" . $model_name;
79
+			}
80
+		} else {
81
+			$model_names = array("EE_" . $this->_model_name_pointed_to);
82
+		}
83
+		return $model_names;
84
+	}
85 85
 
86
-    public function is_model_obj_of_type_pointed_to($model_obj_or_ID)
87
-    {
88
-        foreach ($this->get_model_class_names_pointed_to() as $model_obj_classname) {
89
-            if ($model_obj_or_ID instanceof $model_obj_classname) {
90
-                return true;
91
-            }
92
-        }
93
-        return false;
94
-    }
86
+	public function is_model_obj_of_type_pointed_to($model_obj_or_ID)
87
+	{
88
+		foreach ($this->get_model_class_names_pointed_to() as $model_obj_classname) {
89
+			if ($model_obj_or_ID instanceof $model_obj_classname) {
90
+				return true;
91
+			}
92
+		}
93
+		return false;
94
+	}
95 95
 }
Please login to merge, or discard this patch.
core/db_models/relations/EE_Model_Relation_Base.php 3 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -133,9 +133,9 @@  discard block
 block discarded – undo
133 133
 
134 134
     /**
135 135
      * @param        $other_table
136
-     * @param        $other_table_alias
136
+     * @param        string $other_table_alias
137 137
      * @param        $other_table_column
138
-     * @param        $this_table_alias
138
+     * @param        string $this_table_alias
139 139
      * @param        $this_table_join_column
140 140
      * @param string $extra_join_sql
141 141
      * @return string
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
      * Alters the $query_params to disable default where conditions, unless otherwise specified
190 190
      *
191 191
      * @param string $query_params
192
-     * @return array
192
+     * @return string
193 193
      */
194 194
     protected function _disable_default_where_conditions_on_query_param($query_params)
195 195
     {
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
      * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
207 207
      * model objects will only be soft-deleted.
208 208
      *
209
-     * @param EE_Base_Class|int|string $model_object_or_id
209
+     * @param EE_Base_Class|null $model_object_or_id
210 210
      * @param array                    $query_params
211 211
      * @return int of how many related models got deleted
212 212
      * @throws \EE_Error
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
      * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
238 238
      * model objects will only be soft-deleted.
239 239
      *
240
-     * @param EE_Base_Class|int|string $model_object_or_id
240
+     * @param EE_Base_Class|null $model_object_or_id
241 241
      * @param array                    $query_params
242 242
      * @return int of how many related models got deleted
243 243
      * @throws \EE_Error
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
         $this_table_join_column,
157 157
         $extra_join_sql = ''
158 158
     ) {
159
-        return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
159
+        return " LEFT JOIN ".$other_table." AS ".$other_table_alias." ON ".$other_table_alias.".".$other_table_column."=".$this_table_alias.".".$this_table_join_column.($extra_join_sql ? " AND $extra_join_sql" : '');
160 160
     }
161 161
 
162 162
 
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
                                                              . "."
191 191
                                                              . $this->get_this_model()->get_primary_key_field()->get_name();
192 192
         $model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
193
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
193
+        $query_params[0][$query_param_where_this_model_pk] = $model_object_id;
194 194
         return $this->get_other_model()->get_all($query_params);
195 195
     }
196 196
 
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
      */
204 204
     protected function _disable_default_where_conditions_on_query_param($query_params)
205 205
     {
206
-        if (! isset($query_params['default_where_conditions'])) {
206
+        if ( ! isset($query_params['default_where_conditions'])) {
207 207
             $query_params['default_where_conditions'] = 'none';
208 208
         }
209 209
         return $query_params;
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
                 $model_object_or_id
234 234
             );
235 235
             /* @var $model_object_or_id EE_Base_Class */
236
-            if (! $delete_is_blocked) {
236
+            if ( ! $delete_is_blocked) {
237 237
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
238 238
                 $related_model_object->delete();
239 239
                 $deleted_count++;
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
             if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
270 270
                 $this->remove_relation_to($model_object_or_id, $related_model_object);
271 271
                 $deleted_count++;
272
-                if (! $delete_is_blocked) {
272
+                if ( ! $delete_is_blocked) {
273 273
                     $related_model_object->delete_permanently();
274 274
                 } else {
275 275
                     // delete is blocked
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
                 }
279 279
             } else {
280 280
                 // its not a soft-deletable thing anyways. do the normal logic.
281
-                if (! $delete_is_blocked) {
281
+                if ( ! $delete_is_blocked) {
282 282
                     $this->remove_relation_to($model_object_or_id, $related_model_object);
283 283
                     $related_model_object->delete();
284 284
                     $deleted_count++;
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
         if ($model_object_or_id instanceof EE_Base_Class) {
303 303
             $model_object_id = $model_object_or_id->ID();
304 304
         }
305
-        if (! $model_object_id) {
305
+        if ( ! $model_object_id) {
306 306
             throw new EE_Error(sprintf(
307 307
                 __(
308 308
                     "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
Please login to merge, or discard this patch.
Indentation   +497 added lines, -497 removed lines patch added patch discarded remove patch
@@ -15,502 +15,502 @@
 block discarded – undo
15 15
  */
16 16
 abstract class EE_Model_Relation_Base implements HasSchemaInterface
17 17
 {
18
-    /**
19
-     * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
20
-     *
21
-     * @var string eg Event, Question_Group, Registration
22
-     */
23
-    private $_this_model_name;
24
-    /**
25
-     * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
26
-     *
27
-     * @var string eg Event, Question_Group, Registration
28
-     */
29
-    private $_other_model_name;
30
-
31
-    /**
32
-     * this is typically used when calling the relation models to make sure they inherit any set timezone from the
33
-     * initiating model.
34
-     *
35
-     * @var string
36
-     */
37
-    protected $_timezone;
38
-
39
-    /**
40
-     * If you try to delete "this_model", and there are related "other_models",
41
-     * and this isn't null, then abandon the deletion and add this warning.
42
-     * This effectively makes it impossible to delete "this_model" while there are
43
-     * related "other_models" along this relation.
44
-     *
45
-     * @var string (internationalized)
46
-     */
47
-    protected $_blocking_delete_error_message;
48
-
49
-    protected $_blocking_delete = false;
50
-
51
-    /**
52
-     * Object representing the relationship between two models. This knows how to join the models,
53
-     * get related models across the relation, and add-and-remove the relationships.
54
-     *
55
-     * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
56
-     *                                               and add an error) the deletion of this model
57
-     * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
58
-     *                                               default
59
-     */
60
-    public function __construct($block_deletes, $blocking_delete_error_message)
61
-    {
62
-        $this->_blocking_delete               = $block_deletes;
63
-        $this->_blocking_delete_error_message = $blocking_delete_error_message;
64
-    }
65
-
66
-
67
-    /**
68
-     * @param $this_model_name
69
-     * @param $other_model_name
70
-     * @throws EE_Error
71
-     */
72
-    public function _construct_finalize_set_models($this_model_name, $other_model_name)
73
-    {
74
-        $this->_this_model_name  = $this_model_name;
75
-        $this->_other_model_name = $other_model_name;
76
-        if (is_string($this->_blocking_delete)) {
77
-            throw new EE_Error(sprintf(
78
-                __(
79
-                    "When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
80
-                    "event_espresso"
81
-                ),
82
-                get_class($this),
83
-                $this_model_name,
84
-                $other_model_name,
85
-                $this->_blocking_delete
86
-            ));
87
-        }
88
-    }
89
-
90
-
91
-    /**
92
-     * Gets the model where this relation is defined.
93
-     *
94
-     * @return EEM_Base
95
-     */
96
-    public function get_this_model()
97
-    {
98
-        return $this->_get_model($this->_this_model_name);
99
-    }
100
-
101
-
102
-    /**
103
-     * Gets the model which this relation establishes the relation TO (ie,
104
-     * this relation object was defined on get_this_model(), get_other_model() is the other one)
105
-     *
106
-     * @return EEM_Base
107
-     */
108
-    public function get_other_model()
109
-    {
110
-        return $this->_get_model($this->_other_model_name);
111
-    }
112
-
113
-
114
-    /**
115
-     * Internally used by get_this_model() and get_other_model()
116
-     *
117
-     * @param string $model_name like Event, Question_Group, etc. omit the EEM_
118
-     * @return EEM_Base
119
-     */
120
-    protected function _get_model($model_name)
121
-    {
122
-        $modelInstance = EE_Registry::instance()->load_model($model_name);
123
-        $modelInstance->set_timezone($this->_timezone);
124
-        return $modelInstance;
125
-    }
126
-
127
-
128
-    /**
129
-     * entirely possible that relations may be called from a model and we need to make sure those relations have their
130
-     * timezone set correctly.
131
-     *
132
-     * @param string $timezone timezone to set.
133
-     */
134
-    public function set_timezone($timezone)
135
-    {
136
-        if ($timezone !== null) {
137
-            $this->_timezone = $timezone;
138
-        }
139
-    }
140
-
141
-
142
-    /**
143
-     * @param        $other_table
144
-     * @param        $other_table_alias
145
-     * @param        $other_table_column
146
-     * @param        $this_table_alias
147
-     * @param        $this_table_join_column
148
-     * @param string $extra_join_sql
149
-     * @return string
150
-     */
151
-    protected function _left_join(
152
-        $other_table,
153
-        $other_table_alias,
154
-        $other_table_column,
155
-        $this_table_alias,
156
-        $this_table_join_column,
157
-        $extra_join_sql = ''
158
-    ) {
159
-        return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
160
-    }
161
-
162
-
163
-    /**
164
-     * Gets all the model objects of type of other model related to $model_object,
165
-     * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
166
-     * For both of those child classes, $model_object must be saved so that it has an ID before querying,
167
-     * otherwise an error will be thrown. Note: by default we disable default_where_conditions
168
-     * EE_Belongs_To_Relation doesn't need to be saved before querying.
169
-     *
170
-     * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
171
-     * @param array             $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
172
-     * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
173
-     * @return EE_Base_Class[]
174
-     * @throws \EE_Error
175
-     */
176
-    public function get_all_related(
177
-        $model_object_or_id,
178
-        $query_params = array(),
179
-        $values_already_prepared_by_model_object = false
180
-    ) {
181
-        if ($values_already_prepared_by_model_object !== false) {
182
-            EE_Error::doing_it_wrong(
183
-                'EE_Model_Relation_Base::get_all_related',
184
-                __('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
185
-                '4.8.1'
186
-            );
187
-        }
188
-        $query_params                                      = $this->_disable_default_where_conditions_on_query_param($query_params);
189
-        $query_param_where_this_model_pk                   = $this->get_this_model()->get_this_model_name()
190
-                                                             . "."
191
-                                                             . $this->get_this_model()->get_primary_key_field()->get_name();
192
-        $model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
193
-        $query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
194
-        return $this->get_other_model()->get_all($query_params);
195
-    }
196
-
197
-
198
-    /**
199
-     * Alters the $query_params to disable default where conditions, unless otherwise specified
200
-     *
201
-     * @param string $query_params
202
-     * @return array
203
-     */
204
-    protected function _disable_default_where_conditions_on_query_param($query_params)
205
-    {
206
-        if (! isset($query_params['default_where_conditions'])) {
207
-            $query_params['default_where_conditions'] = 'none';
208
-        }
209
-        return $query_params;
210
-    }
211
-
212
-
213
-    /**
214
-     * Deletes the related model objects which meet the query parameters. If no
215
-     * parameters are specified, then all related model objects will be deleted.
216
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
217
-     * model objects will only be soft-deleted.
218
-     *
219
-     * @param EE_Base_Class|int|string $model_object_or_id
220
-     * @param array                    $query_params
221
-     * @return int of how many related models got deleted
222
-     * @throws \EE_Error
223
-     */
224
-    public function delete_all_related($model_object_or_id, $query_params = array())
225
-    {
226
-        // for each thing we would delete,
227
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
228
-        // determine if it's blocked by anything else before it can be deleted
229
-        $deleted_count = 0;
230
-        foreach ($related_model_objects as $related_model_object) {
231
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
232
-                $related_model_object,
233
-                $model_object_or_id
234
-            );
235
-            /* @var $model_object_or_id EE_Base_Class */
236
-            if (! $delete_is_blocked) {
237
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
238
-                $related_model_object->delete();
239
-                $deleted_count++;
240
-            }
241
-        }
242
-        return $deleted_count;
243
-    }
244
-
245
-
246
-    /**
247
-     * Deletes the related model objects which meet the query parameters. If no
248
-     * parameters are specified, then all related model objects will be deleted.
249
-     * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
250
-     * model objects will only be soft-deleted.
251
-     *
252
-     * @param EE_Base_Class|int|string $model_object_or_id
253
-     * @param array                    $query_params
254
-     * @return int of how many related models got deleted
255
-     * @throws \EE_Error
256
-     */
257
-    public function delete_related_permanently($model_object_or_id, $query_params = array())
258
-    {
259
-        // for each thing we would delete,
260
-        $related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
261
-        // determine if it's blocked by anything else before it can be deleted
262
-        $deleted_count = 0;
263
-        foreach ($related_model_objects as $related_model_object) {
264
-            $delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
265
-                $related_model_object,
266
-                $model_object_or_id
267
-            );
268
-            /* @var $model_object_or_id EE_Base_Class */
269
-            if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
270
-                $this->remove_relation_to($model_object_or_id, $related_model_object);
271
-                $deleted_count++;
272
-                if (! $delete_is_blocked) {
273
-                    $related_model_object->delete_permanently();
274
-                } else {
275
-                    // delete is blocked
276
-                    // brent and darren, in this case, wanted to just soft delete it then
277
-                    $related_model_object->delete();
278
-                }
279
-            } else {
280
-                // its not a soft-deletable thing anyways. do the normal logic.
281
-                if (! $delete_is_blocked) {
282
-                    $this->remove_relation_to($model_object_or_id, $related_model_object);
283
-                    $related_model_object->delete();
284
-                    $deleted_count++;
285
-                }
286
-            }
287
-        }
288
-        return $deleted_count;
289
-    }
290
-
291
-
292
-    /**
293
-     * this just returns a model_object_id for incoming item that could be an object or id.
294
-     *
295
-     * @param  EE_Base_Class|int $model_object_or_id model object or the primary key of this model
296
-     * @throws EE_Error
297
-     * @return int
298
-     */
299
-    protected function _get_model_object_id($model_object_or_id)
300
-    {
301
-        $model_object_id = $model_object_or_id;
302
-        if ($model_object_or_id instanceof EE_Base_Class) {
303
-            $model_object_id = $model_object_or_id->ID();
304
-        }
305
-        if (! $model_object_id) {
306
-            throw new EE_Error(sprintf(
307
-                __(
308
-                    "Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
309
-                    "event_espresso"
310
-                ),
311
-                $this->get_other_model()->get_this_model_name(),
312
-                $this->get_this_model()->get_this_model_name()
313
-            ));
314
-        }
315
-        return $model_object_id;
316
-    }
317
-
318
-
319
-    /**
320
-     * Gets the SQL string for performing the join between this model and the other model.
321
-     *
322
-     * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
323
-     * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
324
-     *                other_model_primary_table.fk" etc
325
-     */
326
-    abstract public function get_join_statement($model_relation_chain);
327
-
328
-
329
-    /**
330
-     * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
331
-     * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
332
-     * relationship only allows this model to be related to a single other model of this type)
333
-     *
334
-     * @param       $this_obj_or_id
335
-     * @param       $other_obj_or_id
336
-     * @param array $extra_join_model_fields_n_values
337
-     * @return \EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
338
-     *                        $other_obj_or_id)
339
-     */
340
-    abstract public function add_relation_to(
341
-        $this_obj_or_id,
342
-        $other_obj_or_id,
343
-        $extra_join_model_fields_n_values = array()
344
-    );
345
-
346
-
347
-    /**
348
-     * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
349
-     * model objects
350
-     *
351
-     * @param       $this_obj_or_id
352
-     * @param       $other_obj_or_id
353
-     * @param array $where_query
354
-     * @return bool
355
-     */
356
-    abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array());
357
-
358
-
359
-    /**
360
-     * Removes ALL relation instances for this relation obj
361
-     *
362
-     * @param EE_Base_Class|int $this_obj_or_id
363
-     * @param array             $where_query_param @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
364
-     * @return EE_Base_Class[]
365
-     * @throws \EE_Error
366
-     */
367
-    public function remove_relations($this_obj_or_id, $where_query_param = array())
368
-    {
369
-        $related_things = $this->get_all_related($this_obj_or_id, array($where_query_param));
370
-        $objs_removed   = array();
371
-        foreach ($related_things as $related_thing) {
372
-            $objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
373
-        }
374
-        return $objs_removed;
375
-    }
376
-
377
-
378
-    /**
379
-     * If you aren't allowed to delete this model when there are related models across this
380
-     * relation object, return true. Otherwise, if you can delete this model even though
381
-     * related objects exist, returns false.
382
-     *
383
-     * @return boolean
384
-     */
385
-    public function block_delete_if_related_models_exist()
386
-    {
387
-        return $this->_blocking_delete;
388
-    }
389
-
390
-
391
-    /**
392
-     * Gets the error message to show
393
-     *
394
-     * @return string
395
-     */
396
-    public function get_deletion_error_message()
397
-    {
398
-        if ($this->_blocking_delete_error_message) {
399
-            return $this->_blocking_delete_error_message;
400
-        } else {
18
+	/**
19
+	 * The model name of which this relation is a component (ie, the model that called new EE_Model_Relation_Base)
20
+	 *
21
+	 * @var string eg Event, Question_Group, Registration
22
+	 */
23
+	private $_this_model_name;
24
+	/**
25
+	 * The model name pointed to by this relation (ie, the model we want to establish a relationship to)
26
+	 *
27
+	 * @var string eg Event, Question_Group, Registration
28
+	 */
29
+	private $_other_model_name;
30
+
31
+	/**
32
+	 * this is typically used when calling the relation models to make sure they inherit any set timezone from the
33
+	 * initiating model.
34
+	 *
35
+	 * @var string
36
+	 */
37
+	protected $_timezone;
38
+
39
+	/**
40
+	 * If you try to delete "this_model", and there are related "other_models",
41
+	 * and this isn't null, then abandon the deletion and add this warning.
42
+	 * This effectively makes it impossible to delete "this_model" while there are
43
+	 * related "other_models" along this relation.
44
+	 *
45
+	 * @var string (internationalized)
46
+	 */
47
+	protected $_blocking_delete_error_message;
48
+
49
+	protected $_blocking_delete = false;
50
+
51
+	/**
52
+	 * Object representing the relationship between two models. This knows how to join the models,
53
+	 * get related models across the relation, and add-and-remove the relationships.
54
+	 *
55
+	 * @param boolean $block_deletes                 if there are related models across this relation, block (prevent
56
+	 *                                               and add an error) the deletion of this model
57
+	 * @param string  $blocking_delete_error_message a customized error message on blocking deletes instead of the
58
+	 *                                               default
59
+	 */
60
+	public function __construct($block_deletes, $blocking_delete_error_message)
61
+	{
62
+		$this->_blocking_delete               = $block_deletes;
63
+		$this->_blocking_delete_error_message = $blocking_delete_error_message;
64
+	}
65
+
66
+
67
+	/**
68
+	 * @param $this_model_name
69
+	 * @param $other_model_name
70
+	 * @throws EE_Error
71
+	 */
72
+	public function _construct_finalize_set_models($this_model_name, $other_model_name)
73
+	{
74
+		$this->_this_model_name  = $this_model_name;
75
+		$this->_other_model_name = $other_model_name;
76
+		if (is_string($this->_blocking_delete)) {
77
+			throw new EE_Error(sprintf(
78
+				__(
79
+					"When instantiating the relation of type %s from %s to %s, the \$block_deletes argument should be a boolean, not a string (%s)",
80
+					"event_espresso"
81
+				),
82
+				get_class($this),
83
+				$this_model_name,
84
+				$other_model_name,
85
+				$this->_blocking_delete
86
+			));
87
+		}
88
+	}
89
+
90
+
91
+	/**
92
+	 * Gets the model where this relation is defined.
93
+	 *
94
+	 * @return EEM_Base
95
+	 */
96
+	public function get_this_model()
97
+	{
98
+		return $this->_get_model($this->_this_model_name);
99
+	}
100
+
101
+
102
+	/**
103
+	 * Gets the model which this relation establishes the relation TO (ie,
104
+	 * this relation object was defined on get_this_model(), get_other_model() is the other one)
105
+	 *
106
+	 * @return EEM_Base
107
+	 */
108
+	public function get_other_model()
109
+	{
110
+		return $this->_get_model($this->_other_model_name);
111
+	}
112
+
113
+
114
+	/**
115
+	 * Internally used by get_this_model() and get_other_model()
116
+	 *
117
+	 * @param string $model_name like Event, Question_Group, etc. omit the EEM_
118
+	 * @return EEM_Base
119
+	 */
120
+	protected function _get_model($model_name)
121
+	{
122
+		$modelInstance = EE_Registry::instance()->load_model($model_name);
123
+		$modelInstance->set_timezone($this->_timezone);
124
+		return $modelInstance;
125
+	}
126
+
127
+
128
+	/**
129
+	 * entirely possible that relations may be called from a model and we need to make sure those relations have their
130
+	 * timezone set correctly.
131
+	 *
132
+	 * @param string $timezone timezone to set.
133
+	 */
134
+	public function set_timezone($timezone)
135
+	{
136
+		if ($timezone !== null) {
137
+			$this->_timezone = $timezone;
138
+		}
139
+	}
140
+
141
+
142
+	/**
143
+	 * @param        $other_table
144
+	 * @param        $other_table_alias
145
+	 * @param        $other_table_column
146
+	 * @param        $this_table_alias
147
+	 * @param        $this_table_join_column
148
+	 * @param string $extra_join_sql
149
+	 * @return string
150
+	 */
151
+	protected function _left_join(
152
+		$other_table,
153
+		$other_table_alias,
154
+		$other_table_column,
155
+		$this_table_alias,
156
+		$this_table_join_column,
157
+		$extra_join_sql = ''
158
+	) {
159
+		return " LEFT JOIN " . $other_table . " AS " . $other_table_alias . " ON " . $other_table_alias . "." . $other_table_column . "=" . $this_table_alias . "." . $this_table_join_column . ($extra_join_sql ? " AND $extra_join_sql" : '');
160
+	}
161
+
162
+
163
+	/**
164
+	 * Gets all the model objects of type of other model related to $model_object,
165
+	 * according to this relation. This is the same code for EE_HABTM_Relation and EE_Has_Many_Relation.
166
+	 * For both of those child classes, $model_object must be saved so that it has an ID before querying,
167
+	 * otherwise an error will be thrown. Note: by default we disable default_where_conditions
168
+	 * EE_Belongs_To_Relation doesn't need to be saved before querying.
169
+	 *
170
+	 * @param EE_Base_Class|int $model_object_or_id                      or the primary key of this model
171
+	 * @param array             $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
172
+	 * @param boolean           $values_already_prepared_by_model_object @deprecated since 4.8.1
173
+	 * @return EE_Base_Class[]
174
+	 * @throws \EE_Error
175
+	 */
176
+	public function get_all_related(
177
+		$model_object_or_id,
178
+		$query_params = array(),
179
+		$values_already_prepared_by_model_object = false
180
+	) {
181
+		if ($values_already_prepared_by_model_object !== false) {
182
+			EE_Error::doing_it_wrong(
183
+				'EE_Model_Relation_Base::get_all_related',
184
+				__('The argument $values_already_prepared_by_model_object is no longer used.', 'event_espresso'),
185
+				'4.8.1'
186
+			);
187
+		}
188
+		$query_params                                      = $this->_disable_default_where_conditions_on_query_param($query_params);
189
+		$query_param_where_this_model_pk                   = $this->get_this_model()->get_this_model_name()
190
+															 . "."
191
+															 . $this->get_this_model()->get_primary_key_field()->get_name();
192
+		$model_object_id                                   = $this->_get_model_object_id($model_object_or_id);
193
+		$query_params[0][ $query_param_where_this_model_pk ] = $model_object_id;
194
+		return $this->get_other_model()->get_all($query_params);
195
+	}
196
+
197
+
198
+	/**
199
+	 * Alters the $query_params to disable default where conditions, unless otherwise specified
200
+	 *
201
+	 * @param string $query_params
202
+	 * @return array
203
+	 */
204
+	protected function _disable_default_where_conditions_on_query_param($query_params)
205
+	{
206
+		if (! isset($query_params['default_where_conditions'])) {
207
+			$query_params['default_where_conditions'] = 'none';
208
+		}
209
+		return $query_params;
210
+	}
211
+
212
+
213
+	/**
214
+	 * Deletes the related model objects which meet the query parameters. If no
215
+	 * parameters are specified, then all related model objects will be deleted.
216
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
217
+	 * model objects will only be soft-deleted.
218
+	 *
219
+	 * @param EE_Base_Class|int|string $model_object_or_id
220
+	 * @param array                    $query_params
221
+	 * @return int of how many related models got deleted
222
+	 * @throws \EE_Error
223
+	 */
224
+	public function delete_all_related($model_object_or_id, $query_params = array())
225
+	{
226
+		// for each thing we would delete,
227
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
228
+		// determine if it's blocked by anything else before it can be deleted
229
+		$deleted_count = 0;
230
+		foreach ($related_model_objects as $related_model_object) {
231
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
232
+				$related_model_object,
233
+				$model_object_or_id
234
+			);
235
+			/* @var $model_object_or_id EE_Base_Class */
236
+			if (! $delete_is_blocked) {
237
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
238
+				$related_model_object->delete();
239
+				$deleted_count++;
240
+			}
241
+		}
242
+		return $deleted_count;
243
+	}
244
+
245
+
246
+	/**
247
+	 * Deletes the related model objects which meet the query parameters. If no
248
+	 * parameters are specified, then all related model objects will be deleted.
249
+	 * Note: If the related model is extends EEM_Soft_Delete_Base, then the related
250
+	 * model objects will only be soft-deleted.
251
+	 *
252
+	 * @param EE_Base_Class|int|string $model_object_or_id
253
+	 * @param array                    $query_params
254
+	 * @return int of how many related models got deleted
255
+	 * @throws \EE_Error
256
+	 */
257
+	public function delete_related_permanently($model_object_or_id, $query_params = array())
258
+	{
259
+		// for each thing we would delete,
260
+		$related_model_objects = $this->get_all_related($model_object_or_id, $query_params);
261
+		// determine if it's blocked by anything else before it can be deleted
262
+		$deleted_count = 0;
263
+		foreach ($related_model_objects as $related_model_object) {
264
+			$delete_is_blocked = $this->get_other_model()->delete_is_blocked_by_related_models(
265
+				$related_model_object,
266
+				$model_object_or_id
267
+			);
268
+			/* @var $model_object_or_id EE_Base_Class */
269
+			if ($related_model_object instanceof EE_Soft_Delete_Base_Class) {
270
+				$this->remove_relation_to($model_object_or_id, $related_model_object);
271
+				$deleted_count++;
272
+				if (! $delete_is_blocked) {
273
+					$related_model_object->delete_permanently();
274
+				} else {
275
+					// delete is blocked
276
+					// brent and darren, in this case, wanted to just soft delete it then
277
+					$related_model_object->delete();
278
+				}
279
+			} else {
280
+				// its not a soft-deletable thing anyways. do the normal logic.
281
+				if (! $delete_is_blocked) {
282
+					$this->remove_relation_to($model_object_or_id, $related_model_object);
283
+					$related_model_object->delete();
284
+					$deleted_count++;
285
+				}
286
+			}
287
+		}
288
+		return $deleted_count;
289
+	}
290
+
291
+
292
+	/**
293
+	 * this just returns a model_object_id for incoming item that could be an object or id.
294
+	 *
295
+	 * @param  EE_Base_Class|int $model_object_or_id model object or the primary key of this model
296
+	 * @throws EE_Error
297
+	 * @return int
298
+	 */
299
+	protected function _get_model_object_id($model_object_or_id)
300
+	{
301
+		$model_object_id = $model_object_or_id;
302
+		if ($model_object_or_id instanceof EE_Base_Class) {
303
+			$model_object_id = $model_object_or_id->ID();
304
+		}
305
+		if (! $model_object_id) {
306
+			throw new EE_Error(sprintf(
307
+				__(
308
+					"Sorry, we cant get the related %s model objects to %s model object before it has an ID. You can solve that by just saving it before trying to get its related model objects",
309
+					"event_espresso"
310
+				),
311
+				$this->get_other_model()->get_this_model_name(),
312
+				$this->get_this_model()->get_this_model_name()
313
+			));
314
+		}
315
+		return $model_object_id;
316
+	}
317
+
318
+
319
+	/**
320
+	 * Gets the SQL string for performing the join between this model and the other model.
321
+	 *
322
+	 * @param string $model_relation_chain like 'Event.Event_Venue.Venue'
323
+	 * @return string of SQL, eg "LEFT JOIN table_name AS table_alias ON this_model_primary_table.pk =
324
+	 *                other_model_primary_table.fk" etc
325
+	 */
326
+	abstract public function get_join_statement($model_relation_chain);
327
+
328
+
329
+	/**
330
+	 * Adds a relationships between the two model objects provided. Each type of relationship handles this differently
331
+	 * (EE_Belongs_To is a slight exception, it should more accurately be called set_relation_to(...), as this
332
+	 * relationship only allows this model to be related to a single other model of this type)
333
+	 *
334
+	 * @param       $this_obj_or_id
335
+	 * @param       $other_obj_or_id
336
+	 * @param array $extra_join_model_fields_n_values
337
+	 * @return \EE_Base_Class the EE_Base_Class which was added as a relation. (Convenient if you only pass an ID for
338
+	 *                        $other_obj_or_id)
339
+	 */
340
+	abstract public function add_relation_to(
341
+		$this_obj_or_id,
342
+		$other_obj_or_id,
343
+		$extra_join_model_fields_n_values = array()
344
+	);
345
+
346
+
347
+	/**
348
+	 * Similar to 'add_relation_to(...)', performs the opposite action of removing the relationship between the two
349
+	 * model objects
350
+	 *
351
+	 * @param       $this_obj_or_id
352
+	 * @param       $other_obj_or_id
353
+	 * @param array $where_query
354
+	 * @return bool
355
+	 */
356
+	abstract public function remove_relation_to($this_obj_or_id, $other_obj_or_id, $where_query = array());
357
+
358
+
359
+	/**
360
+	 * Removes ALL relation instances for this relation obj
361
+	 *
362
+	 * @param EE_Base_Class|int $this_obj_or_id
363
+	 * @param array             $where_query_param @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
364
+	 * @return EE_Base_Class[]
365
+	 * @throws \EE_Error
366
+	 */
367
+	public function remove_relations($this_obj_or_id, $where_query_param = array())
368
+	{
369
+		$related_things = $this->get_all_related($this_obj_or_id, array($where_query_param));
370
+		$objs_removed   = array();
371
+		foreach ($related_things as $related_thing) {
372
+			$objs_removed[] = $this->remove_relation_to($this_obj_or_id, $related_thing);
373
+		}
374
+		return $objs_removed;
375
+	}
376
+
377
+
378
+	/**
379
+	 * If you aren't allowed to delete this model when there are related models across this
380
+	 * relation object, return true. Otherwise, if you can delete this model even though
381
+	 * related objects exist, returns false.
382
+	 *
383
+	 * @return boolean
384
+	 */
385
+	public function block_delete_if_related_models_exist()
386
+	{
387
+		return $this->_blocking_delete;
388
+	}
389
+
390
+
391
+	/**
392
+	 * Gets the error message to show
393
+	 *
394
+	 * @return string
395
+	 */
396
+	public function get_deletion_error_message()
397
+	{
398
+		if ($this->_blocking_delete_error_message) {
399
+			return $this->_blocking_delete_error_message;
400
+		} else {
401 401
 //          return sprintf(__('Cannot delete %1$s when there are related %2$s', "event_espresso"),$this->get_this_model()->item_name(2),$this->get_other_model()->item_name(2));
402
-            return sprintf(
403
-                __(
404
-                    'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
405
-                    "event_espresso"
406
-                ),
407
-                $this->get_this_model()->item_name(1),
408
-                $this->get_other_model()->item_name(1),
409
-                $this->get_other_model()->item_name(2)
410
-            );
411
-        }
412
-    }
413
-
414
-    /**
415
-     * Returns whatever is set as the nicename for the object.
416
-     *
417
-     * @return string
418
-     */
419
-    public function getSchemaDescription()
420
-    {
421
-        $description = $this instanceof EE_Belongs_To_Relation
422
-            ? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
423
-            : esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
424
-        return sprintf(
425
-            $description,
426
-            $this->get_other_model()->get_this_model_name(),
427
-            $this->get_this_model()->get_this_model_name()
428
-        );
429
-    }
430
-
431
-    /**
432
-     * Returns whatever is set as the $_schema_type property for the object.
433
-     * Note: this will automatically add 'null' to the schema if the object is_nullable()
434
-     *
435
-     * @return string|array
436
-     */
437
-    public function getSchemaType()
438
-    {
439
-        return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
440
-    }
441
-
442
-    /**
443
-     * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
444
-     * this method and return the properties for the schema.
445
-     * The reason this is not a property on the class is because there may be filters set on the values for the property
446
-     * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
447
-     *
448
-     * @return array
449
-     */
450
-    public function getSchemaProperties()
451
-    {
452
-        return array();
453
-    }
454
-
455
-    /**
456
-     * If a child class has enum values, they should override this method and provide a simple array
457
-     * of the enum values.
458
-     * The reason this is not a property on the class is because there may be filterable enum values that
459
-     * are set on the instantiated object that could be filtered after construct.
460
-     *
461
-     * @return array
462
-     */
463
-    public function getSchemaEnum()
464
-    {
465
-        return array();
466
-    }
467
-
468
-    /**
469
-     * This returns the value of the $_schema_format property on the object.
470
-     *
471
-     * @return string
472
-     */
473
-    public function getSchemaFormat()
474
-    {
475
-        return array();
476
-    }
477
-
478
-    /**
479
-     * This returns the value of the $_schema_readonly property on the object.
480
-     *
481
-     * @return bool
482
-     */
483
-    public function getSchemaReadonly()
484
-    {
485
-        return true;
486
-    }
487
-
488
-    /**
489
-     * This returns elements used to represent this field in the json schema.
490
-     *
491
-     * @link http://json-schema.org/
492
-     * @return array
493
-     */
494
-    public function getSchema()
495
-    {
496
-        $schema = array(
497
-            'description' => $this->getSchemaDescription(),
498
-            'type' => $this->getSchemaType(),
499
-            'relation' => true,
500
-            'relation_type' => get_class($this),
501
-            'readonly' => $this->getSchemaReadonly()
502
-        );
503
-
504
-        if ($this instanceof EE_HABTM_Relation) {
505
-            $schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
506
-        }
507
-
508
-        if ($this->getSchemaType() === 'array') {
509
-            $schema['items'] = array(
510
-                'type' => 'object'
511
-            );
512
-        }
513
-
514
-        return $schema;
515
-    }
402
+			return sprintf(
403
+				__(
404
+					'This %1$s is currently linked to one or more %2$s records. If this %1$s is incorrect, then please remove it from all %3$s before attempting to delete it.',
405
+					"event_espresso"
406
+				),
407
+				$this->get_this_model()->item_name(1),
408
+				$this->get_other_model()->item_name(1),
409
+				$this->get_other_model()->item_name(2)
410
+			);
411
+		}
412
+	}
413
+
414
+	/**
415
+	 * Returns whatever is set as the nicename for the object.
416
+	 *
417
+	 * @return string
418
+	 */
419
+	public function getSchemaDescription()
420
+	{
421
+		$description = $this instanceof EE_Belongs_To_Relation
422
+			? esc_html__('The related %1$s entity to the %2$s.', 'event_espresso')
423
+			: esc_html__('The related %1$s entities to the %2$s.', 'event_espresso');
424
+		return sprintf(
425
+			$description,
426
+			$this->get_other_model()->get_this_model_name(),
427
+			$this->get_this_model()->get_this_model_name()
428
+		);
429
+	}
430
+
431
+	/**
432
+	 * Returns whatever is set as the $_schema_type property for the object.
433
+	 * Note: this will automatically add 'null' to the schema if the object is_nullable()
434
+	 *
435
+	 * @return string|array
436
+	 */
437
+	public function getSchemaType()
438
+	{
439
+		return $this instanceof EE_Belongs_To_Relation ? 'object' : 'array';
440
+	}
441
+
442
+	/**
443
+	 * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
444
+	 * this method and return the properties for the schema.
445
+	 * The reason this is not a property on the class is because there may be filters set on the values for the property
446
+	 * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
447
+	 *
448
+	 * @return array
449
+	 */
450
+	public function getSchemaProperties()
451
+	{
452
+		return array();
453
+	}
454
+
455
+	/**
456
+	 * If a child class has enum values, they should override this method and provide a simple array
457
+	 * of the enum values.
458
+	 * The reason this is not a property on the class is because there may be filterable enum values that
459
+	 * are set on the instantiated object that could be filtered after construct.
460
+	 *
461
+	 * @return array
462
+	 */
463
+	public function getSchemaEnum()
464
+	{
465
+		return array();
466
+	}
467
+
468
+	/**
469
+	 * This returns the value of the $_schema_format property on the object.
470
+	 *
471
+	 * @return string
472
+	 */
473
+	public function getSchemaFormat()
474
+	{
475
+		return array();
476
+	}
477
+
478
+	/**
479
+	 * This returns the value of the $_schema_readonly property on the object.
480
+	 *
481
+	 * @return bool
482
+	 */
483
+	public function getSchemaReadonly()
484
+	{
485
+		return true;
486
+	}
487
+
488
+	/**
489
+	 * This returns elements used to represent this field in the json schema.
490
+	 *
491
+	 * @link http://json-schema.org/
492
+	 * @return array
493
+	 */
494
+	public function getSchema()
495
+	{
496
+		$schema = array(
497
+			'description' => $this->getSchemaDescription(),
498
+			'type' => $this->getSchemaType(),
499
+			'relation' => true,
500
+			'relation_type' => get_class($this),
501
+			'readonly' => $this->getSchemaReadonly()
502
+		);
503
+
504
+		if ($this instanceof EE_HABTM_Relation) {
505
+			$schema['joining_model_name'] = $this->get_join_model()->get_this_model_name();
506
+		}
507
+
508
+		if ($this->getSchemaType() === 'array') {
509
+			$schema['items'] = array(
510
+				'type' => 'object'
511
+			);
512
+		}
513
+
514
+		return $schema;
515
+	}
516 516
 }
Please login to merge, or discard this patch.