Completed
Branch BUG/reg-status-change-recursio... (fbd515)
by
unknown
09:28 queued 36s
created
core/db_models/EEM_Registration.model.php 1 patch
Indentation   +866 added lines, -866 removed lines patch added patch discarded remove patch
@@ -13,815 +13,815 @@  discard block
 block discarded – undo
13 13
 class EEM_Registration extends EEM_Soft_Delete_Base
14 14
 {
15 15
 
16
-    /**
17
-     * @var EEM_Registration $_instance
18
-     */
19
-    protected static $_instance;
20
-
21
-    /**
22
-     * Keys are the status IDs for registrations (eg, RAP, RCN, etc), and the values
23
-     * are status codes (eg, approved, cancelled, etc)
24
-     *
25
-     * @var array
26
-     */
27
-    private static $_reg_status;
28
-
29
-    /**
30
-     * The value of REG_count for a primary registrant
31
-     */
32
-    const PRIMARY_REGISTRANT_COUNT = 1;
33
-
34
-    /**
35
-     * Status ID (STS_ID on esp_status table) to indicate an INCOMPLETE registration.
36
-     * Initial status for registrations when they are first created
37
-     * Payments are NOT allowed.
38
-     * Automatically toggled to whatever the default Event registration status is upon completion of the attendee
39
-     * information reg step NO space reserved. Registration is NOT active
40
-     */
41
-    const status_id_incomplete = 'RIC';
42
-
43
-    /**
44
-     * Status ID (STS_ID on esp_status table) to indicate an UNAPPROVED registration.
45
-     * Payments are NOT allowed.
46
-     * Event Admin must manually toggle STS_ID for it to change
47
-     * No space reserved.
48
-     * Registration is active
49
-     */
50
-    const status_id_not_approved = 'RNA';
51
-
52
-    /**
53
-     * Status ID (STS_ID on esp_status table) to indicate registration is PENDING_PAYMENT .
54
-     * Payments are allowed.
55
-     * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
56
-     * No space reserved.
57
-     * Registration is active
58
-     */
59
-    const status_id_pending_payment = 'RPP';
60
-
61
-    /**
62
-     * Status ID (STS_ID on esp_status table) to indicate registration is on the WAIT_LIST .
63
-     * Payments are allowed.
64
-     * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
65
-     * No space reserved.
66
-     * Registration is active
67
-     */
68
-    const status_id_wait_list = 'RWL';
69
-
70
-    /**
71
-     * Status ID (STS_ID on esp_status table) to indicate an APPROVED registration.
72
-     * the TXN may or may not be completed ( paid in full )
73
-     * Payments are allowed.
74
-     * A space IS reserved.
75
-     * Registration is active
76
-     */
77
-    const status_id_approved = 'RAP';
78
-
79
-    /**
80
-     * Status ID (STS_ID on esp_status table) to indicate a registration was CANCELLED by the attendee.
81
-     * Payments are NOT allowed.
82
-     * NO space reserved.
83
-     * Registration is NOT active
84
-     */
85
-    const status_id_cancelled = 'RCN';
86
-
87
-    /**
88
-     * Status ID (STS_ID on esp_status table) to indicate a registration was DECLINED by the Event Admin
89
-     * Payments are NOT allowed.
90
-     * No space reserved.
91
-     * Registration is NOT active
92
-     */
93
-    const status_id_declined = 'RDC';
94
-
95
-    /**
96
-     * @var TableAnalysis $table_analysis
97
-     */
98
-    protected $_table_analysis;
99
-
100
-
101
-    /**
102
-     *    private constructor to prevent direct creation
103
-     *
104
-     * @Constructor
105
-     * @access protected
106
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
107
-     *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
108
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
109
-     *                         timezone in the 'timezone_string' wp option)
110
-     * @throws EE_Error
111
-     */
112
-    protected function __construct($timezone = null)
113
-    {
114
-        $this->_table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
115
-        $this->singular_item = esc_html__('Registration', 'event_espresso');
116
-        $this->plural_item = esc_html__('Registrations', 'event_espresso');
117
-        $this->_tables = array(
118
-            'Registration' => new EE_Primary_Table('esp_registration', 'REG_ID'),
119
-        );
120
-        $this->_fields = array(
121
-            'Registration' => array(
122
-                'REG_ID' => new EE_Primary_Key_Int_Field(
123
-                    'REG_ID',
124
-                    esc_html__('Registration ID', 'event_espresso')
125
-                ),
126
-                'EVT_ID' => new EE_Foreign_Key_Int_Field(
127
-                    'EVT_ID',
128
-                    esc_html__('Event ID', 'event_espresso'),
129
-                    false,
130
-                    0,
131
-                    'Event'
132
-                ),
133
-                'ATT_ID' => new EE_Foreign_Key_Int_Field(
134
-                    'ATT_ID',
135
-                    esc_html__('Attendee ID', 'event_espresso'),
136
-                    false,
137
-                    0,
138
-                    'Attendee'
139
-                ),
140
-                'TXN_ID' => new EE_Foreign_Key_Int_Field(
141
-                    'TXN_ID',
142
-                    esc_html__('Transaction ID', 'event_espresso'),
143
-                    false,
144
-                    0,
145
-                    'Transaction'
146
-                ),
147
-                'TKT_ID' => new EE_Foreign_Key_Int_Field(
148
-                    'TKT_ID',
149
-                    esc_html__('Ticket ID', 'event_espresso'),
150
-                    false,
151
-                    0,
152
-                    'Ticket'
153
-                ),
154
-                'STS_ID' => new EE_Foreign_Key_String_Field(
155
-                    'STS_ID',
156
-                    esc_html__('Status ID', 'event_espresso'),
157
-                    false,
158
-                    EEM_Registration::status_id_incomplete,
159
-                    'Status'
160
-                ),
161
-                'REG_date' => new EE_Datetime_Field(
162
-                    'REG_date',
163
-                    esc_html__('Time registration occurred', 'event_espresso'),
164
-                    false,
165
-                    EE_Datetime_Field::now,
166
-                    $timezone
167
-                ),
168
-                'REG_final_price' => new EE_Money_Field(
169
-                    'REG_final_price',
170
-                    esc_html__('Registration\'s share of the transaction total', 'event_espresso'),
171
-                    false,
172
-                    0
173
-                ),
174
-                'REG_paid' => new EE_Money_Field(
175
-                    'REG_paid',
176
-                    esc_html__('Amount paid to date towards registration', 'event_espresso'),
177
-                    false,
178
-                    0
179
-                ),
180
-                'REG_session' => new EE_Plain_Text_Field(
181
-                    'REG_session',
182
-                    esc_html__('Session ID of registration', 'event_espresso'),
183
-                    false,
184
-                    ''
185
-                ),
186
-                'REG_code' => new EE_Plain_Text_Field(
187
-                    'REG_code',
188
-                    esc_html__('Unique Code for this registration', 'event_espresso'),
189
-                    false,
190
-                    ''
191
-                ),
192
-                'REG_url_link' => new EE_Plain_Text_Field(
193
-                    'REG_url_link',
194
-                    esc_html__('String to be used in URL for identifying registration', 'event_espresso'),
195
-                    false,
196
-                    ''
197
-                ),
198
-                'REG_count' => new EE_Integer_Field(
199
-                    'REG_count',
200
-                    esc_html__('Count of this registration in the group registration ', 'event_espresso'),
201
-                    true,
202
-                    1
203
-                ),
204
-                'REG_group_size' => new EE_Integer_Field(
205
-                    'REG_group_size',
206
-                    esc_html__('Number of registrations on this group', 'event_espresso'),
207
-                    false,
208
-                    1
209
-                ),
210
-                'REG_att_is_going' => new EE_Boolean_Field(
211
-                    'REG_att_is_going',
212
-                    esc_html__('Flag indicating the registrant plans on attending', 'event_espresso'),
213
-                    false,
214
-                    false
215
-                ),
216
-                'REG_deleted' => new EE_Trashed_Flag_Field(
217
-                    'REG_deleted',
218
-                    esc_html__('Flag indicating if registration has been archived or not.', 'event_espresso'),
219
-                    false,
220
-                    false
221
-                ),
222
-            ),
223
-        );
224
-        $this->_model_relations = array(
225
-            'Event' => new EE_Belongs_To_Relation(),
226
-            'Attendee' => new EE_Belongs_To_Relation(),
227
-            'Transaction' => new EE_Belongs_To_Relation(),
228
-            'Ticket' => new EE_Belongs_To_Relation(),
229
-            'Status' => new EE_Belongs_To_Relation(),
230
-            'Answer' => new EE_Has_Many_Relation(),
231
-            'Checkin' => new EE_Has_Many_Relation(),
232
-            'Registration_Payment' => new EE_Has_Many_Relation(),
233
-            'Payment' => new EE_HABTM_Relation('Registration_Payment'),
234
-            'Message' => new EE_Has_Many_Any_Relation(false)
235
-            // allow deletes even if there are messages in the queue related
236
-        );
237
-        $this->_model_chain_to_wp_user = 'Event';
238
-        parent::__construct($timezone);
239
-    }
240
-
241
-
242
-    /**
243
-     * a list of ALL valid registration statuses currently in use within the system
244
-     * generated by combining the filterable active and inactive reg status arrays
245
-     *
246
-     * @return array
247
-     */
248
-    public static function reg_statuses()
249
-    {
250
-        return array_unique(
251
-            array_merge(
252
-                EEM_Registration::active_reg_statuses(),
253
-                EEM_Registration::inactive_reg_statuses()
254
-            )
255
-        );
256
-    }
257
-
258
-
259
-    /**
260
-     * reg_statuses_that_allow_payment
261
-     * a filterable list of registration statuses that allow a registrant to make a payment
262
-     *
263
-     * @access public
264
-     * @return array
265
-     */
266
-    public static function reg_statuses_that_allow_payment()
267
-    {
268
-        return apply_filters(
269
-            'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
270
-            array(
271
-                EEM_Registration::status_id_approved,
272
-                EEM_Registration::status_id_pending_payment,
273
-            )
274
-        );
275
-    }
276
-
277
-
278
-    /**
279
-     * active_reg_statuses
280
-     * a filterable list of registration statuses that are considered active
281
-     *
282
-     * @access public
283
-     * @return array
284
-     */
285
-    public static function active_reg_statuses()
286
-    {
287
-        return apply_filters(
288
-            'FHEE__EEM_Registration__active_reg_statuses',
289
-            array(
290
-                EEM_Registration::status_id_approved,
291
-                EEM_Registration::status_id_pending_payment,
292
-                EEM_Registration::status_id_wait_list,
293
-                EEM_Registration::status_id_not_approved,
294
-            )
295
-        );
296
-    }
297
-
298
-
299
-    /**
300
-     * inactive_reg_statuses
301
-     * a filterable list of registration statuses that are not considered active
302
-     *
303
-     * @access public
304
-     * @return array
305
-     */
306
-    public static function inactive_reg_statuses()
307
-    {
308
-        return apply_filters(
309
-            'FHEE__EEM_Registration__inactive_reg_statuses',
310
-            array(
311
-                EEM_Registration::status_id_incomplete,
312
-                EEM_Registration::status_id_cancelled,
313
-                EEM_Registration::status_id_declined,
314
-            )
315
-        );
316
-    }
317
-
318
-
319
-    /**
320
-     *    closed_reg_statuses
321
-     *    a filterable list of registration statuses that are considered "closed"
322
-     * meaning they should not be considered in any calculations involving monies owing
323
-     *
324
-     * @access public
325
-     * @return array
326
-     */
327
-    public static function closed_reg_statuses()
328
-    {
329
-        return apply_filters(
330
-            'FHEE__EEM_Registration__closed_reg_statuses',
331
-            array(
332
-                EEM_Registration::status_id_cancelled,
333
-                EEM_Registration::status_id_declined,
334
-                EEM_Registration::status_id_wait_list,
335
-            )
336
-        );
337
-    }
338
-
339
-
340
-    /**
341
-     *        get list of registration statuses
342
-     *
343
-     * @access public
344
-     * @param array $exclude The status ids to exclude from the returned results
345
-     * @param bool $translated If true will return the values as singular localized strings
346
-     * @return array
347
-     * @throws EE_Error
348
-     */
349
-    public static function reg_status_array($exclude = array(), $translated = false)
350
-    {
351
-        EEM_Registration::instance()->_get_registration_status_array($exclude);
352
-        return $translated
353
-            ? EEM_Status::instance()->localized_status(self::$_reg_status, false, 'sentence')
354
-            : self::$_reg_status;
355
-    }
356
-
357
-
358
-    /**
359
-     *    get list of registration statuses
360
-     *
361
-     * @access private
362
-     * @param array $exclude
363
-     * @return void
364
-     * @throws EE_Error
365
-     */
366
-    private function _get_registration_status_array($exclude = array())
367
-    {
368
-        // in the very rare circumstance that we are deleting a model's table's data
369
-        // and the table hasn't actually been created, this could have an error
370
-        /** @type WPDB $wpdb */
371
-        global $wpdb;
372
-        if ($this->_get_table_analysis()->tableExists($wpdb->prefix . 'esp_status')) {
373
-            $results = $wpdb->get_results(
374
-                "SELECT STS_ID, STS_code FROM {$wpdb->prefix}esp_status WHERE STS_type = 'registration'"
375
-            );
376
-            self::$_reg_status = array();
377
-            foreach ($results as $status) {
378
-                if (!in_array($status->STS_ID, $exclude, true)) {
379
-                    self::$_reg_status[ $status->STS_ID ] = $status->STS_code;
380
-                }
381
-            }
382
-        }
383
-    }
384
-
385
-
386
-    /**
387
-     * Gets the injected table analyzer, or throws an exception
388
-     *
389
-     * @return TableAnalysis
390
-     * @throws EE_Error
391
-     */
392
-    protected function _get_table_analysis()
393
-    {
394
-        if ($this->_table_analysis instanceof TableAnalysis) {
395
-            return $this->_table_analysis;
396
-        }
397
-        throw new EE_Error(
398
-            sprintf(
399
-                esc_html__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
400
-                get_class($this)
401
-            )
402
-        );
403
-    }
404
-
405
-
406
-    /**
407
-     * This returns a wpdb->results array of all registration date month and years matching the incoming query params
408
-     * and grouped by month and year.
409
-     *
410
-     * @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
411
-     * @return array
412
-     * @throws EE_Error
413
-     */
414
-    public function get_reg_months_and_years($where_params)
415
-    {
416
-        $query_params[0] = $where_params;
417
-        $query_params['group_by'] = array('reg_year', 'reg_month');
418
-        $query_params['order_by'] = array('REG_date' => 'DESC');
419
-        $columns_to_select = array(
420
-            'reg_year' => array('YEAR(REG_date)', '%s'),
421
-            'reg_month' => array('MONTHNAME(REG_date)', '%s'),
422
-        );
423
-        return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
424
-    }
425
-
426
-
427
-    /**
428
-     * retrieve ALL registrations for a particular Attendee from db
429
-     *
430
-     * @param int $ATT_ID
431
-     * @return EE_Base_Class[]|EE_Registration[]|null
432
-     * @throws EE_Error
433
-     */
434
-    public function get_all_registrations_for_attendee($ATT_ID = 0)
435
-    {
436
-        if (!$ATT_ID) {
437
-            return null;
438
-        }
439
-        return $this->get_all(array(array('ATT_ID' => $ATT_ID)));
440
-    }
441
-
442
-
443
-    /**
444
-     * Gets a registration given their REG_url_link. Yes, this should usually
445
-     * be passed via a GET parameter.
446
-     *
447
-     * @param string $REG_url_link
448
-     * @return EE_Base_Class|EE_Registration|null
449
-     * @throws EE_Error
450
-     */
451
-    public function get_registration_for_reg_url_link($REG_url_link)
452
-    {
453
-        if (!$REG_url_link) {
454
-            return null;
455
-        }
456
-        return $this->get_one(array(array('REG_url_link' => $REG_url_link)));
457
-    }
458
-
459
-
460
-    /**
461
-     *        retrieve registration for a specific transaction attendee from db
462
-     *
463
-     * @access        public
464
-     * @param    int $TXN_ID
465
-     * @param    int $ATT_ID
466
-     * @param    int $att_nmbr in case the ATT_ID is the same for multiple registrations (same details used) then the
467
-     *                         attendee number is required
468
-     * @return        mixed        array on success, FALSE on fail
469
-     * @throws EE_Error
470
-     */
471
-    public function get_registration_for_transaction_attendee($TXN_ID = 0, $ATT_ID = 0, $att_nmbr = 0)
472
-    {
473
-        return $this->get_one(array(
474
-            array(
475
-                'TXN_ID' => $TXN_ID,
476
-                'ATT_ID' => $ATT_ID,
477
-            ),
478
-            'limit' => array(min($att_nmbr - 1, 0), 1),
479
-        ));
480
-    }
481
-
482
-
483
-    /**
484
-     *        get the number of registrations per day  for the Registration Admin page Reports Tab.
485
-     *        (doesn't utilize models because it's a fairly specialized query)
486
-     *
487
-     * @access        public
488
-     * @param $period string which can be passed to php's strtotime function (eg "-1 month")
489
-     * @return stdClass[] with properties regDate and total
490
-     * @throws EE_Error
491
-     */
492
-    public function get_registrations_per_day_report($period = '-1 month')
493
-    {
494
-        $sql_date = $this->convert_datetime_for_query(
495
-            'REG_date',
496
-            date('Y-m-d H:i:s', strtotime($period)),
497
-            'Y-m-d H:i:s',
498
-            'UTC'
499
-        );
500
-        $where = array(
501
-            'REG_date' => array('>=', $sql_date),
502
-            'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
503
-        );
504
-        if (!EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_day_report')) {
505
-            $where['Event.EVT_wp_user'] = get_current_user_id();
506
-        }
507
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'REG_date');
508
-        $results = $this->_get_all_wpdb_results(
509
-            array(
510
-                $where,
511
-                'group_by' => 'regDate',
512
-                'order_by' => array('REG_date' => 'ASC'),
513
-            ),
514
-            OBJECT,
515
-            array(
516
-                'regDate' => array('DATE(' . $query_interval . ')', '%s'),
517
-                'total' => array('count(REG_ID)', '%d'),
518
-            )
519
-        );
520
-        return $results;
521
-    }
522
-
523
-
524
-    /**
525
-     * Get the number of registrations per day including the count of registrations for each Registration Status.
526
-     * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
527
-     *
528
-     * @param string $period
529
-     * @return stdClass[] with properties Registration_REG_date and a column for each registration status as the STS_ID
530
-     * @throws EE_Error
531
-     *                    (i.e. RAP)
532
-     */
533
-    public function get_registrations_per_day_and_per_status_report($period = '-1 month')
534
-    {
535
-        global $wpdb;
536
-        $registration_table = $wpdb->prefix . 'esp_registration';
537
-        $event_table = $wpdb->posts;
538
-        $sql_date = date('Y-m-d H:i:s', strtotime($period));
539
-        // prepare the query interval for displaying offset
540
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'dates.REG_date');
541
-        // inner date query
542
-        $inner_date_query = "SELECT DISTINCT REG_date from {$registration_table} ";
543
-        $inner_where = ' WHERE';
544
-        // exclude events not authored by user if permissions in effect
545
-        if (!EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
546
-            $inner_date_query .= "LEFT JOIN {$event_table} ON ID = EVT_ID";
547
-            $inner_where .= ' post_author = ' . get_current_user_id() . ' AND';
548
-        }
549
-        $inner_where .= " REG_date >= '{$sql_date}'";
550
-        $inner_date_query .= $inner_where;
551
-        // start main query
552
-        $select = "SELECT DATE({$query_interval}) as Registration_REG_date, ";
553
-        $join = '';
554
-        $join_parts = array();
555
-        $select_parts = array();
556
-        // loop through registration stati to do parts for each status.
557
-        foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
558
-            if ($STS_ID === EEM_Registration::status_id_incomplete) {
559
-                continue;
560
-            }
561
-            $select_parts[] = "COUNT({$STS_code}.REG_ID) as {$STS_ID}";
562
-            $join_parts[] = "{$registration_table} AS {$STS_code} ON {$STS_code}.REG_date = dates.REG_date AND {$STS_code}.STS_ID = '{$STS_ID}'";
563
-        }
564
-        // setup the selects
565
-        $select .= implode(', ', $select_parts);
566
-        $select .= " FROM ($inner_date_query) AS dates LEFT JOIN ";
567
-        // setup the joins
568
-        $join .= implode(' LEFT JOIN ', $join_parts);
569
-        // now let's put it all together
570
-        $query = $select . $join . ' GROUP BY Registration_REG_date';
571
-        // and execute it
572
-        return $wpdb->get_results($query, ARRAY_A);
573
-    }
574
-
575
-
576
-    /**
577
-     *        get the number of registrations per event  for the Registration Admin page Reports Tab
578
-     *
579
-     * @access        public
580
-     * @param $period string which can be passed to php's strtotime function (eg "-1 month")
581
-     * @return stdClass[] each with properties event_name, reg_limit, and total
582
-     * @throws EE_Error
583
-     */
584
-    public function get_registrations_per_event_report($period = '-1 month')
585
-    {
586
-        $date_sql = $this->convert_datetime_for_query(
587
-            'REG_date',
588
-            date('Y-m-d H:i:s', strtotime($period)),
589
-            'Y-m-d H:i:s',
590
-            'UTC'
591
-        );
592
-        $where = array(
593
-            'REG_date' => array('>=', $date_sql),
594
-            'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
595
-        );
596
-        if (!EE_Registry::instance()->CAP->current_user_can(
597
-            'ee_read_others_registrations',
598
-            'reg_per_event_report'
599
-        )
600
-        ) {
601
-            $where['Event.EVT_wp_user'] = get_current_user_id();
602
-        }
603
-        $results = $this->_get_all_wpdb_results(
604
-            array(
605
-            $where,
606
-            'group_by' => 'Event.EVT_name',
607
-            'order_by' => 'Event.EVT_name',
608
-            'limit' => array(0, 24),
609
-            ),
610
-            OBJECT,
611
-            array(
612
-                'event_name' => array('Event_CPT.post_title', '%s'),
613
-                'total' => array('COUNT(REG_ID)', '%s'),
614
-            )
615
-        );
616
-        return $results;
617
-    }
618
-
619
-
620
-    /**
621
-     * Get the number of registrations per event grouped by registration status.
622
-     * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
623
-     *
624
-     * @param string $period
625
-     * @return stdClass[] with properties `Registration_Event` and a column for each registration status as the STS_ID
626
-     * @throws EE_Error
627
-     *                    (i.e. RAP)
628
-     */
629
-    public function get_registrations_per_event_and_per_status_report($period = '-1 month')
630
-    {
631
-        global $wpdb;
632
-        $registration_table = $wpdb->prefix . 'esp_registration';
633
-        $event_table = $wpdb->posts;
634
-        $sql_date = date('Y-m-d H:i:s', strtotime($period));
635
-        // inner date query
636
-        $inner_date_query = "SELECT DISTINCT EVT_ID, REG_date from $registration_table ";
637
-        $inner_where = ' WHERE';
638
-        // exclude events not authored by user if permissions in effect
639
-        if (!EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
640
-            $inner_date_query .= "LEFT JOIN {$event_table} ON ID = EVT_ID";
641
-            $inner_where .= ' post_author = ' . get_current_user_id() . ' AND';
642
-        }
643
-        $inner_where .= " REG_date >= '{$sql_date}'";
644
-        $inner_date_query .= $inner_where;
645
-        // build main query
646
-        $select = 'SELECT Event.post_title as Registration_Event, ';
647
-        $join = '';
648
-        $join_parts = array();
649
-        $select_parts = array();
650
-        // loop through registration stati to do parts for each status.
651
-        foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
652
-            if ($STS_ID === EEM_Registration::status_id_incomplete) {
653
-                continue;
654
-            }
655
-            $select_parts[] = "COUNT({$STS_code}.REG_ID) as {$STS_ID}";
656
-            $join_parts[] = "{$registration_table} AS {$STS_code} ON {$STS_code}.EVT_ID = dates.EVT_ID AND {$STS_code}.STS_ID = '{$STS_ID}' AND {$STS_code}.REG_date = dates.REG_date";
657
-        }
658
-        // setup the selects
659
-        $select .= implode(', ', $select_parts);
660
-        $select .= " FROM ($inner_date_query) AS dates LEFT JOIN $event_table as Event ON Event.ID = dates.EVT_ID LEFT JOIN ";
661
-        // setup remaining joins
662
-        $join .= implode(' LEFT JOIN ', $join_parts);
663
-        // now put it all together
664
-        $query = $select . $join . ' GROUP BY Registration_Event';
665
-        // and execute
666
-        return $wpdb->get_results($query, ARRAY_A);
667
-    }
668
-
669
-
670
-    /**
671
-     * Returns the EE_Registration of the primary attendee on the transaction id provided
672
-     *
673
-     * @param int $TXN_ID
674
-     * @return EE_Base_Class|EE_Registration|null
675
-     * @throws EE_Error
676
-     */
677
-    public function get_primary_registration_for_transaction_ID($TXN_ID = 0)
678
-    {
679
-        if (!$TXN_ID) {
680
-            return null;
681
-        }
682
-        return $this->get_one(array(
683
-            array(
684
-                'TXN_ID' => $TXN_ID,
685
-                'REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT,
686
-            ),
687
-        ));
688
-    }
689
-
690
-
691
-    /**
692
-     *        get_event_registration_count
693
-     *
694
-     * @access public
695
-     * @param int $EVT_ID
696
-     * @param boolean $for_incomplete_payments
697
-     * @return int
698
-     * @throws EE_Error
699
-     */
700
-    public function get_event_registration_count($EVT_ID, $for_incomplete_payments = false)
701
-    {
702
-        // we only count approved registrations towards registration limits
703
-        $query_params = array(array('EVT_ID' => $EVT_ID, 'STS_ID' => self::status_id_approved));
704
-        if ($for_incomplete_payments) {
705
-            $query_params[0]['Transaction.STS_ID'] = array('!=', EEM_Transaction::complete_status_code);
706
-        }
707
-        return $this->count($query_params);
708
-    }
709
-
710
-
711
-    /**
712
-     * Deletes all registrations with no transactions. Note that this needs to be very efficient
713
-     * and so it uses wpdb directly
714
-     *
715
-     * @global WPDB $wpdb
716
-     * @return int number deleted
717
-     * @throws EE_Error
718
-     */
719
-    public function delete_registrations_with_no_transaction()
720
-    {
721
-        /** @type WPDB $wpdb */
722
-        global $wpdb;
723
-        return $wpdb->query(
724
-            'DELETE r FROM '
725
-            . $this->table()
726
-            . ' r LEFT JOIN '
727
-            . EEM_Transaction::instance()->table()
728
-            . ' t ON r.TXN_ID = t.TXN_ID WHERE t.TXN_ID IS NULL'
729
-        );
730
-    }
731
-
732
-
733
-    /**
734
-     *  Count registrations checked into (or out of) a datetime
735
-     *
736
-     * @param int $DTT_ID datetime ID
737
-     * @param boolean $checked_in whether to count registrations checked IN or OUT
738
-     * @return int
739
-     * @throws EE_Error
740
-     */
741
-    public function count_registrations_checked_into_datetime($DTT_ID, $checked_in = true)
742
-    {
743
-        global $wpdb;
744
-        // subquery to get latest checkin
745
-        $query = $wpdb->prepare(
746
-            'SELECT '
747
-            . 'COUNT( DISTINCT checkins.REG_ID ) '
748
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
749
-            . '( SELECT '
750
-            . 'max( CHK_timestamp ) AS latest_checkin, '
751
-            . 'REG_ID AS REG_ID '
752
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' '
753
-            . 'WHERE DTT_ID=%d '
754
-            . 'GROUP BY REG_ID'
755
-            . ') AS most_recent_checkin_per_reg '
756
-            . 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
757
-            . 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
758
-            . 'WHERE '
759
-            . 'checkins.CHK_in=%d',
760
-            $DTT_ID,
761
-            $checked_in
762
-        );
763
-        return (int) $wpdb->get_var($query);
764
-    }
765
-
766
-
767
-    /**
768
-     *  Count registrations checked into (or out of) an event.
769
-     *
770
-     * @param int $EVT_ID event ID
771
-     * @param boolean $checked_in whether to count registrations checked IN or OUT
772
-     * @return int
773
-     * @throws EE_Error
774
-     */
775
-    public function count_registrations_checked_into_event($EVT_ID, $checked_in = true)
776
-    {
777
-        global $wpdb;
778
-        // subquery to get latest checkin
779
-        $query = $wpdb->prepare(
780
-            'SELECT '
781
-            . 'COUNT( DISTINCT checkins.REG_ID ) '
782
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
783
-            . '( SELECT '
784
-            . 'max( CHK_timestamp ) AS latest_checkin, '
785
-            . 'REG_ID AS REG_ID '
786
-            . 'FROM ' . EEM_Checkin::instance()->table() . ' AS c '
787
-            . 'INNER JOIN ' . EEM_Datetime::instance()->table() . ' AS d '
788
-            . 'ON c.DTT_ID=d.DTT_ID '
789
-            . 'WHERE d.EVT_ID=%d '
790
-            . 'GROUP BY REG_ID'
791
-            . ') AS most_recent_checkin_per_reg '
792
-            . 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
793
-            . 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
794
-            . 'WHERE '
795
-            . 'checkins.CHK_in=%d',
796
-            $EVT_ID,
797
-            $checked_in
798
-        );
799
-        return (int) $wpdb->get_var($query);
800
-    }
801
-
802
-
803
-    /**
804
-     * The purpose of this method is to retrieve an array of
805
-     * EE_Registration objects that represent the latest registration
806
-     * for each ATT_ID given in the function argument.
807
-     *
808
-     * @param array $attendee_ids
809
-     * @return EE_Base_Class[]|EE_Registration[]
810
-     * @throws EE_Error
811
-     */
812
-    public function get_latest_registration_for_each_of_given_contacts($attendee_ids = array())
813
-    {
814
-        // first do a native wp_query to get the latest REG_ID's matching these attendees.
815
-        global $wpdb;
816
-        $registration_table = $wpdb->prefix . 'esp_registration';
817
-        $attendee_table = $wpdb->posts;
818
-        $attendee_ids = is_array($attendee_ids)
819
-            ? array_map('absint', $attendee_ids)
820
-            : array((int) $attendee_ids);
821
-        $ATT_IDs = implode(',', $attendee_ids);
822
-        // first we do a query to get the registration ids
823
-        // (because a group by before order by causes the order by to be ignored.)
824
-        $registration_id_query = "
16
+	/**
17
+	 * @var EEM_Registration $_instance
18
+	 */
19
+	protected static $_instance;
20
+
21
+	/**
22
+	 * Keys are the status IDs for registrations (eg, RAP, RCN, etc), and the values
23
+	 * are status codes (eg, approved, cancelled, etc)
24
+	 *
25
+	 * @var array
26
+	 */
27
+	private static $_reg_status;
28
+
29
+	/**
30
+	 * The value of REG_count for a primary registrant
31
+	 */
32
+	const PRIMARY_REGISTRANT_COUNT = 1;
33
+
34
+	/**
35
+	 * Status ID (STS_ID on esp_status table) to indicate an INCOMPLETE registration.
36
+	 * Initial status for registrations when they are first created
37
+	 * Payments are NOT allowed.
38
+	 * Automatically toggled to whatever the default Event registration status is upon completion of the attendee
39
+	 * information reg step NO space reserved. Registration is NOT active
40
+	 */
41
+	const status_id_incomplete = 'RIC';
42
+
43
+	/**
44
+	 * Status ID (STS_ID on esp_status table) to indicate an UNAPPROVED registration.
45
+	 * Payments are NOT allowed.
46
+	 * Event Admin must manually toggle STS_ID for it to change
47
+	 * No space reserved.
48
+	 * Registration is active
49
+	 */
50
+	const status_id_not_approved = 'RNA';
51
+
52
+	/**
53
+	 * Status ID (STS_ID on esp_status table) to indicate registration is PENDING_PAYMENT .
54
+	 * Payments are allowed.
55
+	 * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
56
+	 * No space reserved.
57
+	 * Registration is active
58
+	 */
59
+	const status_id_pending_payment = 'RPP';
60
+
61
+	/**
62
+	 * Status ID (STS_ID on esp_status table) to indicate registration is on the WAIT_LIST .
63
+	 * Payments are allowed.
64
+	 * STS_ID will automatically be toggled to RAP if payment is made in full by the attendee
65
+	 * No space reserved.
66
+	 * Registration is active
67
+	 */
68
+	const status_id_wait_list = 'RWL';
69
+
70
+	/**
71
+	 * Status ID (STS_ID on esp_status table) to indicate an APPROVED registration.
72
+	 * the TXN may or may not be completed ( paid in full )
73
+	 * Payments are allowed.
74
+	 * A space IS reserved.
75
+	 * Registration is active
76
+	 */
77
+	const status_id_approved = 'RAP';
78
+
79
+	/**
80
+	 * Status ID (STS_ID on esp_status table) to indicate a registration was CANCELLED by the attendee.
81
+	 * Payments are NOT allowed.
82
+	 * NO space reserved.
83
+	 * Registration is NOT active
84
+	 */
85
+	const status_id_cancelled = 'RCN';
86
+
87
+	/**
88
+	 * Status ID (STS_ID on esp_status table) to indicate a registration was DECLINED by the Event Admin
89
+	 * Payments are NOT allowed.
90
+	 * No space reserved.
91
+	 * Registration is NOT active
92
+	 */
93
+	const status_id_declined = 'RDC';
94
+
95
+	/**
96
+	 * @var TableAnalysis $table_analysis
97
+	 */
98
+	protected $_table_analysis;
99
+
100
+
101
+	/**
102
+	 *    private constructor to prevent direct creation
103
+	 *
104
+	 * @Constructor
105
+	 * @access protected
106
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
107
+	 *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
108
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
109
+	 *                         timezone in the 'timezone_string' wp option)
110
+	 * @throws EE_Error
111
+	 */
112
+	protected function __construct($timezone = null)
113
+	{
114
+		$this->_table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
115
+		$this->singular_item = esc_html__('Registration', 'event_espresso');
116
+		$this->plural_item = esc_html__('Registrations', 'event_espresso');
117
+		$this->_tables = array(
118
+			'Registration' => new EE_Primary_Table('esp_registration', 'REG_ID'),
119
+		);
120
+		$this->_fields = array(
121
+			'Registration' => array(
122
+				'REG_ID' => new EE_Primary_Key_Int_Field(
123
+					'REG_ID',
124
+					esc_html__('Registration ID', 'event_espresso')
125
+				),
126
+				'EVT_ID' => new EE_Foreign_Key_Int_Field(
127
+					'EVT_ID',
128
+					esc_html__('Event ID', 'event_espresso'),
129
+					false,
130
+					0,
131
+					'Event'
132
+				),
133
+				'ATT_ID' => new EE_Foreign_Key_Int_Field(
134
+					'ATT_ID',
135
+					esc_html__('Attendee ID', 'event_espresso'),
136
+					false,
137
+					0,
138
+					'Attendee'
139
+				),
140
+				'TXN_ID' => new EE_Foreign_Key_Int_Field(
141
+					'TXN_ID',
142
+					esc_html__('Transaction ID', 'event_espresso'),
143
+					false,
144
+					0,
145
+					'Transaction'
146
+				),
147
+				'TKT_ID' => new EE_Foreign_Key_Int_Field(
148
+					'TKT_ID',
149
+					esc_html__('Ticket ID', 'event_espresso'),
150
+					false,
151
+					0,
152
+					'Ticket'
153
+				),
154
+				'STS_ID' => new EE_Foreign_Key_String_Field(
155
+					'STS_ID',
156
+					esc_html__('Status ID', 'event_espresso'),
157
+					false,
158
+					EEM_Registration::status_id_incomplete,
159
+					'Status'
160
+				),
161
+				'REG_date' => new EE_Datetime_Field(
162
+					'REG_date',
163
+					esc_html__('Time registration occurred', 'event_espresso'),
164
+					false,
165
+					EE_Datetime_Field::now,
166
+					$timezone
167
+				),
168
+				'REG_final_price' => new EE_Money_Field(
169
+					'REG_final_price',
170
+					esc_html__('Registration\'s share of the transaction total', 'event_espresso'),
171
+					false,
172
+					0
173
+				),
174
+				'REG_paid' => new EE_Money_Field(
175
+					'REG_paid',
176
+					esc_html__('Amount paid to date towards registration', 'event_espresso'),
177
+					false,
178
+					0
179
+				),
180
+				'REG_session' => new EE_Plain_Text_Field(
181
+					'REG_session',
182
+					esc_html__('Session ID of registration', 'event_espresso'),
183
+					false,
184
+					''
185
+				),
186
+				'REG_code' => new EE_Plain_Text_Field(
187
+					'REG_code',
188
+					esc_html__('Unique Code for this registration', 'event_espresso'),
189
+					false,
190
+					''
191
+				),
192
+				'REG_url_link' => new EE_Plain_Text_Field(
193
+					'REG_url_link',
194
+					esc_html__('String to be used in URL for identifying registration', 'event_espresso'),
195
+					false,
196
+					''
197
+				),
198
+				'REG_count' => new EE_Integer_Field(
199
+					'REG_count',
200
+					esc_html__('Count of this registration in the group registration ', 'event_espresso'),
201
+					true,
202
+					1
203
+				),
204
+				'REG_group_size' => new EE_Integer_Field(
205
+					'REG_group_size',
206
+					esc_html__('Number of registrations on this group', 'event_espresso'),
207
+					false,
208
+					1
209
+				),
210
+				'REG_att_is_going' => new EE_Boolean_Field(
211
+					'REG_att_is_going',
212
+					esc_html__('Flag indicating the registrant plans on attending', 'event_espresso'),
213
+					false,
214
+					false
215
+				),
216
+				'REG_deleted' => new EE_Trashed_Flag_Field(
217
+					'REG_deleted',
218
+					esc_html__('Flag indicating if registration has been archived or not.', 'event_espresso'),
219
+					false,
220
+					false
221
+				),
222
+			),
223
+		);
224
+		$this->_model_relations = array(
225
+			'Event' => new EE_Belongs_To_Relation(),
226
+			'Attendee' => new EE_Belongs_To_Relation(),
227
+			'Transaction' => new EE_Belongs_To_Relation(),
228
+			'Ticket' => new EE_Belongs_To_Relation(),
229
+			'Status' => new EE_Belongs_To_Relation(),
230
+			'Answer' => new EE_Has_Many_Relation(),
231
+			'Checkin' => new EE_Has_Many_Relation(),
232
+			'Registration_Payment' => new EE_Has_Many_Relation(),
233
+			'Payment' => new EE_HABTM_Relation('Registration_Payment'),
234
+			'Message' => new EE_Has_Many_Any_Relation(false)
235
+			// allow deletes even if there are messages in the queue related
236
+		);
237
+		$this->_model_chain_to_wp_user = 'Event';
238
+		parent::__construct($timezone);
239
+	}
240
+
241
+
242
+	/**
243
+	 * a list of ALL valid registration statuses currently in use within the system
244
+	 * generated by combining the filterable active and inactive reg status arrays
245
+	 *
246
+	 * @return array
247
+	 */
248
+	public static function reg_statuses()
249
+	{
250
+		return array_unique(
251
+			array_merge(
252
+				EEM_Registration::active_reg_statuses(),
253
+				EEM_Registration::inactive_reg_statuses()
254
+			)
255
+		);
256
+	}
257
+
258
+
259
+	/**
260
+	 * reg_statuses_that_allow_payment
261
+	 * a filterable list of registration statuses that allow a registrant to make a payment
262
+	 *
263
+	 * @access public
264
+	 * @return array
265
+	 */
266
+	public static function reg_statuses_that_allow_payment()
267
+	{
268
+		return apply_filters(
269
+			'FHEE__EEM_Registration__reg_statuses_that_allow_payment',
270
+			array(
271
+				EEM_Registration::status_id_approved,
272
+				EEM_Registration::status_id_pending_payment,
273
+			)
274
+		);
275
+	}
276
+
277
+
278
+	/**
279
+	 * active_reg_statuses
280
+	 * a filterable list of registration statuses that are considered active
281
+	 *
282
+	 * @access public
283
+	 * @return array
284
+	 */
285
+	public static function active_reg_statuses()
286
+	{
287
+		return apply_filters(
288
+			'FHEE__EEM_Registration__active_reg_statuses',
289
+			array(
290
+				EEM_Registration::status_id_approved,
291
+				EEM_Registration::status_id_pending_payment,
292
+				EEM_Registration::status_id_wait_list,
293
+				EEM_Registration::status_id_not_approved,
294
+			)
295
+		);
296
+	}
297
+
298
+
299
+	/**
300
+	 * inactive_reg_statuses
301
+	 * a filterable list of registration statuses that are not considered active
302
+	 *
303
+	 * @access public
304
+	 * @return array
305
+	 */
306
+	public static function inactive_reg_statuses()
307
+	{
308
+		return apply_filters(
309
+			'FHEE__EEM_Registration__inactive_reg_statuses',
310
+			array(
311
+				EEM_Registration::status_id_incomplete,
312
+				EEM_Registration::status_id_cancelled,
313
+				EEM_Registration::status_id_declined,
314
+			)
315
+		);
316
+	}
317
+
318
+
319
+	/**
320
+	 *    closed_reg_statuses
321
+	 *    a filterable list of registration statuses that are considered "closed"
322
+	 * meaning they should not be considered in any calculations involving monies owing
323
+	 *
324
+	 * @access public
325
+	 * @return array
326
+	 */
327
+	public static function closed_reg_statuses()
328
+	{
329
+		return apply_filters(
330
+			'FHEE__EEM_Registration__closed_reg_statuses',
331
+			array(
332
+				EEM_Registration::status_id_cancelled,
333
+				EEM_Registration::status_id_declined,
334
+				EEM_Registration::status_id_wait_list,
335
+			)
336
+		);
337
+	}
338
+
339
+
340
+	/**
341
+	 *        get list of registration statuses
342
+	 *
343
+	 * @access public
344
+	 * @param array $exclude The status ids to exclude from the returned results
345
+	 * @param bool $translated If true will return the values as singular localized strings
346
+	 * @return array
347
+	 * @throws EE_Error
348
+	 */
349
+	public static function reg_status_array($exclude = array(), $translated = false)
350
+	{
351
+		EEM_Registration::instance()->_get_registration_status_array($exclude);
352
+		return $translated
353
+			? EEM_Status::instance()->localized_status(self::$_reg_status, false, 'sentence')
354
+			: self::$_reg_status;
355
+	}
356
+
357
+
358
+	/**
359
+	 *    get list of registration statuses
360
+	 *
361
+	 * @access private
362
+	 * @param array $exclude
363
+	 * @return void
364
+	 * @throws EE_Error
365
+	 */
366
+	private function _get_registration_status_array($exclude = array())
367
+	{
368
+		// in the very rare circumstance that we are deleting a model's table's data
369
+		// and the table hasn't actually been created, this could have an error
370
+		/** @type WPDB $wpdb */
371
+		global $wpdb;
372
+		if ($this->_get_table_analysis()->tableExists($wpdb->prefix . 'esp_status')) {
373
+			$results = $wpdb->get_results(
374
+				"SELECT STS_ID, STS_code FROM {$wpdb->prefix}esp_status WHERE STS_type = 'registration'"
375
+			);
376
+			self::$_reg_status = array();
377
+			foreach ($results as $status) {
378
+				if (!in_array($status->STS_ID, $exclude, true)) {
379
+					self::$_reg_status[ $status->STS_ID ] = $status->STS_code;
380
+				}
381
+			}
382
+		}
383
+	}
384
+
385
+
386
+	/**
387
+	 * Gets the injected table analyzer, or throws an exception
388
+	 *
389
+	 * @return TableAnalysis
390
+	 * @throws EE_Error
391
+	 */
392
+	protected function _get_table_analysis()
393
+	{
394
+		if ($this->_table_analysis instanceof TableAnalysis) {
395
+			return $this->_table_analysis;
396
+		}
397
+		throw new EE_Error(
398
+			sprintf(
399
+				esc_html__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
400
+				get_class($this)
401
+			)
402
+		);
403
+	}
404
+
405
+
406
+	/**
407
+	 * This returns a wpdb->results array of all registration date month and years matching the incoming query params
408
+	 * and grouped by month and year.
409
+	 *
410
+	 * @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
411
+	 * @return array
412
+	 * @throws EE_Error
413
+	 */
414
+	public function get_reg_months_and_years($where_params)
415
+	{
416
+		$query_params[0] = $where_params;
417
+		$query_params['group_by'] = array('reg_year', 'reg_month');
418
+		$query_params['order_by'] = array('REG_date' => 'DESC');
419
+		$columns_to_select = array(
420
+			'reg_year' => array('YEAR(REG_date)', '%s'),
421
+			'reg_month' => array('MONTHNAME(REG_date)', '%s'),
422
+		);
423
+		return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
424
+	}
425
+
426
+
427
+	/**
428
+	 * retrieve ALL registrations for a particular Attendee from db
429
+	 *
430
+	 * @param int $ATT_ID
431
+	 * @return EE_Base_Class[]|EE_Registration[]|null
432
+	 * @throws EE_Error
433
+	 */
434
+	public function get_all_registrations_for_attendee($ATT_ID = 0)
435
+	{
436
+		if (!$ATT_ID) {
437
+			return null;
438
+		}
439
+		return $this->get_all(array(array('ATT_ID' => $ATT_ID)));
440
+	}
441
+
442
+
443
+	/**
444
+	 * Gets a registration given their REG_url_link. Yes, this should usually
445
+	 * be passed via a GET parameter.
446
+	 *
447
+	 * @param string $REG_url_link
448
+	 * @return EE_Base_Class|EE_Registration|null
449
+	 * @throws EE_Error
450
+	 */
451
+	public function get_registration_for_reg_url_link($REG_url_link)
452
+	{
453
+		if (!$REG_url_link) {
454
+			return null;
455
+		}
456
+		return $this->get_one(array(array('REG_url_link' => $REG_url_link)));
457
+	}
458
+
459
+
460
+	/**
461
+	 *        retrieve registration for a specific transaction attendee from db
462
+	 *
463
+	 * @access        public
464
+	 * @param    int $TXN_ID
465
+	 * @param    int $ATT_ID
466
+	 * @param    int $att_nmbr in case the ATT_ID is the same for multiple registrations (same details used) then the
467
+	 *                         attendee number is required
468
+	 * @return        mixed        array on success, FALSE on fail
469
+	 * @throws EE_Error
470
+	 */
471
+	public function get_registration_for_transaction_attendee($TXN_ID = 0, $ATT_ID = 0, $att_nmbr = 0)
472
+	{
473
+		return $this->get_one(array(
474
+			array(
475
+				'TXN_ID' => $TXN_ID,
476
+				'ATT_ID' => $ATT_ID,
477
+			),
478
+			'limit' => array(min($att_nmbr - 1, 0), 1),
479
+		));
480
+	}
481
+
482
+
483
+	/**
484
+	 *        get the number of registrations per day  for the Registration Admin page Reports Tab.
485
+	 *        (doesn't utilize models because it's a fairly specialized query)
486
+	 *
487
+	 * @access        public
488
+	 * @param $period string which can be passed to php's strtotime function (eg "-1 month")
489
+	 * @return stdClass[] with properties regDate and total
490
+	 * @throws EE_Error
491
+	 */
492
+	public function get_registrations_per_day_report($period = '-1 month')
493
+	{
494
+		$sql_date = $this->convert_datetime_for_query(
495
+			'REG_date',
496
+			date('Y-m-d H:i:s', strtotime($period)),
497
+			'Y-m-d H:i:s',
498
+			'UTC'
499
+		);
500
+		$where = array(
501
+			'REG_date' => array('>=', $sql_date),
502
+			'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
503
+		);
504
+		if (!EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_day_report')) {
505
+			$where['Event.EVT_wp_user'] = get_current_user_id();
506
+		}
507
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'REG_date');
508
+		$results = $this->_get_all_wpdb_results(
509
+			array(
510
+				$where,
511
+				'group_by' => 'regDate',
512
+				'order_by' => array('REG_date' => 'ASC'),
513
+			),
514
+			OBJECT,
515
+			array(
516
+				'regDate' => array('DATE(' . $query_interval . ')', '%s'),
517
+				'total' => array('count(REG_ID)', '%d'),
518
+			)
519
+		);
520
+		return $results;
521
+	}
522
+
523
+
524
+	/**
525
+	 * Get the number of registrations per day including the count of registrations for each Registration Status.
526
+	 * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
527
+	 *
528
+	 * @param string $period
529
+	 * @return stdClass[] with properties Registration_REG_date and a column for each registration status as the STS_ID
530
+	 * @throws EE_Error
531
+	 *                    (i.e. RAP)
532
+	 */
533
+	public function get_registrations_per_day_and_per_status_report($period = '-1 month')
534
+	{
535
+		global $wpdb;
536
+		$registration_table = $wpdb->prefix . 'esp_registration';
537
+		$event_table = $wpdb->posts;
538
+		$sql_date = date('Y-m-d H:i:s', strtotime($period));
539
+		// prepare the query interval for displaying offset
540
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'dates.REG_date');
541
+		// inner date query
542
+		$inner_date_query = "SELECT DISTINCT REG_date from {$registration_table} ";
543
+		$inner_where = ' WHERE';
544
+		// exclude events not authored by user if permissions in effect
545
+		if (!EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
546
+			$inner_date_query .= "LEFT JOIN {$event_table} ON ID = EVT_ID";
547
+			$inner_where .= ' post_author = ' . get_current_user_id() . ' AND';
548
+		}
549
+		$inner_where .= " REG_date >= '{$sql_date}'";
550
+		$inner_date_query .= $inner_where;
551
+		// start main query
552
+		$select = "SELECT DATE({$query_interval}) as Registration_REG_date, ";
553
+		$join = '';
554
+		$join_parts = array();
555
+		$select_parts = array();
556
+		// loop through registration stati to do parts for each status.
557
+		foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
558
+			if ($STS_ID === EEM_Registration::status_id_incomplete) {
559
+				continue;
560
+			}
561
+			$select_parts[] = "COUNT({$STS_code}.REG_ID) as {$STS_ID}";
562
+			$join_parts[] = "{$registration_table} AS {$STS_code} ON {$STS_code}.REG_date = dates.REG_date AND {$STS_code}.STS_ID = '{$STS_ID}'";
563
+		}
564
+		// setup the selects
565
+		$select .= implode(', ', $select_parts);
566
+		$select .= " FROM ($inner_date_query) AS dates LEFT JOIN ";
567
+		// setup the joins
568
+		$join .= implode(' LEFT JOIN ', $join_parts);
569
+		// now let's put it all together
570
+		$query = $select . $join . ' GROUP BY Registration_REG_date';
571
+		// and execute it
572
+		return $wpdb->get_results($query, ARRAY_A);
573
+	}
574
+
575
+
576
+	/**
577
+	 *        get the number of registrations per event  for the Registration Admin page Reports Tab
578
+	 *
579
+	 * @access        public
580
+	 * @param $period string which can be passed to php's strtotime function (eg "-1 month")
581
+	 * @return stdClass[] each with properties event_name, reg_limit, and total
582
+	 * @throws EE_Error
583
+	 */
584
+	public function get_registrations_per_event_report($period = '-1 month')
585
+	{
586
+		$date_sql = $this->convert_datetime_for_query(
587
+			'REG_date',
588
+			date('Y-m-d H:i:s', strtotime($period)),
589
+			'Y-m-d H:i:s',
590
+			'UTC'
591
+		);
592
+		$where = array(
593
+			'REG_date' => array('>=', $date_sql),
594
+			'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
595
+		);
596
+		if (!EE_Registry::instance()->CAP->current_user_can(
597
+			'ee_read_others_registrations',
598
+			'reg_per_event_report'
599
+		)
600
+		) {
601
+			$where['Event.EVT_wp_user'] = get_current_user_id();
602
+		}
603
+		$results = $this->_get_all_wpdb_results(
604
+			array(
605
+			$where,
606
+			'group_by' => 'Event.EVT_name',
607
+			'order_by' => 'Event.EVT_name',
608
+			'limit' => array(0, 24),
609
+			),
610
+			OBJECT,
611
+			array(
612
+				'event_name' => array('Event_CPT.post_title', '%s'),
613
+				'total' => array('COUNT(REG_ID)', '%s'),
614
+			)
615
+		);
616
+		return $results;
617
+	}
618
+
619
+
620
+	/**
621
+	 * Get the number of registrations per event grouped by registration status.
622
+	 * Note: EEM_Registration::status_id_incomplete registrations are excluded from the results.
623
+	 *
624
+	 * @param string $period
625
+	 * @return stdClass[] with properties `Registration_Event` and a column for each registration status as the STS_ID
626
+	 * @throws EE_Error
627
+	 *                    (i.e. RAP)
628
+	 */
629
+	public function get_registrations_per_event_and_per_status_report($period = '-1 month')
630
+	{
631
+		global $wpdb;
632
+		$registration_table = $wpdb->prefix . 'esp_registration';
633
+		$event_table = $wpdb->posts;
634
+		$sql_date = date('Y-m-d H:i:s', strtotime($period));
635
+		// inner date query
636
+		$inner_date_query = "SELECT DISTINCT EVT_ID, REG_date from $registration_table ";
637
+		$inner_where = ' WHERE';
638
+		// exclude events not authored by user if permissions in effect
639
+		if (!EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
640
+			$inner_date_query .= "LEFT JOIN {$event_table} ON ID = EVT_ID";
641
+			$inner_where .= ' post_author = ' . get_current_user_id() . ' AND';
642
+		}
643
+		$inner_where .= " REG_date >= '{$sql_date}'";
644
+		$inner_date_query .= $inner_where;
645
+		// build main query
646
+		$select = 'SELECT Event.post_title as Registration_Event, ';
647
+		$join = '';
648
+		$join_parts = array();
649
+		$select_parts = array();
650
+		// loop through registration stati to do parts for each status.
651
+		foreach (EEM_Registration::reg_status_array() as $STS_ID => $STS_code) {
652
+			if ($STS_ID === EEM_Registration::status_id_incomplete) {
653
+				continue;
654
+			}
655
+			$select_parts[] = "COUNT({$STS_code}.REG_ID) as {$STS_ID}";
656
+			$join_parts[] = "{$registration_table} AS {$STS_code} ON {$STS_code}.EVT_ID = dates.EVT_ID AND {$STS_code}.STS_ID = '{$STS_ID}' AND {$STS_code}.REG_date = dates.REG_date";
657
+		}
658
+		// setup the selects
659
+		$select .= implode(', ', $select_parts);
660
+		$select .= " FROM ($inner_date_query) AS dates LEFT JOIN $event_table as Event ON Event.ID = dates.EVT_ID LEFT JOIN ";
661
+		// setup remaining joins
662
+		$join .= implode(' LEFT JOIN ', $join_parts);
663
+		// now put it all together
664
+		$query = $select . $join . ' GROUP BY Registration_Event';
665
+		// and execute
666
+		return $wpdb->get_results($query, ARRAY_A);
667
+	}
668
+
669
+
670
+	/**
671
+	 * Returns the EE_Registration of the primary attendee on the transaction id provided
672
+	 *
673
+	 * @param int $TXN_ID
674
+	 * @return EE_Base_Class|EE_Registration|null
675
+	 * @throws EE_Error
676
+	 */
677
+	public function get_primary_registration_for_transaction_ID($TXN_ID = 0)
678
+	{
679
+		if (!$TXN_ID) {
680
+			return null;
681
+		}
682
+		return $this->get_one(array(
683
+			array(
684
+				'TXN_ID' => $TXN_ID,
685
+				'REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT,
686
+			),
687
+		));
688
+	}
689
+
690
+
691
+	/**
692
+	 *        get_event_registration_count
693
+	 *
694
+	 * @access public
695
+	 * @param int $EVT_ID
696
+	 * @param boolean $for_incomplete_payments
697
+	 * @return int
698
+	 * @throws EE_Error
699
+	 */
700
+	public function get_event_registration_count($EVT_ID, $for_incomplete_payments = false)
701
+	{
702
+		// we only count approved registrations towards registration limits
703
+		$query_params = array(array('EVT_ID' => $EVT_ID, 'STS_ID' => self::status_id_approved));
704
+		if ($for_incomplete_payments) {
705
+			$query_params[0]['Transaction.STS_ID'] = array('!=', EEM_Transaction::complete_status_code);
706
+		}
707
+		return $this->count($query_params);
708
+	}
709
+
710
+
711
+	/**
712
+	 * Deletes all registrations with no transactions. Note that this needs to be very efficient
713
+	 * and so it uses wpdb directly
714
+	 *
715
+	 * @global WPDB $wpdb
716
+	 * @return int number deleted
717
+	 * @throws EE_Error
718
+	 */
719
+	public function delete_registrations_with_no_transaction()
720
+	{
721
+		/** @type WPDB $wpdb */
722
+		global $wpdb;
723
+		return $wpdb->query(
724
+			'DELETE r FROM '
725
+			. $this->table()
726
+			. ' r LEFT JOIN '
727
+			. EEM_Transaction::instance()->table()
728
+			. ' t ON r.TXN_ID = t.TXN_ID WHERE t.TXN_ID IS NULL'
729
+		);
730
+	}
731
+
732
+
733
+	/**
734
+	 *  Count registrations checked into (or out of) a datetime
735
+	 *
736
+	 * @param int $DTT_ID datetime ID
737
+	 * @param boolean $checked_in whether to count registrations checked IN or OUT
738
+	 * @return int
739
+	 * @throws EE_Error
740
+	 */
741
+	public function count_registrations_checked_into_datetime($DTT_ID, $checked_in = true)
742
+	{
743
+		global $wpdb;
744
+		// subquery to get latest checkin
745
+		$query = $wpdb->prepare(
746
+			'SELECT '
747
+			. 'COUNT( DISTINCT checkins.REG_ID ) '
748
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
749
+			. '( SELECT '
750
+			. 'max( CHK_timestamp ) AS latest_checkin, '
751
+			. 'REG_ID AS REG_ID '
752
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' '
753
+			. 'WHERE DTT_ID=%d '
754
+			. 'GROUP BY REG_ID'
755
+			. ') AS most_recent_checkin_per_reg '
756
+			. 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
757
+			. 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
758
+			. 'WHERE '
759
+			. 'checkins.CHK_in=%d',
760
+			$DTT_ID,
761
+			$checked_in
762
+		);
763
+		return (int) $wpdb->get_var($query);
764
+	}
765
+
766
+
767
+	/**
768
+	 *  Count registrations checked into (or out of) an event.
769
+	 *
770
+	 * @param int $EVT_ID event ID
771
+	 * @param boolean $checked_in whether to count registrations checked IN or OUT
772
+	 * @return int
773
+	 * @throws EE_Error
774
+	 */
775
+	public function count_registrations_checked_into_event($EVT_ID, $checked_in = true)
776
+	{
777
+		global $wpdb;
778
+		// subquery to get latest checkin
779
+		$query = $wpdb->prepare(
780
+			'SELECT '
781
+			. 'COUNT( DISTINCT checkins.REG_ID ) '
782
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS checkins INNER JOIN'
783
+			. '( SELECT '
784
+			. 'max( CHK_timestamp ) AS latest_checkin, '
785
+			. 'REG_ID AS REG_ID '
786
+			. 'FROM ' . EEM_Checkin::instance()->table() . ' AS c '
787
+			. 'INNER JOIN ' . EEM_Datetime::instance()->table() . ' AS d '
788
+			. 'ON c.DTT_ID=d.DTT_ID '
789
+			. 'WHERE d.EVT_ID=%d '
790
+			. 'GROUP BY REG_ID'
791
+			. ') AS most_recent_checkin_per_reg '
792
+			. 'ON checkins.REG_ID=most_recent_checkin_per_reg.REG_ID '
793
+			. 'AND checkins.CHK_timestamp = most_recent_checkin_per_reg.latest_checkin '
794
+			. 'WHERE '
795
+			. 'checkins.CHK_in=%d',
796
+			$EVT_ID,
797
+			$checked_in
798
+		);
799
+		return (int) $wpdb->get_var($query);
800
+	}
801
+
802
+
803
+	/**
804
+	 * The purpose of this method is to retrieve an array of
805
+	 * EE_Registration objects that represent the latest registration
806
+	 * for each ATT_ID given in the function argument.
807
+	 *
808
+	 * @param array $attendee_ids
809
+	 * @return EE_Base_Class[]|EE_Registration[]
810
+	 * @throws EE_Error
811
+	 */
812
+	public function get_latest_registration_for_each_of_given_contacts($attendee_ids = array())
813
+	{
814
+		// first do a native wp_query to get the latest REG_ID's matching these attendees.
815
+		global $wpdb;
816
+		$registration_table = $wpdb->prefix . 'esp_registration';
817
+		$attendee_table = $wpdb->posts;
818
+		$attendee_ids = is_array($attendee_ids)
819
+			? array_map('absint', $attendee_ids)
820
+			: array((int) $attendee_ids);
821
+		$ATT_IDs = implode(',', $attendee_ids);
822
+		// first we do a query to get the registration ids
823
+		// (because a group by before order by causes the order by to be ignored.)
824
+		$registration_id_query = "
825 825
 			SELECT registrations.registration_ids as registration_id
826 826
 			FROM (
827 827
 				SELECT
@@ -835,61 +835,61 @@  discard block
 block discarded – undo
835 835
 			  ) AS registrations
836 836
 			  GROUP BY registrations.attendee_ids
837 837
 		";
838
-        $registration_ids = $wpdb->get_results($registration_id_query, ARRAY_A);
839
-        if (empty($registration_ids)) {
840
-            return array();
841
-        }
842
-        $ids_for_model_query = array();
843
-        // let's flatten the ids so they can be used in the model query.
844
-        foreach ($registration_ids as $registration_id) {
845
-            if (isset($registration_id['registration_id'])) {
846
-                $ids_for_model_query[] = $registration_id['registration_id'];
847
-            }
848
-        }
849
-        // construct query
850
-        $_where = array(
851
-            'REG_ID' => array('IN', $ids_for_model_query),
852
-        );
853
-        return $this->get_all(array($_where));
854
-    }
855
-
856
-
857
-
858
-    /**
859
-     * returns a count of registrations for the supplied event having the status as specified
860
-     *
861
-     * @param int $EVT_ID
862
-     * @param array $statuses
863
-     * @return int
864
-     * @throws InvalidArgumentException
865
-     * @throws InvalidStatusException
866
-     * @throws EE_Error
867
-     */
868
-    public function event_reg_count_for_statuses($EVT_ID, $statuses = array())
869
-    {
870
-        $EVT_ID = absint($EVT_ID);
871
-        if (! $EVT_ID) {
872
-            throw new InvalidArgumentException(
873
-                esc_html__('An invalid Event ID was supplied.', 'event_espresso')
874
-            );
875
-        }
876
-        $statuses = is_array($statuses) ? $statuses : array($statuses);
877
-        $statuses = ! empty($statuses) ? $statuses : array(EEM_Registration::status_id_approved);
878
-        $valid_reg_statuses = EEM_Registration::reg_statuses();
879
-        foreach ($statuses as $status) {
880
-            if (! in_array($status, $valid_reg_statuses, true)) {
881
-                throw new InvalidStatusException($status, esc_html__('Registration', 'event_espresso'));
882
-            }
883
-        }
884
-        return $this->count(
885
-            array(
886
-                array(
887
-                    'EVT_ID' => $EVT_ID,
888
-                    'STS_ID' => array('IN', $statuses),
889
-                ),
890
-            ),
891
-            'REG_ID',
892
-            true
893
-        );
894
-    }
838
+		$registration_ids = $wpdb->get_results($registration_id_query, ARRAY_A);
839
+		if (empty($registration_ids)) {
840
+			return array();
841
+		}
842
+		$ids_for_model_query = array();
843
+		// let's flatten the ids so they can be used in the model query.
844
+		foreach ($registration_ids as $registration_id) {
845
+			if (isset($registration_id['registration_id'])) {
846
+				$ids_for_model_query[] = $registration_id['registration_id'];
847
+			}
848
+		}
849
+		// construct query
850
+		$_where = array(
851
+			'REG_ID' => array('IN', $ids_for_model_query),
852
+		);
853
+		return $this->get_all(array($_where));
854
+	}
855
+
856
+
857
+
858
+	/**
859
+	 * returns a count of registrations for the supplied event having the status as specified
860
+	 *
861
+	 * @param int $EVT_ID
862
+	 * @param array $statuses
863
+	 * @return int
864
+	 * @throws InvalidArgumentException
865
+	 * @throws InvalidStatusException
866
+	 * @throws EE_Error
867
+	 */
868
+	public function event_reg_count_for_statuses($EVT_ID, $statuses = array())
869
+	{
870
+		$EVT_ID = absint($EVT_ID);
871
+		if (! $EVT_ID) {
872
+			throw new InvalidArgumentException(
873
+				esc_html__('An invalid Event ID was supplied.', 'event_espresso')
874
+			);
875
+		}
876
+		$statuses = is_array($statuses) ? $statuses : array($statuses);
877
+		$statuses = ! empty($statuses) ? $statuses : array(EEM_Registration::status_id_approved);
878
+		$valid_reg_statuses = EEM_Registration::reg_statuses();
879
+		foreach ($statuses as $status) {
880
+			if (! in_array($status, $valid_reg_statuses, true)) {
881
+				throw new InvalidStatusException($status, esc_html__('Registration', 'event_espresso'));
882
+			}
883
+		}
884
+		return $this->count(
885
+			array(
886
+				array(
887
+					'EVT_ID' => $EVT_ID,
888
+					'STS_ID' => array('IN', $statuses),
889
+				),
890
+			),
891
+			'REG_ID',
892
+			true
893
+		);
894
+	}
895 895
 }
Please login to merge, or discard this patch.
core/db_models/strategies/EE_Default_Where_Conditions.strategy.php 1 patch
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 /**
4 4
  *
5 5
  * Class EE_Default_Where_Conditions
6
-  *
6
+ *
7 7
  * Strategy to be used for getting default where conditions for EEM_Base children.
8 8
  * Should be initialized and set on construction of model
9 9
  *
@@ -16,143 +16,143 @@  discard block
 block discarded – undo
16 16
 class EE_Default_Where_Conditions
17 17
 {
18 18
 
19
-    /**
20
-     * This const can be used in EE_Default_Where_Conditions values, and at the time of querying it will be
21
-     * replaced with the current user's ID (because we don't want to use the current user's ID at time of
22
-     * initializing the models because it's too early)
23
-     */
24
-    const current_user_placeholder = '%$current_user_placeholder_should_be_replaced_automatically$%';
25
-
26
-    /**
27
-     * This const can be used in EE_Default_Where_Conditions where parameters as the name
28
-     * of the user field. When we are actually generating the where conditions it will be
29
-     * replaced with the model's wp user fieldname
30
-     */
31
-    const user_field_name_placeholder = '%$user_field_name_placeholder$%';
32
-
33
-    /**
34
-     * Model for which this strategy find default where conditions
35
-     * @var EEM_Base
36
-     */
37
-    protected $_model;
38
-
39
-    /**
40
-     * Where conditions specified on construction
41
-     * @var array
42
-     */
43
-    protected $_where_conditions_provided = array();
44
-
45
-    /**
46
-     * Custom where conditions. Model relation chains will be automatically added
47
-     * onto any field names
48
-     * @param array $custom_where_conditions
49
-     */
50
-    public function __construct($custom_where_conditions = array())
51
-    {
52
-        $this->_where_conditions_provided = $custom_where_conditions;
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * finalizes construction of the strategy for use in getting default where conditions
59
-     * for querying of the model.
60
-     * @param EEM_Base $model
61
-     */
62
-    public function _finalize_construct(EEM_Base $model)
63
-    {
64
-        $this->_model = $model;
65
-    }
66
-
67
-
68
-
69
-    /**
70
-     * Returns the where conditions explicitly passed in the constructor
71
-     * @return array
72
-     */
73
-    public function get_where_conditions_provided()
74
-    {
75
-        return $this->_where_conditions_provided;
76
-    }
77
-
78
-
79
-
80
-    /**
81
-     * Gets the where conditions to be added onto the query
82
-     * @param string $model_relation_chain
83
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
84
-     */
85
-    public function get_default_where_conditions($model_relation_chain = '')
86
-    {
87
-        return $this->prepare_where_conditions_for_querying(array_merge($this->_get_default_where_conditions(), $this->get_where_conditions_provided()), $model_relation_chain);
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     * Gets the default where conditions that are specific to this child of EE_Default_Where_Conditions.
94
-     * Adding model relation chains is handled by the public method get_default_where_conditions
95
-     * @return array
96
-     */
97
-    protected function _get_default_where_conditions()
98
-    {
99
-        return array();
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     * Takes the default query parameters, and traverses them, adding the model relation chain
106
-     * onto them (intelligently doesn't do that to logic query params like NOT, OR, and AND)
107
-     * @param array $where_conditions
108
-     * @param string $model_relation_chain
109
-     * @return array
110
-     * @throws \EE_Error
111
-     */
112
-    public function prepare_where_conditions_for_querying($where_conditions, $model_relation_chain)
113
-    {
114
-        $where_conditions_with_model_relation_chain_prefixes = array();
115
-        if (! is_array($where_conditions)) {
116
-            $where_conditions = array();
117
-        }
118
-        foreach ($where_conditions as $key => $value) {
119
-            if (in_array($key, array( 'OR', 'AND', 'NOT' ))
120
-                || strpos($key, 'OR*') !== false
121
-                || strpos($key, 'AND*') !== false
122
-                || strpos($key, 'NOT*') !== false
123
-            ) {
124
-                $where_conditions_with_model_relation_chain_prefixes[ $key ] = $this->prepare_where_conditions_for_querying(
125
-                    $value,
126
-                    $model_relation_chain
127
-                );
128
-            } else {
129
-                if ($model_relation_chain != ''
130
-                    && $model_relation_chain[ strlen($model_relation_chain) - 1 ] != '.'
131
-                ) {
132
-                    $model_relation_chain = $model_relation_chain . ".";
133
-                }
134
-                // check for the current user id place holder, and if present change it
135
-                if ($value === self::current_user_placeholder) {
136
-                    $value = get_current_user_id();
137
-                }
138
-                // check for user field placeholder
139
-                if ($key == self::user_field_name_placeholder) {
140
-                    if (! $this->_model->wp_user_field_name()) {
141
-                        throw new EE_Error(
142
-                            sprintf(
143
-                                __(
144
-                                    'There is no foreign key to the WP_User model on model %s. Please either modify your default where conditions, add a _model_chain_to_wp_user onto the model, or a proper EE_WP_User_Field onto the model',
145
-                                    'event_espresso'
146
-                                ),
147
-                                $this->_model->get_this_model_name()
148
-                            )
149
-                        );
150
-                    }
151
-                    $key = $this->_model->wp_user_field_name();
152
-                }
153
-                $where_conditions_with_model_relation_chain_prefixes[ $model_relation_chain . $key ] = $value;
154
-            }
155
-        }
156
-        return $where_conditions_with_model_relation_chain_prefixes;
157
-    }
19
+	/**
20
+	 * This const can be used in EE_Default_Where_Conditions values, and at the time of querying it will be
21
+	 * replaced with the current user's ID (because we don't want to use the current user's ID at time of
22
+	 * initializing the models because it's too early)
23
+	 */
24
+	const current_user_placeholder = '%$current_user_placeholder_should_be_replaced_automatically$%';
25
+
26
+	/**
27
+	 * This const can be used in EE_Default_Where_Conditions where parameters as the name
28
+	 * of the user field. When we are actually generating the where conditions it will be
29
+	 * replaced with the model's wp user fieldname
30
+	 */
31
+	const user_field_name_placeholder = '%$user_field_name_placeholder$%';
32
+
33
+	/**
34
+	 * Model for which this strategy find default where conditions
35
+	 * @var EEM_Base
36
+	 */
37
+	protected $_model;
38
+
39
+	/**
40
+	 * Where conditions specified on construction
41
+	 * @var array
42
+	 */
43
+	protected $_where_conditions_provided = array();
44
+
45
+	/**
46
+	 * Custom where conditions. Model relation chains will be automatically added
47
+	 * onto any field names
48
+	 * @param array $custom_where_conditions
49
+	 */
50
+	public function __construct($custom_where_conditions = array())
51
+	{
52
+		$this->_where_conditions_provided = $custom_where_conditions;
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * finalizes construction of the strategy for use in getting default where conditions
59
+	 * for querying of the model.
60
+	 * @param EEM_Base $model
61
+	 */
62
+	public function _finalize_construct(EEM_Base $model)
63
+	{
64
+		$this->_model = $model;
65
+	}
66
+
67
+
68
+
69
+	/**
70
+	 * Returns the where conditions explicitly passed in the constructor
71
+	 * @return array
72
+	 */
73
+	public function get_where_conditions_provided()
74
+	{
75
+		return $this->_where_conditions_provided;
76
+	}
77
+
78
+
79
+
80
+	/**
81
+	 * Gets the where conditions to be added onto the query
82
+	 * @param string $model_relation_chain
83
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
84
+	 */
85
+	public function get_default_where_conditions($model_relation_chain = '')
86
+	{
87
+		return $this->prepare_where_conditions_for_querying(array_merge($this->_get_default_where_conditions(), $this->get_where_conditions_provided()), $model_relation_chain);
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 * Gets the default where conditions that are specific to this child of EE_Default_Where_Conditions.
94
+	 * Adding model relation chains is handled by the public method get_default_where_conditions
95
+	 * @return array
96
+	 */
97
+	protected function _get_default_where_conditions()
98
+	{
99
+		return array();
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 * Takes the default query parameters, and traverses them, adding the model relation chain
106
+	 * onto them (intelligently doesn't do that to logic query params like NOT, OR, and AND)
107
+	 * @param array $where_conditions
108
+	 * @param string $model_relation_chain
109
+	 * @return array
110
+	 * @throws \EE_Error
111
+	 */
112
+	public function prepare_where_conditions_for_querying($where_conditions, $model_relation_chain)
113
+	{
114
+		$where_conditions_with_model_relation_chain_prefixes = array();
115
+		if (! is_array($where_conditions)) {
116
+			$where_conditions = array();
117
+		}
118
+		foreach ($where_conditions as $key => $value) {
119
+			if (in_array($key, array( 'OR', 'AND', 'NOT' ))
120
+				|| strpos($key, 'OR*') !== false
121
+				|| strpos($key, 'AND*') !== false
122
+				|| strpos($key, 'NOT*') !== false
123
+			) {
124
+				$where_conditions_with_model_relation_chain_prefixes[ $key ] = $this->prepare_where_conditions_for_querying(
125
+					$value,
126
+					$model_relation_chain
127
+				);
128
+			} else {
129
+				if ($model_relation_chain != ''
130
+					&& $model_relation_chain[ strlen($model_relation_chain) - 1 ] != '.'
131
+				) {
132
+					$model_relation_chain = $model_relation_chain . ".";
133
+				}
134
+				// check for the current user id place holder, and if present change it
135
+				if ($value === self::current_user_placeholder) {
136
+					$value = get_current_user_id();
137
+				}
138
+				// check for user field placeholder
139
+				if ($key == self::user_field_name_placeholder) {
140
+					if (! $this->_model->wp_user_field_name()) {
141
+						throw new EE_Error(
142
+							sprintf(
143
+								__(
144
+									'There is no foreign key to the WP_User model on model %s. Please either modify your default where conditions, add a _model_chain_to_wp_user onto the model, or a proper EE_WP_User_Field onto the model',
145
+									'event_espresso'
146
+								),
147
+								$this->_model->get_this_model_name()
148
+							)
149
+						);
150
+					}
151
+					$key = $this->_model->wp_user_field_name();
152
+				}
153
+				$where_conditions_with_model_relation_chain_prefixes[ $model_relation_chain . $key ] = $value;
154
+			}
155
+		}
156
+		return $where_conditions_with_model_relation_chain_prefixes;
157
+	}
158 158
 }
Please login to merge, or discard this patch.
core/db_models/strategies/EE_Soft_Delete_Where_Conditions.strategy.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -13,41 +13,41 @@
 block discarded – undo
13 13
  */
14 14
 class EE_Soft_Delete_Where_Conditions extends EE_Default_Where_Conditions
15 15
 {
16
-    /**
17
-     * Strategy for setting default soft delete where conditions. This strategy will find
18
-     * the field of type 'EE_Trashed_Flag_Field', and add a condition that it be FALSE on all queries involving
19
-     * the model.
20
-     * If you want to override these default where conditions, you may explicitly in the query you send to the model.
21
-     * Eg,
22
-     *
23
-     */
24
-    public function __construct()
25
-    {
26
-    }
27
-    /**
28
-     * Gets the where default where conditions for a custom post type model
29
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
30
-     */
31
-    protected function _get_default_where_conditions()
32
-    {
33
-        $trashed_field_name = $this->deleted_field_name();
34
-        return array(
35
-            $trashed_field_name => false
36
-        );
37
-    }
38
-    /**
39
-     * Searches for field on the model of type 'deleted_flag'. if it is found,
40
-     * returns it's name.
41
-     * @return string
42
-     * @throws EE_Error
43
-     */
44
-    private function deleted_field_name()
45
-    {
46
-        $field = $this->_model->get_a_field_of_type('EE_Trashed_Flag_Field');
47
-        if ($field) {
48
-            return $field->get_name();
49
-        } else {
50
-            throw new EE_Error(sprintf(__('We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?', 'event_espresso'), get_class($this), get_class($this)));
51
-        }
52
-    }
16
+	/**
17
+	 * Strategy for setting default soft delete where conditions. This strategy will find
18
+	 * the field of type 'EE_Trashed_Flag_Field', and add a condition that it be FALSE on all queries involving
19
+	 * the model.
20
+	 * If you want to override these default where conditions, you may explicitly in the query you send to the model.
21
+	 * Eg,
22
+	 *
23
+	 */
24
+	public function __construct()
25
+	{
26
+	}
27
+	/**
28
+	 * Gets the where default where conditions for a custom post type model
29
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
30
+	 */
31
+	protected function _get_default_where_conditions()
32
+	{
33
+		$trashed_field_name = $this->deleted_field_name();
34
+		return array(
35
+			$trashed_field_name => false
36
+		);
37
+	}
38
+	/**
39
+	 * Searches for field on the model of type 'deleted_flag'. if it is found,
40
+	 * returns it's name.
41
+	 * @return string
42
+	 * @throws EE_Error
43
+	 */
44
+	private function deleted_field_name()
45
+	{
46
+		$field = $this->_model->get_a_field_of_type('EE_Trashed_Flag_Field');
47
+		if ($field) {
48
+			return $field->get_name();
49
+		} else {
50
+			throw new EE_Error(sprintf(__('We are trying to find the deleted flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?', 'event_espresso'), get_class($this), get_class($this)));
51
+		}
52
+	}
53 53
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Message_Template_Group.class.php 1 patch
Indentation   +483 added lines, -483 removed lines patch added patch discarded remove patch
@@ -13,487 +13,487 @@
 block discarded – undo
13 13
 class EE_Message_Template_Group extends EE_Soft_Delete_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * Extra Meta key prefix for whether a given context for this message tmeplate group is active or not.
18
-     */
19
-    const ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX = 'active_context_';
20
-
21
-    /**
22
-     * @param array  $props_n_values
23
-     * @param string $timezone
24
-     * @return EE_Message_Template_Group|mixed
25
-     * @throws EE_Error
26
-     */
27
-    public static function new_instance($props_n_values = array(), $timezone = '')
28
-    {
29
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
30
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone);
31
-    }
32
-
33
-
34
-    /**
35
-     * @param array  $props_n_values
36
-     * @param string $timezone
37
-     * @return EE_Message_Template_Group
38
-     */
39
-    public static function new_instance_from_db($props_n_values = array(), $timezone = '')
40
-    {
41
-        return new self($props_n_values, true, $timezone);
42
-    }
43
-
44
-
45
-    /**
46
-     * @param bool $message_type
47
-     * @throws EE_Error
48
-     */
49
-    public function set_message_type($message_type = false)
50
-    {
51
-        if (! $message_type) {
52
-            throw new EE_Error(esc_html__('Missing required value for the message_type parameter', 'event_espresso'));
53
-        }
54
-        $this->set('MTP_message_type', $message_type);
55
-    }
56
-
57
-
58
-    /**
59
-     * @param bool $messenger
60
-     * @throws EE_Error
61
-     */
62
-    public function set_messenger($messenger = false)
63
-    {
64
-        if (! $messenger) {
65
-            throw new EE_Error(esc_html__('Missing required value for the messenger parameter', 'event_espresso'));
66
-        }
67
-        $this->set('MTP_messenger', $messenger);
68
-    }
69
-
70
-
71
-    /**
72
-     * @param bool $GRP_ID
73
-     * @throws EE_Error
74
-     */
75
-    public function set_group_template_id($GRP_ID = false)
76
-    {
77
-        if (! $GRP_ID) {
78
-            throw new EE_Error(
79
-                esc_html__(
80
-                    'Missing required value for the message template group id',
81
-                    'event_espresso'
82
-                )
83
-            );
84
-        }
85
-        $this->set('GRP_ID', $GRP_ID);
86
-    }
87
-
88
-
89
-    /**
90
-     * get Group ID
91
-     *
92
-     * @access public
93
-     * @return int
94
-     * @throws EE_Error
95
-     */
96
-    public function GRP_ID()
97
-    {
98
-        return $this->get('GRP_ID');
99
-    }
100
-
101
-
102
-    /**
103
-     * get User ID
104
-     *
105
-     * @access public
106
-     * @return int
107
-     * @throws EE_Error
108
-     */
109
-    public function user()
110
-    {
111
-        $user_id = $this->get('MTP_user_id');
112
-        return empty($user_id) ? get_current_user_id() : $user_id;
113
-    }
114
-
115
-
116
-    /**
117
-     * Wrapper for the user function() (preserve backward compat)
118
-     *
119
-     * @since  4.5.0
120
-     * @return int
121
-     * @throws EE_Error
122
-     */
123
-    public function wp_user()
124
-    {
125
-        return $this->user();
126
-    }
127
-
128
-
129
-    /**
130
-     * This simply returns a count of all related events to this message template group
131
-     *
132
-     * @return int
133
-     */
134
-    public function count_events()
135
-    {
136
-        return $this->count_related('Event');
137
-    }
138
-
139
-
140
-    /**
141
-     * returns the name saved in the db for this template
142
-     *
143
-     * @return string
144
-     * @throws EE_Error
145
-     */
146
-    public function name()
147
-    {
148
-        return $this->get('MTP_name');
149
-    }
150
-
151
-
152
-    /**
153
-     * Returns the description saved in the db for this template group
154
-     *
155
-     * @return string
156
-     * @throws EE_Error
157
-     */
158
-    public function description()
159
-    {
160
-        return $this->get('MTP_description');
161
-    }
162
-
163
-
164
-    /**
165
-     * returns all related EE_Message_Template objects
166
-     *
167
-     * @param  array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
168
-     * @return EE_Message_Template[]
169
-     * @throws EE_Error
170
-     */
171
-    public function message_templates($query_params = array())
172
-    {
173
-        return $this->get_many_related('Message_Template', $query_params);
174
-    }
175
-
176
-
177
-    /**
178
-     * get Message Messenger
179
-     *
180
-     * @access public
181
-     * @return string
182
-     * @throws EE_Error
183
-     */
184
-    public function messenger()
185
-    {
186
-        return $this->get('MTP_messenger');
187
-    }
188
-
189
-
190
-    /**
191
-     * get Message Messenger OBJECT
192
-     * If an attempt to get the corresponding messenger object fails, then we set this message
193
-     * template group to inactive, and save to db.  Then return null so client code can handle
194
-     * appropriately.
195
-     *
196
-     * @return EE_messenger
197
-     * @throws EE_Error
198
-     */
199
-    public function messenger_obj()
200
-    {
201
-        $messenger = $this->messenger();
202
-        try {
203
-            $messenger = EEH_MSG_Template::messenger_obj($messenger);
204
-        } catch (EE_Error $e) {
205
-            // if an exception was thrown then let's deactivate this message template group because it means there is no
206
-            // class for this messenger in this group.
207
-            $this->set('MTP_is_active', false);
208
-            $this->save();
209
-            return null;
210
-        }
211
-        return $messenger;
212
-    }
213
-
214
-
215
-    /**
216
-     * get Message Type
217
-     *
218
-     * @access public
219
-     * @return string
220
-     * @throws EE_Error
221
-     */
222
-    public function message_type()
223
-    {
224
-        return $this->get('MTP_message_type');
225
-    }
226
-
227
-
228
-    /**
229
-     * get Message type OBJECT
230
-     * If an attempt to get the corresponding message type object fails, then we set this message
231
-     * template group to inactive, and save to db.  Then return null so client code can handle
232
-     * appropriately.
233
-     *
234
-     * @throws EE_Error
235
-     * @return EE_message_type|false if exception thrown.
236
-     */
237
-    public function message_type_obj()
238
-    {
239
-        $message_type = $this->message_type();
240
-        try {
241
-            $message_type = EEH_MSG_Template::message_type_obj($message_type);
242
-        } catch (EE_Error $e) {
243
-            // if an exception was thrown then let's deactivate this message template group because it means there is no
244
-            // class for the message type in this group.
245
-            $this->set('MTP_is_active', false);
246
-            $this->save();
247
-            return null;
248
-        }
249
-        return $message_type;
250
-    }
251
-
252
-
253
-    /**
254
-     * @return array
255
-     * @throws EE_Error
256
-     */
257
-    public function contexts_config()
258
-    {
259
-        return $this->message_type_obj()->get_contexts();
260
-    }
261
-
262
-
263
-    /**
264
-     * This returns the context_label for contexts as set in the message type object
265
-     * Note this is an array with singular and plural keys
266
-     *
267
-     * @access public
268
-     * @return array labels for "context"
269
-     * @throws EE_Error
270
-     */
271
-    public function context_label()
272
-    {
273
-        $obj = $this->message_type_obj();
274
-        return $obj->get_context_label();
275
-    }
276
-
277
-
278
-    /**
279
-     * This returns an array of EE_Message_Template objects indexed by context and field.
280
-     *
281
-     * @return array ()
282
-     * @throws EE_Error
283
-     */
284
-    public function context_templates()
285
-    {
286
-        $mtps_arr = array();
287
-        $mtps = $this->get_many_related('Message_Template');
288
-        if (empty($mtps)) {
289
-            return array();
290
-        }
291
-        // note contexts could have CHECKBOX fields per context. So we return the objects indexed by context AND field.
292
-        foreach ($mtps as $mtp) {
293
-            $mtps_arr[ $mtp->get('MTP_context') ][ $mtp->get('MTP_template_field') ] = $mtp;
294
-        }
295
-        return $mtps_arr;
296
-    }
297
-
298
-
299
-    /**
300
-     * this returns if the template group this template belongs to is global
301
-     *
302
-     * @return bool true if it is, false if it isn't
303
-     * @throws EE_Error
304
-     */
305
-    public function is_global()
306
-    {
307
-        return $this->get('MTP_is_global');
308
-    }
309
-
310
-
311
-    /**
312
-     * this returns if the template group this template belongs to is active (i.e. turned "on" or not)
313
-     *
314
-     * @return bool true if it is, false if it isn't
315
-     * @throws EE_Error
316
-     */
317
-    public function is_active()
318
-    {
319
-        return $this->get('MTP_is_active');
320
-    }
321
-
322
-
323
-    /**
324
-     * This will return an array of shortcodes => labels from the messenger and message_type objects associated with
325
-     * this template.
326
-     *
327
-     * @since 4.3.0
328
-     * @uses  EEH_MSG_Template::get_shortcodes()
329
-     * @param string $context what context we're going to return shortcodes for
330
-     * @param array  $fields  what fields we're returning valid shortcodes for.  If empty then we assume all fields are
331
-     *                        to be returned.
332
-     * @param bool   $merged  If TRUE then we don't return shortcodes indexed by field but instead an array of the
333
-     *                        unique shortcodes for all the given (or all) fields.
334
-     * @return mixed (array|bool) an array of shortcodes in the format array( '[shortcode] => 'label') OR FALSE if no
335
-     *                        shortcodes found.
336
-     * @throws EE_Error
337
-     */
338
-    public function get_shortcodes($context, $fields = array(), $merged = false)
339
-    {
340
-        $messenger = $this->messenger();
341
-        $message_type = $this->message_type();
342
-        return EEH_MSG_Template::get_shortcodes($message_type, $messenger, $fields, $context, $merged);
343
-    }
344
-
345
-
346
-    /**
347
-     * This just gets the template pack name assigned to this message template group.  If it's not set, then we just
348
-     * use the default template pack.
349
-     *
350
-     * @since 4.5.0
351
-     * @return string
352
-     * @throws EE_Error
353
-     */
354
-    public function get_template_pack_name()
355
-    {
356
-        return $this->get_extra_meta('MTP_template_pack', true, 'default');
357
-    }
358
-
359
-
360
-    /**
361
-     * This returns the specific template pack object referenced by the template pack name attached to this message
362
-     * template group.  If no template pack is assigned then the default template pack is retrieved.
363
-     *
364
-     * @since 4.5.0
365
-     * @return EE_Messages_Template_Pack
366
-     * @throws EE_Error
367
-     * @throws InvalidArgumentException
368
-     * @throws ReflectionException
369
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
370
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
371
-     */
372
-    public function get_template_pack()
373
-    {
374
-        $pack_name = $this->get_template_pack_name();
375
-        EE_Registry::instance()->load_helper('MSG_Template');
376
-        return EEH_MSG_Template::get_template_pack($pack_name);
377
-    }
378
-
379
-
380
-    /**
381
-     * This retrieves the template variation assigned to this message template group.  If it's not set, then we just
382
-     * use the default template variation.
383
-     *
384
-     * @since 4.5.0
385
-     * @return string
386
-     * @throws EE_Error
387
-     */
388
-    public function get_template_pack_variation()
389
-    {
390
-        return $this->get_extra_meta('MTP_variation', true, 'default');
391
-    }
392
-
393
-
394
-    /**
395
-     * This just sets the template pack name attached to this message template group.
396
-     *
397
-     * @since 4.5.0
398
-     * @param string $template_pack_name What message template pack is assigned.
399
-     * @return int
400
-     * @throws EE_Error
401
-     */
402
-    public function set_template_pack_name($template_pack_name)
403
-    {
404
-        return $this->update_extra_meta('MTP_template_pack', $template_pack_name);
405
-    }
406
-
407
-
408
-    /**
409
-     * This just sets the template pack variation attached to this message template group.
410
-     *
411
-     * @since 4.5.0
412
-     * @param string $variation What variation is being set on the message template group.
413
-     * @return int
414
-     * @throws EE_Error
415
-     */
416
-    public function set_template_pack_variation($variation)
417
-    {
418
-        return $this->update_extra_meta('MTP_variation', $variation);
419
-    }
420
-
421
-
422
-    /**
423
-     * Deactivates the given context.
424
-     *
425
-     * @param $context
426
-     * @return bool|int
427
-     * @throws EE_Error
428
-     * @throws InvalidIdentifierException
429
-     */
430
-    public function deactivate_context($context)
431
-    {
432
-        $this->validate_context($context);
433
-        return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, false);
434
-    }
435
-
436
-
437
-    /**
438
-     * Activates the given context.
439
-     *
440
-     * @param $context
441
-     * @return bool|int
442
-     * @throws EE_Error
443
-     * @throws InvalidIdentifierException
444
-     */
445
-    public function activate_context($context)
446
-    {
447
-        $this->validate_context($context);
448
-        return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true);
449
-    }
450
-
451
-
452
-    /**
453
-     * Returns whether the context is active or not.
454
-     * Note, this will default to true if the extra meta record doesn't exist.
455
-     * Also, this does NOT account for whether the "To" field is empty or not. Some messengers may allow the "To" field
456
-     * to be empty (@see EE_Messenger::allow_empty_to_field()) so an empty "To" field is not always an indicator of
457
-     * whether a context is "active" or not.
458
-     *
459
-     * @param $context
460
-     * @return bool
461
-     * @throws EE_Error
462
-     * @throws InvalidIdentifierException
463
-     */
464
-    public function is_context_active($context)
465
-    {
466
-        $this->validate_context($context);
467
-        return filter_var(
468
-            $this->get_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true, true),
469
-            FILTER_VALIDATE_BOOLEAN
470
-        );
471
-    }
472
-
473
-
474
-    /**
475
-     * Validates the incoming context to verify it matches a registered context for the related message type.
476
-     *
477
-     * @param string $context
478
-     * @throws EE_Error
479
-     * @throws InvalidIdentifierException
480
-     */
481
-    public function validate_context($context)
482
-    {
483
-        $contexts = $this->contexts_config();
484
-        if (! isset($contexts[ $context ])) {
485
-            throw new InvalidIdentifierException(
486
-                '',
487
-                '',
488
-                sprintf(
489
-                    esc_html__(
490
-                        'An invalid string identifying a context was provided.  "%1$s" was received, and one of "%2$s" was expected.',
491
-                        'event_espresso'
492
-                    ),
493
-                    $context,
494
-                    implode(',', array_keys($contexts))
495
-                )
496
-            );
497
-        }
498
-    }
16
+	/**
17
+	 * Extra Meta key prefix for whether a given context for this message tmeplate group is active or not.
18
+	 */
19
+	const ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX = 'active_context_';
20
+
21
+	/**
22
+	 * @param array  $props_n_values
23
+	 * @param string $timezone
24
+	 * @return EE_Message_Template_Group|mixed
25
+	 * @throws EE_Error
26
+	 */
27
+	public static function new_instance($props_n_values = array(), $timezone = '')
28
+	{
29
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone);
30
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone);
31
+	}
32
+
33
+
34
+	/**
35
+	 * @param array  $props_n_values
36
+	 * @param string $timezone
37
+	 * @return EE_Message_Template_Group
38
+	 */
39
+	public static function new_instance_from_db($props_n_values = array(), $timezone = '')
40
+	{
41
+		return new self($props_n_values, true, $timezone);
42
+	}
43
+
44
+
45
+	/**
46
+	 * @param bool $message_type
47
+	 * @throws EE_Error
48
+	 */
49
+	public function set_message_type($message_type = false)
50
+	{
51
+		if (! $message_type) {
52
+			throw new EE_Error(esc_html__('Missing required value for the message_type parameter', 'event_espresso'));
53
+		}
54
+		$this->set('MTP_message_type', $message_type);
55
+	}
56
+
57
+
58
+	/**
59
+	 * @param bool $messenger
60
+	 * @throws EE_Error
61
+	 */
62
+	public function set_messenger($messenger = false)
63
+	{
64
+		if (! $messenger) {
65
+			throw new EE_Error(esc_html__('Missing required value for the messenger parameter', 'event_espresso'));
66
+		}
67
+		$this->set('MTP_messenger', $messenger);
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param bool $GRP_ID
73
+	 * @throws EE_Error
74
+	 */
75
+	public function set_group_template_id($GRP_ID = false)
76
+	{
77
+		if (! $GRP_ID) {
78
+			throw new EE_Error(
79
+				esc_html__(
80
+					'Missing required value for the message template group id',
81
+					'event_espresso'
82
+				)
83
+			);
84
+		}
85
+		$this->set('GRP_ID', $GRP_ID);
86
+	}
87
+
88
+
89
+	/**
90
+	 * get Group ID
91
+	 *
92
+	 * @access public
93
+	 * @return int
94
+	 * @throws EE_Error
95
+	 */
96
+	public function GRP_ID()
97
+	{
98
+		return $this->get('GRP_ID');
99
+	}
100
+
101
+
102
+	/**
103
+	 * get User ID
104
+	 *
105
+	 * @access public
106
+	 * @return int
107
+	 * @throws EE_Error
108
+	 */
109
+	public function user()
110
+	{
111
+		$user_id = $this->get('MTP_user_id');
112
+		return empty($user_id) ? get_current_user_id() : $user_id;
113
+	}
114
+
115
+
116
+	/**
117
+	 * Wrapper for the user function() (preserve backward compat)
118
+	 *
119
+	 * @since  4.5.0
120
+	 * @return int
121
+	 * @throws EE_Error
122
+	 */
123
+	public function wp_user()
124
+	{
125
+		return $this->user();
126
+	}
127
+
128
+
129
+	/**
130
+	 * This simply returns a count of all related events to this message template group
131
+	 *
132
+	 * @return int
133
+	 */
134
+	public function count_events()
135
+	{
136
+		return $this->count_related('Event');
137
+	}
138
+
139
+
140
+	/**
141
+	 * returns the name saved in the db for this template
142
+	 *
143
+	 * @return string
144
+	 * @throws EE_Error
145
+	 */
146
+	public function name()
147
+	{
148
+		return $this->get('MTP_name');
149
+	}
150
+
151
+
152
+	/**
153
+	 * Returns the description saved in the db for this template group
154
+	 *
155
+	 * @return string
156
+	 * @throws EE_Error
157
+	 */
158
+	public function description()
159
+	{
160
+		return $this->get('MTP_description');
161
+	}
162
+
163
+
164
+	/**
165
+	 * returns all related EE_Message_Template objects
166
+	 *
167
+	 * @param  array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
168
+	 * @return EE_Message_Template[]
169
+	 * @throws EE_Error
170
+	 */
171
+	public function message_templates($query_params = array())
172
+	{
173
+		return $this->get_many_related('Message_Template', $query_params);
174
+	}
175
+
176
+
177
+	/**
178
+	 * get Message Messenger
179
+	 *
180
+	 * @access public
181
+	 * @return string
182
+	 * @throws EE_Error
183
+	 */
184
+	public function messenger()
185
+	{
186
+		return $this->get('MTP_messenger');
187
+	}
188
+
189
+
190
+	/**
191
+	 * get Message Messenger OBJECT
192
+	 * If an attempt to get the corresponding messenger object fails, then we set this message
193
+	 * template group to inactive, and save to db.  Then return null so client code can handle
194
+	 * appropriately.
195
+	 *
196
+	 * @return EE_messenger
197
+	 * @throws EE_Error
198
+	 */
199
+	public function messenger_obj()
200
+	{
201
+		$messenger = $this->messenger();
202
+		try {
203
+			$messenger = EEH_MSG_Template::messenger_obj($messenger);
204
+		} catch (EE_Error $e) {
205
+			// if an exception was thrown then let's deactivate this message template group because it means there is no
206
+			// class for this messenger in this group.
207
+			$this->set('MTP_is_active', false);
208
+			$this->save();
209
+			return null;
210
+		}
211
+		return $messenger;
212
+	}
213
+
214
+
215
+	/**
216
+	 * get Message Type
217
+	 *
218
+	 * @access public
219
+	 * @return string
220
+	 * @throws EE_Error
221
+	 */
222
+	public function message_type()
223
+	{
224
+		return $this->get('MTP_message_type');
225
+	}
226
+
227
+
228
+	/**
229
+	 * get Message type OBJECT
230
+	 * If an attempt to get the corresponding message type object fails, then we set this message
231
+	 * template group to inactive, and save to db.  Then return null so client code can handle
232
+	 * appropriately.
233
+	 *
234
+	 * @throws EE_Error
235
+	 * @return EE_message_type|false if exception thrown.
236
+	 */
237
+	public function message_type_obj()
238
+	{
239
+		$message_type = $this->message_type();
240
+		try {
241
+			$message_type = EEH_MSG_Template::message_type_obj($message_type);
242
+		} catch (EE_Error $e) {
243
+			// if an exception was thrown then let's deactivate this message template group because it means there is no
244
+			// class for the message type in this group.
245
+			$this->set('MTP_is_active', false);
246
+			$this->save();
247
+			return null;
248
+		}
249
+		return $message_type;
250
+	}
251
+
252
+
253
+	/**
254
+	 * @return array
255
+	 * @throws EE_Error
256
+	 */
257
+	public function contexts_config()
258
+	{
259
+		return $this->message_type_obj()->get_contexts();
260
+	}
261
+
262
+
263
+	/**
264
+	 * This returns the context_label for contexts as set in the message type object
265
+	 * Note this is an array with singular and plural keys
266
+	 *
267
+	 * @access public
268
+	 * @return array labels for "context"
269
+	 * @throws EE_Error
270
+	 */
271
+	public function context_label()
272
+	{
273
+		$obj = $this->message_type_obj();
274
+		return $obj->get_context_label();
275
+	}
276
+
277
+
278
+	/**
279
+	 * This returns an array of EE_Message_Template objects indexed by context and field.
280
+	 *
281
+	 * @return array ()
282
+	 * @throws EE_Error
283
+	 */
284
+	public function context_templates()
285
+	{
286
+		$mtps_arr = array();
287
+		$mtps = $this->get_many_related('Message_Template');
288
+		if (empty($mtps)) {
289
+			return array();
290
+		}
291
+		// note contexts could have CHECKBOX fields per context. So we return the objects indexed by context AND field.
292
+		foreach ($mtps as $mtp) {
293
+			$mtps_arr[ $mtp->get('MTP_context') ][ $mtp->get('MTP_template_field') ] = $mtp;
294
+		}
295
+		return $mtps_arr;
296
+	}
297
+
298
+
299
+	/**
300
+	 * this returns if the template group this template belongs to is global
301
+	 *
302
+	 * @return bool true if it is, false if it isn't
303
+	 * @throws EE_Error
304
+	 */
305
+	public function is_global()
306
+	{
307
+		return $this->get('MTP_is_global');
308
+	}
309
+
310
+
311
+	/**
312
+	 * this returns if the template group this template belongs to is active (i.e. turned "on" or not)
313
+	 *
314
+	 * @return bool true if it is, false if it isn't
315
+	 * @throws EE_Error
316
+	 */
317
+	public function is_active()
318
+	{
319
+		return $this->get('MTP_is_active');
320
+	}
321
+
322
+
323
+	/**
324
+	 * This will return an array of shortcodes => labels from the messenger and message_type objects associated with
325
+	 * this template.
326
+	 *
327
+	 * @since 4.3.0
328
+	 * @uses  EEH_MSG_Template::get_shortcodes()
329
+	 * @param string $context what context we're going to return shortcodes for
330
+	 * @param array  $fields  what fields we're returning valid shortcodes for.  If empty then we assume all fields are
331
+	 *                        to be returned.
332
+	 * @param bool   $merged  If TRUE then we don't return shortcodes indexed by field but instead an array of the
333
+	 *                        unique shortcodes for all the given (or all) fields.
334
+	 * @return mixed (array|bool) an array of shortcodes in the format array( '[shortcode] => 'label') OR FALSE if no
335
+	 *                        shortcodes found.
336
+	 * @throws EE_Error
337
+	 */
338
+	public function get_shortcodes($context, $fields = array(), $merged = false)
339
+	{
340
+		$messenger = $this->messenger();
341
+		$message_type = $this->message_type();
342
+		return EEH_MSG_Template::get_shortcodes($message_type, $messenger, $fields, $context, $merged);
343
+	}
344
+
345
+
346
+	/**
347
+	 * This just gets the template pack name assigned to this message template group.  If it's not set, then we just
348
+	 * use the default template pack.
349
+	 *
350
+	 * @since 4.5.0
351
+	 * @return string
352
+	 * @throws EE_Error
353
+	 */
354
+	public function get_template_pack_name()
355
+	{
356
+		return $this->get_extra_meta('MTP_template_pack', true, 'default');
357
+	}
358
+
359
+
360
+	/**
361
+	 * This returns the specific template pack object referenced by the template pack name attached to this message
362
+	 * template group.  If no template pack is assigned then the default template pack is retrieved.
363
+	 *
364
+	 * @since 4.5.0
365
+	 * @return EE_Messages_Template_Pack
366
+	 * @throws EE_Error
367
+	 * @throws InvalidArgumentException
368
+	 * @throws ReflectionException
369
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
370
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
371
+	 */
372
+	public function get_template_pack()
373
+	{
374
+		$pack_name = $this->get_template_pack_name();
375
+		EE_Registry::instance()->load_helper('MSG_Template');
376
+		return EEH_MSG_Template::get_template_pack($pack_name);
377
+	}
378
+
379
+
380
+	/**
381
+	 * This retrieves the template variation assigned to this message template group.  If it's not set, then we just
382
+	 * use the default template variation.
383
+	 *
384
+	 * @since 4.5.0
385
+	 * @return string
386
+	 * @throws EE_Error
387
+	 */
388
+	public function get_template_pack_variation()
389
+	{
390
+		return $this->get_extra_meta('MTP_variation', true, 'default');
391
+	}
392
+
393
+
394
+	/**
395
+	 * This just sets the template pack name attached to this message template group.
396
+	 *
397
+	 * @since 4.5.0
398
+	 * @param string $template_pack_name What message template pack is assigned.
399
+	 * @return int
400
+	 * @throws EE_Error
401
+	 */
402
+	public function set_template_pack_name($template_pack_name)
403
+	{
404
+		return $this->update_extra_meta('MTP_template_pack', $template_pack_name);
405
+	}
406
+
407
+
408
+	/**
409
+	 * This just sets the template pack variation attached to this message template group.
410
+	 *
411
+	 * @since 4.5.0
412
+	 * @param string $variation What variation is being set on the message template group.
413
+	 * @return int
414
+	 * @throws EE_Error
415
+	 */
416
+	public function set_template_pack_variation($variation)
417
+	{
418
+		return $this->update_extra_meta('MTP_variation', $variation);
419
+	}
420
+
421
+
422
+	/**
423
+	 * Deactivates the given context.
424
+	 *
425
+	 * @param $context
426
+	 * @return bool|int
427
+	 * @throws EE_Error
428
+	 * @throws InvalidIdentifierException
429
+	 */
430
+	public function deactivate_context($context)
431
+	{
432
+		$this->validate_context($context);
433
+		return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, false);
434
+	}
435
+
436
+
437
+	/**
438
+	 * Activates the given context.
439
+	 *
440
+	 * @param $context
441
+	 * @return bool|int
442
+	 * @throws EE_Error
443
+	 * @throws InvalidIdentifierException
444
+	 */
445
+	public function activate_context($context)
446
+	{
447
+		$this->validate_context($context);
448
+		return $this->update_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true);
449
+	}
450
+
451
+
452
+	/**
453
+	 * Returns whether the context is active or not.
454
+	 * Note, this will default to true if the extra meta record doesn't exist.
455
+	 * Also, this does NOT account for whether the "To" field is empty or not. Some messengers may allow the "To" field
456
+	 * to be empty (@see EE_Messenger::allow_empty_to_field()) so an empty "To" field is not always an indicator of
457
+	 * whether a context is "active" or not.
458
+	 *
459
+	 * @param $context
460
+	 * @return bool
461
+	 * @throws EE_Error
462
+	 * @throws InvalidIdentifierException
463
+	 */
464
+	public function is_context_active($context)
465
+	{
466
+		$this->validate_context($context);
467
+		return filter_var(
468
+			$this->get_extra_meta(self::ACTIVE_CONTEXT_RECORD_META_KEY_PREFIX . $context, true, true),
469
+			FILTER_VALIDATE_BOOLEAN
470
+		);
471
+	}
472
+
473
+
474
+	/**
475
+	 * Validates the incoming context to verify it matches a registered context for the related message type.
476
+	 *
477
+	 * @param string $context
478
+	 * @throws EE_Error
479
+	 * @throws InvalidIdentifierException
480
+	 */
481
+	public function validate_context($context)
482
+	{
483
+		$contexts = $this->contexts_config();
484
+		if (! isset($contexts[ $context ])) {
485
+			throw new InvalidIdentifierException(
486
+				'',
487
+				'',
488
+				sprintf(
489
+					esc_html__(
490
+						'An invalid string identifying a context was provided.  "%1$s" was received, and one of "%2$s" was expected.',
491
+						'event_espresso'
492
+					),
493
+					$context,
494
+					implode(',', array_keys($contexts))
495
+				)
496
+			);
497
+		}
498
+	}
499 499
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Transaction.class.php 1 patch
Indentation   +1390 added lines, -1390 removed lines patch added patch discarded remove patch
@@ -13,1394 +13,1394 @@
 block discarded – undo
13 13
 class EE_Transaction extends EE_Base_Class implements EEI_Transaction
14 14
 {
15 15
 
16
-    /**
17
-     * The length of time in seconds that a lock is applied before being considered expired.
18
-     * It is not long because a transaction should only be locked for the duration of the request that locked it
19
-     */
20
-    const LOCK_EXPIRATION = 2;
21
-
22
-    /**
23
-     * txn status upon initial construction.
24
-     *
25
-     * @var string
26
-     */
27
-    protected $_old_txn_status;
28
-
29
-
30
-    /**
31
-     * @param array  $props_n_values          incoming values
32
-     * @param string $timezone                incoming timezone
33
-     *                                        (if not set the timezone set for the website will be used.)
34
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
35
-     *                                        date_format and the second value is the time format
36
-     * @return EE_Transaction
37
-     * @throws EE_Error
38
-     */
39
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
40
-    {
41
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
42
-        $txn = $has_object
43
-            ? $has_object
44
-            : new self($props_n_values, false, $timezone, $date_formats);
45
-        if (! $has_object) {
46
-            $txn->set_old_txn_status($txn->status_ID());
47
-        }
48
-        return $txn;
49
-    }
50
-
51
-
52
-    /**
53
-     * @param array  $props_n_values  incoming values from the database
54
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
55
-     *                                the website will be used.
56
-     * @return EE_Transaction
57
-     * @throws EE_Error
58
-     */
59
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
60
-    {
61
-        $txn = new self($props_n_values, true, $timezone);
62
-        $txn->set_old_txn_status($txn->status_ID());
63
-        return $txn;
64
-    }
65
-
66
-
67
-    /**
68
-     * Sets a meta field indicating that this TXN is locked and should not be updated in the db.
69
-     * If a lock has already been set, then we will attempt to remove it in case it has expired.
70
-     * If that also fails, then an exception is thrown.
71
-     *
72
-     * @throws EE_Error
73
-     */
74
-    public function lock()
75
-    {
76
-        // attempt to set lock, but if that fails...
77
-        if (! $this->add_extra_meta('lock', time(), true)) {
78
-            // then attempt to remove the lock in case it is expired
79
-            if ($this->_remove_expired_lock()) {
80
-                // if removal was successful, then try setting lock again
81
-                $this->lock();
82
-            } else {
83
-                // but if the lock can not be removed, then throw an exception
84
-                throw new EE_Error(
85
-                    sprintf(
86
-                        __(
87
-                            'Could not lock Transaction %1$d because it is already locked, meaning another part of the system is currently editing it. It should already be unlocked by the time you read this, so please refresh the page and try again.',
88
-                            'event_espresso'
89
-                        ),
90
-                        $this->ID()
91
-                    )
92
-                );
93
-            }
94
-        }
95
-    }
96
-
97
-
98
-    /**
99
-     * removes transaction lock applied in EE_Transaction::lock()
100
-     *
101
-     * @return int
102
-     * @throws EE_Error
103
-     */
104
-    public function unlock()
105
-    {
106
-        return $this->delete_extra_meta('lock');
107
-    }
108
-
109
-
110
-    /**
111
-     * Decides whether or not now is the right time to update the transaction.
112
-     * This is useful because we don't always know if it is safe to update the transaction
113
-     * and its related data. why?
114
-     * because it's possible that the transaction is being used in another
115
-     * request and could overwrite anything we save.
116
-     * So we want to only update the txn once we know that won't happen.
117
-     * We also check that the lock isn't expired, and remove it if it is
118
-     *
119
-     * @return boolean
120
-     * @throws EE_Error
121
-     */
122
-    public function is_locked()
123
-    {
124
-        // if TXN is not locked, then return false immediately
125
-        if (! $this->_get_lock()) {
126
-            return false;
127
-        }
128
-        // if not, then let's try and remove the lock in case it's expired...
129
-        // _remove_expired_lock() returns 0 when lock is valid (ie: removed = false)
130
-        // and a positive number if the lock was removed (ie: number of locks deleted),
131
-        // so we need to return the opposite
132
-        return ! $this->_remove_expired_lock() ? true : false;
133
-    }
134
-
135
-
136
-    /**
137
-     * Gets the meta field indicating that this TXN is locked
138
-     *
139
-     * @return int
140
-     * @throws EE_Error
141
-     */
142
-    protected function _get_lock()
143
-    {
144
-        return (int) $this->get_extra_meta('lock', true, 0);
145
-    }
146
-
147
-
148
-    /**
149
-     * If the lock on this transaction is expired, then we want to remove it so that the transaction can be updated
150
-     *
151
-     * @return int
152
-     * @throws EE_Error
153
-     */
154
-    protected function _remove_expired_lock()
155
-    {
156
-        $locked = $this->_get_lock();
157
-        if ($locked && time() - EE_Transaction::LOCK_EXPIRATION > $locked) {
158
-            return $this->unlock();
159
-        }
160
-        return 0;
161
-    }
162
-
163
-
164
-    /**
165
-     * Set transaction total
166
-     *
167
-     * @param float $total total value of transaction
168
-     * @throws EE_Error
169
-     */
170
-    public function set_total($total = 0.00)
171
-    {
172
-        $this->set('TXN_total', (float) $total);
173
-    }
174
-
175
-
176
-    /**
177
-     * Set Total Amount Paid to Date
178
-     *
179
-     * @param float $total_paid total amount paid to date (sum of all payments)
180
-     * @throws EE_Error
181
-     */
182
-    public function set_paid($total_paid = 0.00)
183
-    {
184
-        $this->set('TXN_paid', (float) $total_paid);
185
-    }
186
-
187
-
188
-    /**
189
-     * Set transaction status
190
-     *
191
-     * @param string $status        whether the transaction is open, declined, accepted,
192
-     *                              or any number of custom values that can be set
193
-     * @throws EE_Error
194
-     */
195
-    public function set_status($status = '')
196
-    {
197
-        $this->set('STS_ID', $status);
198
-    }
199
-
200
-
201
-    /**
202
-     * Set hash salt
203
-     *
204
-     * @param string $hash_salt required for some payment gateways
205
-     * @throws EE_Error
206
-     */
207
-    public function set_hash_salt($hash_salt = '')
208
-    {
209
-        $this->set('TXN_hash_salt', $hash_salt);
210
-    }
211
-
212
-
213
-    /**
214
-     * Sets TXN_reg_steps array
215
-     *
216
-     * @param array $txn_reg_steps
217
-     * @throws EE_Error
218
-     */
219
-    public function set_reg_steps(array $txn_reg_steps)
220
-    {
221
-        $this->set('TXN_reg_steps', $txn_reg_steps);
222
-    }
223
-
224
-
225
-    /**
226
-     * Gets TXN_reg_steps
227
-     *
228
-     * @return array
229
-     * @throws EE_Error
230
-     */
231
-    public function reg_steps()
232
-    {
233
-        $TXN_reg_steps = $this->get('TXN_reg_steps');
234
-        return is_array($TXN_reg_steps) ? (array) $TXN_reg_steps : array();
235
-    }
236
-
237
-
238
-    /**
239
-     * @return string of transaction's total cost, with currency symbol and decimal
240
-     * @throws EE_Error
241
-     */
242
-    public function pretty_total()
243
-    {
244
-        return $this->get_pretty('TXN_total');
245
-    }
246
-
247
-
248
-    /**
249
-     * Gets the amount paid in a pretty string (formatted and with currency symbol)
250
-     *
251
-     * @return string
252
-     * @throws EE_Error
253
-     */
254
-    public function pretty_paid()
255
-    {
256
-        return $this->get_pretty('TXN_paid');
257
-    }
258
-
259
-
260
-    /**
261
-     * calculate the amount remaining for this transaction and return;
262
-     *
263
-     * @return float amount remaining
264
-     * @throws EE_Error
265
-     */
266
-    public function remaining()
267
-    {
268
-        return $this->total() - $this->paid();
269
-    }
270
-
271
-
272
-    /**
273
-     * get Transaction Total
274
-     *
275
-     * @return float
276
-     * @throws EE_Error
277
-     */
278
-    public function total()
279
-    {
280
-        return (float) $this->get('TXN_total');
281
-    }
282
-
283
-
284
-    /**
285
-     * get Total Amount Paid to Date
286
-     *
287
-     * @return float
288
-     * @throws EE_Error
289
-     */
290
-    public function paid()
291
-    {
292
-        return (float) $this->get('TXN_paid');
293
-    }
294
-
295
-
296
-    /**
297
-     * @throws EE_Error
298
-     */
299
-    public function get_cart_session()
300
-    {
301
-        $session_data = (array) $this->get('TXN_session_data');
302
-        return isset($session_data['cart']) && $session_data['cart'] instanceof EE_Cart
303
-            ? $session_data['cart']
304
-            : null;
305
-    }
306
-
307
-
308
-    /**
309
-     * get Transaction session data
310
-     *
311
-     * @throws EE_Error
312
-     */
313
-    public function session_data()
314
-    {
315
-        $session_data = $this->get('TXN_session_data');
316
-        if (empty($session_data)) {
317
-            $session_data = array(
318
-                'id'            => null,
319
-                'user_id'       => null,
320
-                'ip_address'    => null,
321
-                'user_agent'    => null,
322
-                'init_access'   => null,
323
-                'last_access'   => null,
324
-                'pages_visited' => array(),
325
-            );
326
-        }
327
-        return $session_data;
328
-    }
329
-
330
-
331
-    /**
332
-     * Set session data within the TXN object
333
-     *
334
-     * @param EE_Session|array $session_data
335
-     * @throws EE_Error
336
-     */
337
-    public function set_txn_session_data($session_data)
338
-    {
339
-        if ($session_data instanceof EE_Session) {
340
-            $this->set('TXN_session_data', $session_data->get_session_data(null, true));
341
-        } else {
342
-            $this->set('TXN_session_data', $session_data);
343
-        }
344
-    }
345
-
346
-
347
-    /**
348
-     * get Transaction hash salt
349
-     *
350
-     * @throws EE_Error
351
-     */
352
-    public function hash_salt_()
353
-    {
354
-        return $this->get('TXN_hash_salt');
355
-    }
356
-
357
-
358
-    /**
359
-     * Returns the transaction datetime as either:
360
-     *            - unix timestamp format ($format = false, $gmt = true)
361
-     *            - formatted date string including the UTC (timezone) offset ($format = true ($gmt
362
-     *              has no affect with this option)), this also may include a timezone abbreviation if the
363
-     *              set timezone in this class differs from what the timezone is on the blog.
364
-     *            - formatted date string including the UTC (timezone) offset (default).
365
-     *
366
-     * @param boolean $format   - whether to return a unix timestamp (default) or formatted date string
367
-     * @param boolean $gmt      - whether to return a unix timestamp with UTC offset applied (default)
368
-     *                          or no UTC offset applied
369
-     * @return string | int
370
-     * @throws EE_Error
371
-     */
372
-    public function datetime($format = false, $gmt = false)
373
-    {
374
-        if ($format) {
375
-            return $this->get_pretty('TXN_timestamp');
376
-        }
377
-        if ($gmt) {
378
-            return $this->get_raw('TXN_timestamp');
379
-        }
380
-        return $this->get('TXN_timestamp');
381
-    }
382
-
383
-
384
-    /**
385
-     * Gets registrations on this transaction
386
-     *
387
-     * @param array   $query_params array of query parameters
388
-     * @param boolean $get_cached   TRUE to retrieve cached registrations or FALSE to pull from the db
389
-     * @return EE_Base_Class[]|EE_Registration[]
390
-     * @throws EE_Error
391
-     */
392
-    public function registrations($query_params = array(), $get_cached = false)
393
-    {
394
-        $query_params = (empty($query_params) || ! is_array($query_params))
395
-            ? array(
396
-                'order_by' => array(
397
-                    'Event.EVT_name'     => 'ASC',
398
-                    'Attendee.ATT_lname' => 'ASC',
399
-                    'Attendee.ATT_fname' => 'ASC',
400
-                ),
401
-            )
402
-            : $query_params;
403
-        $query_params = $get_cached ? array() : $query_params;
404
-        return $this->get_many_related('Registration', $query_params);
405
-    }
406
-
407
-
408
-    /**
409
-     * Gets all the attendees for this transaction (handy for use with EE_Attendee's get_registrations_for_event
410
-     * function for getting attendees and how many registrations they each have for an event)
411
-     *
412
-     * @return mixed EE_Attendee[] by default, int if $output is set to 'COUNT'
413
-     * @throws EE_Error
414
-     */
415
-    public function attendees()
416
-    {
417
-        return $this->get_many_related('Attendee', array(array('Registration.Transaction.TXN_ID' => $this->ID())));
418
-    }
419
-
420
-
421
-    /**
422
-     * Gets payments for this transaction. Unlike other such functions, order by 'DESC' by default
423
-     *
424
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
425
-     * @return EE_Base_Class[]|EE_Payment[]
426
-     * @throws EE_Error
427
-     */
428
-    public function payments($query_params = array())
429
-    {
430
-        return $this->get_many_related('Payment', $query_params);
431
-    }
432
-
433
-
434
-    /**
435
-     * gets only approved payments for this transaction
436
-     *
437
-     * @return EE_Base_Class[]|EE_Payment[]
438
-     * @throws EE_Error
439
-     * @throws InvalidArgumentException
440
-     * @throws ReflectionException
441
-     * @throws InvalidDataTypeException
442
-     * @throws InvalidInterfaceException
443
-     */
444
-    public function approved_payments()
445
-    {
446
-        EE_Registry::instance()->load_model('Payment');
447
-        return $this->get_many_related(
448
-            'Payment',
449
-            array(
450
-                array('STS_ID' => EEM_Payment::status_id_approved),
451
-                'order_by' => array('PAY_timestamp' => 'DESC'),
452
-            )
453
-        );
454
-    }
455
-
456
-
457
-    /**
458
-     * Gets all payments which have not been approved
459
-     *
460
-     * @return EE_Base_Class[]|EEI_Payment[]
461
-     * @throws EE_Error if a model is misconfigured somehow
462
-     */
463
-    public function pending_payments()
464
-    {
465
-        return $this->get_many_related(
466
-            'Payment',
467
-            array(
468
-                array(
469
-                    'STS_ID' => EEM_Payment::status_id_pending,
470
-                ),
471
-                'order_by' => array(
472
-                    'PAY_timestamp' => 'DESC',
473
-                ),
474
-            )
475
-        );
476
-    }
477
-
478
-
479
-    /**
480
-     * echoes $this->pretty_status()
481
-     *
482
-     * @param bool $show_icons
483
-     * @throws EE_Error
484
-     * @throws InvalidArgumentException
485
-     * @throws InvalidDataTypeException
486
-     * @throws InvalidInterfaceException
487
-     */
488
-    public function e_pretty_status($show_icons = false)
489
-    {
490
-        echo $this->pretty_status($show_icons);
491
-    }
492
-
493
-
494
-    /**
495
-     * returns a pretty version of the status, good for displaying to users
496
-     *
497
-     * @param bool $show_icons
498
-     * @return string
499
-     * @throws EE_Error
500
-     * @throws InvalidArgumentException
501
-     * @throws InvalidDataTypeException
502
-     * @throws InvalidInterfaceException
503
-     */
504
-    public function pretty_status($show_icons = false)
505
-    {
506
-        $status = EEM_Status::instance()->localized_status(
507
-            array($this->status_ID() => __('unknown', 'event_espresso')),
508
-            false,
509
-            'sentence'
510
-        );
511
-        $icon = '';
512
-        switch ($this->status_ID()) {
513
-            case EEM_Transaction::complete_status_code:
514
-                $icon = $show_icons ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>' : '';
515
-                break;
516
-            case EEM_Transaction::incomplete_status_code:
517
-                $icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 lt-blue-text"></span>'
518
-                    : '';
519
-                break;
520
-            case EEM_Transaction::abandoned_status_code:
521
-                $icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 red-text"></span>' : '';
522
-                break;
523
-            case EEM_Transaction::failed_status_code:
524
-                $icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>' : '';
525
-                break;
526
-            case EEM_Transaction::overpaid_status_code:
527
-                $icon = $show_icons ? '<span class="dashicons dashicons-plus ee-icon-size-16 orange-text"></span>' : '';
528
-                break;
529
-        }
530
-        return $icon . $status[ $this->status_ID() ];
531
-    }
532
-
533
-
534
-    /**
535
-     * get Transaction Status
536
-     *
537
-     * @throws EE_Error
538
-     */
539
-    public function status_ID()
540
-    {
541
-        return $this->get('STS_ID');
542
-    }
543
-
544
-
545
-    /**
546
-     * Returns TRUE or FALSE for whether or not this transaction cost any money
547
-     *
548
-     * @return boolean
549
-     * @throws EE_Error
550
-     */
551
-    public function is_free()
552
-    {
553
-        return EEH_Money::compare_floats($this->get('TXN_total'), 0, '==');
554
-    }
555
-
556
-
557
-    /**
558
-     * Returns whether this transaction is complete
559
-     * Useful in templates and other logic for deciding if we should ask for another payment...
560
-     *
561
-     * @return boolean
562
-     * @throws EE_Error
563
-     */
564
-    public function is_completed()
565
-    {
566
-        return $this->status_ID() === EEM_Transaction::complete_status_code;
567
-    }
568
-
569
-
570
-    /**
571
-     * Returns whether this transaction is incomplete
572
-     * Useful in templates and other logic for deciding if we should ask for another payment...
573
-     *
574
-     * @return boolean
575
-     * @throws EE_Error
576
-     */
577
-    public function is_incomplete()
578
-    {
579
-        return $this->status_ID() === EEM_Transaction::incomplete_status_code;
580
-    }
581
-
582
-
583
-    /**
584
-     * Returns whether this transaction is overpaid
585
-     * Useful in templates and other logic for deciding if monies need to be refunded
586
-     *
587
-     * @return boolean
588
-     * @throws EE_Error
589
-     */
590
-    public function is_overpaid()
591
-    {
592
-        return $this->status_ID() === EEM_Transaction::overpaid_status_code;
593
-    }
594
-
595
-
596
-    /**
597
-     * Returns whether this transaction was abandoned
598
-     * meaning that the transaction/registration process was somehow interrupted and never completed
599
-     * but that contact information exists for at least one registrant
600
-     *
601
-     * @return boolean
602
-     * @throws EE_Error
603
-     */
604
-    public function is_abandoned()
605
-    {
606
-        return $this->status_ID() === EEM_Transaction::abandoned_status_code;
607
-    }
608
-
609
-
610
-    /**
611
-     * Returns whether this transaction failed
612
-     * meaning that the transaction/registration process was somehow interrupted and never completed
613
-     * and that NO contact information exists for any registrants
614
-     *
615
-     * @return boolean
616
-     * @throws EE_Error
617
-     */
618
-    public function failed()
619
-    {
620
-        return $this->status_ID() === EEM_Transaction::failed_status_code;
621
-    }
622
-
623
-
624
-    /**
625
-     * This returns the url for the invoice of this transaction
626
-     *
627
-     * @param string $type 'html' or 'pdf' (default is pdf)
628
-     * @return string
629
-     * @throws EE_Error
630
-     */
631
-    public function invoice_url($type = 'html')
632
-    {
633
-        $REG = $this->primary_registration();
634
-        if (! $REG instanceof EE_Registration) {
635
-            return '';
636
-        }
637
-        return $REG->invoice_url($type);
638
-    }
639
-
640
-
641
-    /**
642
-     * Gets the primary registration only
643
-     *
644
-     * @return EE_Base_Class|EE_Registration
645
-     * @throws EE_Error
646
-     */
647
-    public function primary_registration()
648
-    {
649
-        $registrations = (array) $this->get_many_related(
650
-            'Registration',
651
-            array(array('REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT))
652
-        );
653
-        foreach ($registrations as $registration) {
654
-            // valid registration that is NOT cancelled or declined ?
655
-            if ($registration instanceof EE_Registration
656
-                && ! in_array($registration->status_ID(), EEM_Registration::closed_reg_statuses(), true)
657
-            ) {
658
-                return $registration;
659
-            }
660
-        }
661
-        // nothing valid found, so just return first thing from array of results
662
-        return reset($registrations);
663
-    }
664
-
665
-
666
-    /**
667
-     * Gets the URL for viewing the receipt
668
-     *
669
-     * @param string $type 'pdf' or 'html' (default is 'html')
670
-     * @return string
671
-     * @throws EE_Error
672
-     */
673
-    public function receipt_url($type = 'html')
674
-    {
675
-        $REG = $this->primary_registration();
676
-        if (! $REG instanceof EE_Registration) {
677
-            return '';
678
-        }
679
-        return $REG->receipt_url($type);
680
-    }
681
-
682
-
683
-    /**
684
-     * Gets the URL of the thank you page with this registration REG_url_link added as
685
-     * a query parameter
686
-     *
687
-     * @return string
688
-     * @throws EE_Error
689
-     */
690
-    public function payment_overview_url()
691
-    {
692
-        $primary_registration = $this->primary_registration();
693
-        return $primary_registration instanceof EE_Registration ? $primary_registration->payment_overview_url() : false;
694
-    }
695
-
696
-
697
-    /**
698
-     * @return string
699
-     * @throws EE_Error
700
-     */
701
-    public function gateway_response_on_transaction()
702
-    {
703
-        $payment = $this->get_first_related('Payment');
704
-        return $payment instanceof EE_Payment ? $payment->gateway_response() : '';
705
-    }
706
-
707
-
708
-    /**
709
-     * Get the status object of this object
710
-     *
711
-     * @return EE_Base_Class|EE_Status
712
-     * @throws EE_Error
713
-     */
714
-    public function status_obj()
715
-    {
716
-        return $this->get_first_related('Status');
717
-    }
718
-
719
-
720
-    /**
721
-     * Gets all the extra meta info on this payment
722
-     *
723
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
724
-     * @return EE_Base_Class[]|EE_Extra_Meta
725
-     * @throws EE_Error
726
-     */
727
-    public function extra_meta($query_params = array())
728
-    {
729
-        return $this->get_many_related('Extra_Meta', $query_params);
730
-    }
731
-
732
-
733
-    /**
734
-     * Wrapper for _add_relation_to
735
-     *
736
-     * @param EE_Registration $registration
737
-     * @return EE_Base_Class the relation was added to
738
-     * @throws EE_Error
739
-     */
740
-    public function add_registration(EE_Registration $registration)
741
-    {
742
-        return $this->_add_relation_to($registration, 'Registration');
743
-    }
744
-
745
-
746
-    /**
747
-     * Removes the given registration from being related (even before saving this transaction).
748
-     * If an ID/index is provided and this transaction isn't saved yet, removes it from list of cached relations
749
-     *
750
-     * @param int $registration_or_id
751
-     * @return EE_Base_Class that was removed from being related
752
-     * @throws EE_Error
753
-     */
754
-    public function remove_registration_with_id($registration_or_id)
755
-    {
756
-        return $this->_remove_relation_to($registration_or_id, 'Registration');
757
-    }
758
-
759
-
760
-    /**
761
-     * Gets all the line items which are for ACTUAL items
762
-     *
763
-     * @return EE_Line_Item[]
764
-     * @throws EE_Error
765
-     */
766
-    public function items_purchased()
767
-    {
768
-        return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_line_item)));
769
-    }
770
-
771
-
772
-    /**
773
-     * Wrapper for _add_relation_to
774
-     *
775
-     * @param EE_Line_Item $line_item
776
-     * @return EE_Base_Class the relation was added to
777
-     * @throws EE_Error
778
-     */
779
-    public function add_line_item(EE_Line_Item $line_item)
780
-    {
781
-        return $this->_add_relation_to($line_item, 'Line_Item');
782
-    }
783
-
784
-
785
-    /**
786
-     * Gets ALL the line items related to this transaction (unstructured)
787
-     *
788
-     * @param array $query_params
789
-     * @return EE_Base_Class[]|EE_Line_Item[]
790
-     * @throws EE_Error
791
-     */
792
-    public function line_items($query_params = array())
793
-    {
794
-        return $this->get_many_related('Line_Item', $query_params);
795
-    }
796
-
797
-
798
-    /**
799
-     * Gets all the line items which are taxes on the total
800
-     *
801
-     * @return EE_Line_Item[]
802
-     * @throws EE_Error
803
-     */
804
-    public function tax_items()
805
-    {
806
-        return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
807
-    }
808
-
809
-
810
-    /**
811
-     * Gets the total line item (which is a parent of all other related line items,
812
-     * meaning it takes them all into account on its total)
813
-     *
814
-     * @param bool $create_if_not_found
815
-     * @return \EE_Line_Item
816
-     * @throws EE_Error
817
-     */
818
-    public function total_line_item($create_if_not_found = true)
819
-    {
820
-        $item = $this->get_first_related('Line_Item', array(array('LIN_type' => EEM_Line_Item::type_total)));
821
-        if (! $item && $create_if_not_found) {
822
-            $item = EEH_Line_Item::create_total_line_item($this);
823
-        }
824
-        return $item;
825
-    }
826
-
827
-
828
-    /**
829
-     * Returns the total amount of tax on this transaction
830
-     * (assumes there's only one tax subtotal line item)
831
-     *
832
-     * @return float
833
-     * @throws EE_Error
834
-     */
835
-    public function tax_total()
836
-    {
837
-        $tax_line_item = $this->tax_total_line_item();
838
-        if ($tax_line_item) {
839
-            return (float) $tax_line_item->total();
840
-        }
841
-        return (float) 0;
842
-    }
843
-
844
-
845
-    /**
846
-     * Gets the tax subtotal line item (assumes there's only one)
847
-     *
848
-     * @return EE_Line_Item
849
-     * @throws EE_Error
850
-     */
851
-    public function tax_total_line_item()
852
-    {
853
-        return EEH_Line_Item::get_taxes_subtotal($this->total_line_item());
854
-    }
855
-
856
-
857
-    /**
858
-     * Gets the array of billing info for the gateway and for this transaction's primary registration's attendee.
859
-     *
860
-     * @return EE_Form_Section_Proper
861
-     * @throws EE_Error
862
-     */
863
-    public function billing_info()
864
-    {
865
-        $payment_method = $this->payment_method();
866
-        if (! $payment_method) {
867
-            EE_Error::add_error(
868
-                __(
869
-                    'Could not find billing info for transaction because no gateway has been used for it yet',
870
-                    'event_espresso'
871
-                ),
872
-                __FILE__,
873
-                __FUNCTION__,
874
-                __LINE__
875
-            );
876
-            return null;
877
-        }
878
-        $primary_reg = $this->primary_registration();
879
-        if (! $primary_reg) {
880
-            EE_Error::add_error(
881
-                __(
882
-                    'Cannot get billing info for gateway %s on transaction because no primary registration exists',
883
-                    'event_espresso'
884
-                ),
885
-                __FILE__,
886
-                __FUNCTION__,
887
-                __LINE__
888
-            );
889
-            return null;
890
-        }
891
-        $attendee = $primary_reg->attendee();
892
-        if (! $attendee) {
893
-            EE_Error::add_error(
894
-                __(
895
-                    'Cannot get billing info for gateway %s on transaction because the primary registration has no attendee exists',
896
-                    'event_espresso'
897
-                ),
898
-                __FILE__,
899
-                __FUNCTION__,
900
-                __LINE__
901
-            );
902
-            return null;
903
-        }
904
-        return $attendee->billing_info_for_payment_method($payment_method);
905
-    }
906
-
907
-
908
-    /**
909
-     * Gets PMD_ID
910
-     *
911
-     * @return int
912
-     * @throws EE_Error
913
-     */
914
-    public function payment_method_ID()
915
-    {
916
-        return $this->get('PMD_ID');
917
-    }
918
-
919
-
920
-    /**
921
-     * Sets PMD_ID
922
-     *
923
-     * @param int $PMD_ID
924
-     * @throws EE_Error
925
-     */
926
-    public function set_payment_method_ID($PMD_ID)
927
-    {
928
-        $this->set('PMD_ID', $PMD_ID);
929
-    }
930
-
931
-
932
-    /**
933
-     * Gets the last-used payment method on this transaction
934
-     * (we COULD just use the last-made payment, but some payment methods, namely
935
-     * offline ones, dont' create payments)
936
-     *
937
-     * @return EE_Payment_Method
938
-     * @throws EE_Error
939
-     */
940
-    public function payment_method()
941
-    {
942
-        $pm = $this->get_first_related('Payment_Method');
943
-        if ($pm instanceof EE_Payment_Method) {
944
-            return $pm;
945
-        }
946
-        $last_payment = $this->last_payment();
947
-        if ($last_payment instanceof EE_Payment && $last_payment->payment_method()) {
948
-            return $last_payment->payment_method();
949
-        }
950
-        return null;
951
-    }
952
-
953
-
954
-    /**
955
-     * Gets the last payment made
956
-     *
957
-     * @return EE_Base_Class|EE_Payment
958
-     * @throws EE_Error
959
-     */
960
-    public function last_payment()
961
-    {
962
-        return $this->get_first_related('Payment', array('order_by' => array('PAY_ID' => 'desc')));
963
-    }
964
-
965
-
966
-    /**
967
-     * Gets all the line items which are unrelated to tickets on this transaction
968
-     *
969
-     * @return EE_Line_Item[]
970
-     * @throws EE_Error
971
-     * @throws InvalidArgumentException
972
-     * @throws InvalidDataTypeException
973
-     * @throws InvalidInterfaceException
974
-     */
975
-    public function non_ticket_line_items()
976
-    {
977
-        return EEM_Line_Item::instance()->get_all_non_ticket_line_items_for_transaction($this->ID());
978
-    }
979
-
980
-
981
-    /**
982
-     * possibly toggles TXN status
983
-     *
984
-     * @param  boolean $update whether to save the TXN
985
-     * @return bool whether the TXN was saved
986
-     * @throws EE_Error
987
-     * @throws RuntimeException
988
-     */
989
-    public function update_status_based_on_total_paid($update = true)
990
-    {
991
-        // set transaction status based on comparison of TXN_paid vs TXN_total
992
-        if (EEH_Money::compare_floats($this->paid(), $this->total(), '>')) {
993
-            $new_txn_status = EEM_Transaction::overpaid_status_code;
994
-        } elseif (EEH_Money::compare_floats($this->paid(), $this->total())) {
995
-            $new_txn_status = EEM_Transaction::complete_status_code;
996
-        } elseif (EEH_Money::compare_floats($this->paid(), $this->total(), '<')) {
997
-            $new_txn_status = EEM_Transaction::incomplete_status_code;
998
-        } else {
999
-            throw new RuntimeException(
1000
-                __('The total paid calculation for this transaction is inaccurate.', 'event_espresso')
1001
-            );
1002
-        }
1003
-        if ($new_txn_status !== $this->status_ID()) {
1004
-            $this->set_status($new_txn_status);
1005
-            if ($update) {
1006
-                return $this->save() ? true : false;
1007
-            }
1008
-        }
1009
-        return false;
1010
-    }
1011
-
1012
-
1013
-    /**
1014
-     * Updates the transaction's status and total_paid based on all the payments
1015
-     * that apply to it
1016
-     *
1017
-     * @deprecated
1018
-     * @return array|bool
1019
-     * @throws EE_Error
1020
-     * @throws InvalidArgumentException
1021
-     * @throws ReflectionException
1022
-     * @throws InvalidDataTypeException
1023
-     * @throws InvalidInterfaceException
1024
-     */
1025
-    public function update_based_on_payments()
1026
-    {
1027
-        EE_Error::doing_it_wrong(
1028
-            __CLASS__ . '::' . __FUNCTION__,
1029
-            sprintf(
1030
-                __('This method is deprecated. Please use "%s" instead', 'event_espresso'),
1031
-                'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
1032
-            ),
1033
-            '4.6.0'
1034
-        );
1035
-        /** @type EE_Transaction_Processor $transaction_processor */
1036
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
1037
-        return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($this);
1038
-    }
1039
-
1040
-
1041
-    /**
1042
-     * @return string
1043
-     */
1044
-    public function old_txn_status()
1045
-    {
1046
-        return $this->_old_txn_status;
1047
-    }
1048
-
1049
-
1050
-    /**
1051
-     * @param string $old_txn_status
1052
-     */
1053
-    public function set_old_txn_status($old_txn_status)
1054
-    {
1055
-        // only set the first time
1056
-        if ($this->_old_txn_status === null) {
1057
-            $this->_old_txn_status = $old_txn_status;
1058
-        }
1059
-    }
1060
-
1061
-
1062
-    /**
1063
-     * reg_status_updated
1064
-     *
1065
-     * @return bool
1066
-     * @throws EE_Error
1067
-     */
1068
-    public function txn_status_updated()
1069
-    {
1070
-        return $this->status_ID() !== $this->_old_txn_status && $this->_old_txn_status !== null;
1071
-    }
1072
-
1073
-
1074
-    /**
1075
-     * _reg_steps_completed
1076
-     * if $check_all is TRUE, then returns TRUE if ALL reg steps have been marked as completed,
1077
-     * if a $reg_step_slug is provided, then this step will be skipped when testing for completion
1078
-     * if $check_all is FALSE and a $reg_step_slug is provided, then ONLY that reg step will be tested for completion
1079
-     *
1080
-     * @param string $reg_step_slug
1081
-     * @param bool   $check_all
1082
-     * @return bool|int
1083
-     * @throws EE_Error
1084
-     */
1085
-    private function _reg_steps_completed($reg_step_slug = '', $check_all = true)
1086
-    {
1087
-        $reg_steps = $this->reg_steps();
1088
-        if (! is_array($reg_steps) || empty($reg_steps)) {
1089
-            return false;
1090
-        }
1091
-        // loop thru reg steps array)
1092
-        foreach ($reg_steps as $slug => $reg_step_completed) {
1093
-            // if NOT checking ALL steps (only checking one step)
1094
-            if (! $check_all) {
1095
-                // and this is the one
1096
-                if ($slug === $reg_step_slug) {
1097
-                    return $reg_step_completed;
1098
-                }
1099
-                // skip to next reg step in loop
1100
-                continue;
1101
-            }
1102
-            // $check_all must be true, else we would never have gotten to this point
1103
-            if ($slug === $reg_step_slug) {
1104
-                // if we reach this point, then we are testing either:
1105
-                // all_reg_steps_completed_except() or
1106
-                // all_reg_steps_completed_except_final_step(),
1107
-                // and since this is the reg step EXCEPTION being tested
1108
-                // we want to return true (yes true) if this reg step is NOT completed
1109
-                // ie: "is everything completed except the final step?"
1110
-                // "that is correct... the final step is not completed, but all others are."
1111
-                return $reg_step_completed !== true;
1112
-            }
1113
-            if ($reg_step_completed !== true) {
1114
-                // if any reg step is NOT completed, then ALL steps are not completed
1115
-                return false;
1116
-            }
1117
-        }
1118
-        return true;
1119
-    }
1120
-
1121
-
1122
-    /**
1123
-     * all_reg_steps_completed
1124
-     * returns:
1125
-     *    true if ALL reg steps have been marked as completed
1126
-     *        or false if any step is not completed
1127
-     *
1128
-     * @return bool
1129
-     * @throws EE_Error
1130
-     */
1131
-    public function all_reg_steps_completed()
1132
-    {
1133
-        return $this->_reg_steps_completed();
1134
-    }
1135
-
1136
-
1137
-    /**
1138
-     * all_reg_steps_completed_except
1139
-     * returns:
1140
-     *        true if ALL reg steps, except a particular step that you wish to skip over, have been marked as completed
1141
-     *        or false if any other step is not completed
1142
-     *        or false if ALL steps are completed including the exception you are testing !!!
1143
-     *
1144
-     * @param string $exception
1145
-     * @return bool
1146
-     * @throws EE_Error
1147
-     */
1148
-    public function all_reg_steps_completed_except($exception = '')
1149
-    {
1150
-        return $this->_reg_steps_completed($exception);
1151
-    }
1152
-
1153
-
1154
-    /**
1155
-     * all_reg_steps_completed_except
1156
-     * returns:
1157
-     *        true if ALL reg steps, except the final step, have been marked as completed
1158
-     *        or false if any step is not completed
1159
-     *    or false if ALL steps are completed including the final step !!!
1160
-     *
1161
-     * @return bool
1162
-     * @throws EE_Error
1163
-     */
1164
-    public function all_reg_steps_completed_except_final_step()
1165
-    {
1166
-        return $this->_reg_steps_completed('finalize_registration');
1167
-    }
1168
-
1169
-
1170
-    /**
1171
-     * reg_step_completed
1172
-     * returns:
1173
-     *    true if a specific reg step has been marked as completed
1174
-     *    a Unix timestamp if it has been initialized but not yet completed,
1175
-     *    or false if it has not yet been initialized
1176
-     *
1177
-     * @param string $reg_step_slug
1178
-     * @return bool|int
1179
-     * @throws EE_Error
1180
-     */
1181
-    public function reg_step_completed($reg_step_slug)
1182
-    {
1183
-        return $this->_reg_steps_completed($reg_step_slug, false);
1184
-    }
1185
-
1186
-
1187
-    /**
1188
-     * completed_final_reg_step
1189
-     * returns:
1190
-     *    true if the finalize_registration reg step has been marked as completed
1191
-     *    a Unix timestamp if it has been initialized but not yet completed,
1192
-     *    or false if it has not yet been initialized
1193
-     *
1194
-     * @return bool|int
1195
-     * @throws EE_Error
1196
-     */
1197
-    public function final_reg_step_completed()
1198
-    {
1199
-        return $this->_reg_steps_completed('finalize_registration', false);
1200
-    }
1201
-
1202
-
1203
-    /**
1204
-     * set_reg_step_initiated
1205
-     * given a valid TXN_reg_step, this sets it's value to a unix timestamp
1206
-     *
1207
-     * @param string $reg_step_slug
1208
-     * @return boolean
1209
-     * @throws EE_Error
1210
-     */
1211
-    public function set_reg_step_initiated($reg_step_slug)
1212
-    {
1213
-        return $this->_set_reg_step_completed_status($reg_step_slug, time());
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * set_reg_step_completed
1219
-     * given a valid TXN_reg_step, this sets the step as completed
1220
-     *
1221
-     * @param string $reg_step_slug
1222
-     * @return boolean
1223
-     * @throws EE_Error
1224
-     */
1225
-    public function set_reg_step_completed($reg_step_slug)
1226
-    {
1227
-        return $this->_set_reg_step_completed_status($reg_step_slug, true);
1228
-    }
1229
-
1230
-
1231
-    /**
1232
-     * set_reg_step_completed
1233
-     * given a valid TXN_reg_step slug, this sets the step as NOT completed
1234
-     *
1235
-     * @param string $reg_step_slug
1236
-     * @return boolean
1237
-     * @throws EE_Error
1238
-     */
1239
-    public function set_reg_step_not_completed($reg_step_slug)
1240
-    {
1241
-        return $this->_set_reg_step_completed_status($reg_step_slug, false);
1242
-    }
1243
-
1244
-
1245
-    /**
1246
-     * set_reg_step_completed
1247
-     * given a valid reg step slug, this sets the TXN_reg_step completed status which is either:
1248
-     *
1249
-     * @param  string      $reg_step_slug
1250
-     * @param  boolean|int $status
1251
-     * @return boolean
1252
-     * @throws EE_Error
1253
-     */
1254
-    private function _set_reg_step_completed_status($reg_step_slug, $status)
1255
-    {
1256
-        // validate status
1257
-        $status = is_bool($status) || is_int($status) ? $status : false;
1258
-        // get reg steps array
1259
-        $txn_reg_steps = $this->reg_steps();
1260
-        // if reg step does NOT exist
1261
-        if (! isset($txn_reg_steps[ $reg_step_slug ])) {
1262
-            return false;
1263
-        }
1264
-        // if  we're trying to complete a step that is already completed
1265
-        if ($txn_reg_steps[ $reg_step_slug ] === true) {
1266
-            return true;
1267
-        }
1268
-        // if  we're trying to complete a step that hasn't even started
1269
-        if ($status === true && $txn_reg_steps[ $reg_step_slug ] === false) {
1270
-            return false;
1271
-        }
1272
-        // if current status value matches the incoming value (no change)
1273
-        // type casting as int means values should collapse to either 0, 1, or a timestamp like 1234567890
1274
-        if ((int) $txn_reg_steps[ $reg_step_slug ] === (int) $status) {
1275
-            // this will happen in cases where multiple AJAX requests occur during the same step
1276
-            return true;
1277
-        }
1278
-        // if we're trying to set a start time, but it has already been set...
1279
-        if (is_numeric($status) && is_numeric($txn_reg_steps[ $reg_step_slug ])) {
1280
-            // skip the update below, but don't return FALSE so that errors won't be displayed
1281
-            return true;
1282
-        }
1283
-        // update completed status
1284
-        $txn_reg_steps[ $reg_step_slug ] = $status;
1285
-        $this->set_reg_steps($txn_reg_steps);
1286
-        $this->save();
1287
-        return true;
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * remove_reg_step
1293
-     * given a valid TXN_reg_step slug, this will remove (unset)
1294
-     * the reg step from the TXN reg step array
1295
-     *
1296
-     * @param string $reg_step_slug
1297
-     * @return void
1298
-     * @throws EE_Error
1299
-     */
1300
-    public function remove_reg_step($reg_step_slug)
1301
-    {
1302
-        // get reg steps array
1303
-        $txn_reg_steps = $this->reg_steps();
1304
-        unset($txn_reg_steps[ $reg_step_slug ]);
1305
-        $this->set_reg_steps($txn_reg_steps);
1306
-    }
1307
-
1308
-
1309
-    /**
1310
-     * toggle_failed_transaction_status
1311
-     * upgrades a TXNs status from failed to abandoned,
1312
-     * meaning that contact information has been captured for at least one registrant
1313
-     *
1314
-     * @param bool $save
1315
-     * @return bool
1316
-     * @throws EE_Error
1317
-     */
1318
-    public function toggle_failed_transaction_status($save = true)
1319
-    {
1320
-        // if TXN status is still set as "failed"...
1321
-        if ($this->status_ID() === EEM_Transaction::failed_status_code) {
1322
-            $this->set_status(EEM_Transaction::abandoned_status_code);
1323
-            if ($save) {
1324
-                $this->save();
1325
-            }
1326
-            return true;
1327
-        }
1328
-        return false;
1329
-    }
1330
-
1331
-
1332
-    /**
1333
-     * toggle_abandoned_transaction_status
1334
-     * upgrades a TXNs status from failed or abandoned to incomplete
1335
-     *
1336
-     * @return bool
1337
-     * @throws EE_Error
1338
-     */
1339
-    public function toggle_abandoned_transaction_status()
1340
-    {
1341
-        // if TXN status has not been updated already due to a payment, and is still set as "failed" or "abandoned"...
1342
-        $txn_status = $this->status_ID();
1343
-        if ($txn_status === EEM_Transaction::failed_status_code
1344
-            || $txn_status === EEM_Transaction::abandoned_status_code
1345
-        ) {
1346
-            // if a contact record for the primary registrant has been created
1347
-            if ($this->primary_registration() instanceof EE_Registration
1348
-                && $this->primary_registration()->attendee() instanceof EE_Attendee
1349
-            ) {
1350
-                $this->set_status(EEM_Transaction::incomplete_status_code);
1351
-            } else {
1352
-                // no contact record? yer abandoned!
1353
-                $this->set_status(EEM_Transaction::abandoned_status_code);
1354
-            }
1355
-            return true;
1356
-        }
1357
-        return false;
1358
-    }
1359
-
1360
-
1361
-    /**
1362
-     * checks if an Abandoned TXN has any related payments, and if so,
1363
-     * updates the TXN status based on the amount paid
1364
-     *
1365
-     * @throws EE_Error
1366
-     * @throws InvalidDataTypeException
1367
-     * @throws InvalidInterfaceException
1368
-     * @throws InvalidArgumentException
1369
-     * @throws RuntimeException
1370
-     */
1371
-    public function verify_abandoned_transaction_status()
1372
-    {
1373
-        if ($this->status_ID() !== EEM_Transaction::abandoned_status_code) {
1374
-            return;
1375
-        }
1376
-        $payments = $this->get_many_related('Payment');
1377
-        if (! empty($payments)) {
1378
-            foreach ($payments as $payment) {
1379
-                if ($payment instanceof EE_Payment) {
1380
-                    // kk this TXN should NOT be abandoned
1381
-                    $this->update_status_based_on_total_paid();
1382
-                    if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1383
-                        EE_Error::add_attention(
1384
-                            sprintf(
1385
-                                esc_html__(
1386
-                                    'The status for Transaction #%1$d has been updated from "Abandoned" to "%2$s", because at least one payment has been made towards it. If the payment appears in the "Payment Details" table below, you may need to edit its status and/or other details as well.',
1387
-                                    'event_espresso'
1388
-                                ),
1389
-                                $this->ID(),
1390
-                                $this->pretty_status()
1391
-                            )
1392
-                        );
1393
-                    }
1394
-                    // get final reg step status
1395
-                    $finalized = $this->final_reg_step_completed();
1396
-                    // if the 'finalize_registration' step has been initiated (has a timestamp)
1397
-                    // but has not yet been fully completed (TRUE)
1398
-                    if (is_int($finalized) && $finalized !== false && $finalized !== true) {
1399
-                        $this->set_reg_step_completed('finalize_registration');
1400
-                        $this->save();
1401
-                    }
1402
-                }
1403
-            }
1404
-        }
1405
-    }
16
+	/**
17
+	 * The length of time in seconds that a lock is applied before being considered expired.
18
+	 * It is not long because a transaction should only be locked for the duration of the request that locked it
19
+	 */
20
+	const LOCK_EXPIRATION = 2;
21
+
22
+	/**
23
+	 * txn status upon initial construction.
24
+	 *
25
+	 * @var string
26
+	 */
27
+	protected $_old_txn_status;
28
+
29
+
30
+	/**
31
+	 * @param array  $props_n_values          incoming values
32
+	 * @param string $timezone                incoming timezone
33
+	 *                                        (if not set the timezone set for the website will be used.)
34
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
35
+	 *                                        date_format and the second value is the time format
36
+	 * @return EE_Transaction
37
+	 * @throws EE_Error
38
+	 */
39
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
40
+	{
41
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
42
+		$txn = $has_object
43
+			? $has_object
44
+			: new self($props_n_values, false, $timezone, $date_formats);
45
+		if (! $has_object) {
46
+			$txn->set_old_txn_status($txn->status_ID());
47
+		}
48
+		return $txn;
49
+	}
50
+
51
+
52
+	/**
53
+	 * @param array  $props_n_values  incoming values from the database
54
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
55
+	 *                                the website will be used.
56
+	 * @return EE_Transaction
57
+	 * @throws EE_Error
58
+	 */
59
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
60
+	{
61
+		$txn = new self($props_n_values, true, $timezone);
62
+		$txn->set_old_txn_status($txn->status_ID());
63
+		return $txn;
64
+	}
65
+
66
+
67
+	/**
68
+	 * Sets a meta field indicating that this TXN is locked and should not be updated in the db.
69
+	 * If a lock has already been set, then we will attempt to remove it in case it has expired.
70
+	 * If that also fails, then an exception is thrown.
71
+	 *
72
+	 * @throws EE_Error
73
+	 */
74
+	public function lock()
75
+	{
76
+		// attempt to set lock, but if that fails...
77
+		if (! $this->add_extra_meta('lock', time(), true)) {
78
+			// then attempt to remove the lock in case it is expired
79
+			if ($this->_remove_expired_lock()) {
80
+				// if removal was successful, then try setting lock again
81
+				$this->lock();
82
+			} else {
83
+				// but if the lock can not be removed, then throw an exception
84
+				throw new EE_Error(
85
+					sprintf(
86
+						__(
87
+							'Could not lock Transaction %1$d because it is already locked, meaning another part of the system is currently editing it. It should already be unlocked by the time you read this, so please refresh the page and try again.',
88
+							'event_espresso'
89
+						),
90
+						$this->ID()
91
+					)
92
+				);
93
+			}
94
+		}
95
+	}
96
+
97
+
98
+	/**
99
+	 * removes transaction lock applied in EE_Transaction::lock()
100
+	 *
101
+	 * @return int
102
+	 * @throws EE_Error
103
+	 */
104
+	public function unlock()
105
+	{
106
+		return $this->delete_extra_meta('lock');
107
+	}
108
+
109
+
110
+	/**
111
+	 * Decides whether or not now is the right time to update the transaction.
112
+	 * This is useful because we don't always know if it is safe to update the transaction
113
+	 * and its related data. why?
114
+	 * because it's possible that the transaction is being used in another
115
+	 * request and could overwrite anything we save.
116
+	 * So we want to only update the txn once we know that won't happen.
117
+	 * We also check that the lock isn't expired, and remove it if it is
118
+	 *
119
+	 * @return boolean
120
+	 * @throws EE_Error
121
+	 */
122
+	public function is_locked()
123
+	{
124
+		// if TXN is not locked, then return false immediately
125
+		if (! $this->_get_lock()) {
126
+			return false;
127
+		}
128
+		// if not, then let's try and remove the lock in case it's expired...
129
+		// _remove_expired_lock() returns 0 when lock is valid (ie: removed = false)
130
+		// and a positive number if the lock was removed (ie: number of locks deleted),
131
+		// so we need to return the opposite
132
+		return ! $this->_remove_expired_lock() ? true : false;
133
+	}
134
+
135
+
136
+	/**
137
+	 * Gets the meta field indicating that this TXN is locked
138
+	 *
139
+	 * @return int
140
+	 * @throws EE_Error
141
+	 */
142
+	protected function _get_lock()
143
+	{
144
+		return (int) $this->get_extra_meta('lock', true, 0);
145
+	}
146
+
147
+
148
+	/**
149
+	 * If the lock on this transaction is expired, then we want to remove it so that the transaction can be updated
150
+	 *
151
+	 * @return int
152
+	 * @throws EE_Error
153
+	 */
154
+	protected function _remove_expired_lock()
155
+	{
156
+		$locked = $this->_get_lock();
157
+		if ($locked && time() - EE_Transaction::LOCK_EXPIRATION > $locked) {
158
+			return $this->unlock();
159
+		}
160
+		return 0;
161
+	}
162
+
163
+
164
+	/**
165
+	 * Set transaction total
166
+	 *
167
+	 * @param float $total total value of transaction
168
+	 * @throws EE_Error
169
+	 */
170
+	public function set_total($total = 0.00)
171
+	{
172
+		$this->set('TXN_total', (float) $total);
173
+	}
174
+
175
+
176
+	/**
177
+	 * Set Total Amount Paid to Date
178
+	 *
179
+	 * @param float $total_paid total amount paid to date (sum of all payments)
180
+	 * @throws EE_Error
181
+	 */
182
+	public function set_paid($total_paid = 0.00)
183
+	{
184
+		$this->set('TXN_paid', (float) $total_paid);
185
+	}
186
+
187
+
188
+	/**
189
+	 * Set transaction status
190
+	 *
191
+	 * @param string $status        whether the transaction is open, declined, accepted,
192
+	 *                              or any number of custom values that can be set
193
+	 * @throws EE_Error
194
+	 */
195
+	public function set_status($status = '')
196
+	{
197
+		$this->set('STS_ID', $status);
198
+	}
199
+
200
+
201
+	/**
202
+	 * Set hash salt
203
+	 *
204
+	 * @param string $hash_salt required for some payment gateways
205
+	 * @throws EE_Error
206
+	 */
207
+	public function set_hash_salt($hash_salt = '')
208
+	{
209
+		$this->set('TXN_hash_salt', $hash_salt);
210
+	}
211
+
212
+
213
+	/**
214
+	 * Sets TXN_reg_steps array
215
+	 *
216
+	 * @param array $txn_reg_steps
217
+	 * @throws EE_Error
218
+	 */
219
+	public function set_reg_steps(array $txn_reg_steps)
220
+	{
221
+		$this->set('TXN_reg_steps', $txn_reg_steps);
222
+	}
223
+
224
+
225
+	/**
226
+	 * Gets TXN_reg_steps
227
+	 *
228
+	 * @return array
229
+	 * @throws EE_Error
230
+	 */
231
+	public function reg_steps()
232
+	{
233
+		$TXN_reg_steps = $this->get('TXN_reg_steps');
234
+		return is_array($TXN_reg_steps) ? (array) $TXN_reg_steps : array();
235
+	}
236
+
237
+
238
+	/**
239
+	 * @return string of transaction's total cost, with currency symbol and decimal
240
+	 * @throws EE_Error
241
+	 */
242
+	public function pretty_total()
243
+	{
244
+		return $this->get_pretty('TXN_total');
245
+	}
246
+
247
+
248
+	/**
249
+	 * Gets the amount paid in a pretty string (formatted and with currency symbol)
250
+	 *
251
+	 * @return string
252
+	 * @throws EE_Error
253
+	 */
254
+	public function pretty_paid()
255
+	{
256
+		return $this->get_pretty('TXN_paid');
257
+	}
258
+
259
+
260
+	/**
261
+	 * calculate the amount remaining for this transaction and return;
262
+	 *
263
+	 * @return float amount remaining
264
+	 * @throws EE_Error
265
+	 */
266
+	public function remaining()
267
+	{
268
+		return $this->total() - $this->paid();
269
+	}
270
+
271
+
272
+	/**
273
+	 * get Transaction Total
274
+	 *
275
+	 * @return float
276
+	 * @throws EE_Error
277
+	 */
278
+	public function total()
279
+	{
280
+		return (float) $this->get('TXN_total');
281
+	}
282
+
283
+
284
+	/**
285
+	 * get Total Amount Paid to Date
286
+	 *
287
+	 * @return float
288
+	 * @throws EE_Error
289
+	 */
290
+	public function paid()
291
+	{
292
+		return (float) $this->get('TXN_paid');
293
+	}
294
+
295
+
296
+	/**
297
+	 * @throws EE_Error
298
+	 */
299
+	public function get_cart_session()
300
+	{
301
+		$session_data = (array) $this->get('TXN_session_data');
302
+		return isset($session_data['cart']) && $session_data['cart'] instanceof EE_Cart
303
+			? $session_data['cart']
304
+			: null;
305
+	}
306
+
307
+
308
+	/**
309
+	 * get Transaction session data
310
+	 *
311
+	 * @throws EE_Error
312
+	 */
313
+	public function session_data()
314
+	{
315
+		$session_data = $this->get('TXN_session_data');
316
+		if (empty($session_data)) {
317
+			$session_data = array(
318
+				'id'            => null,
319
+				'user_id'       => null,
320
+				'ip_address'    => null,
321
+				'user_agent'    => null,
322
+				'init_access'   => null,
323
+				'last_access'   => null,
324
+				'pages_visited' => array(),
325
+			);
326
+		}
327
+		return $session_data;
328
+	}
329
+
330
+
331
+	/**
332
+	 * Set session data within the TXN object
333
+	 *
334
+	 * @param EE_Session|array $session_data
335
+	 * @throws EE_Error
336
+	 */
337
+	public function set_txn_session_data($session_data)
338
+	{
339
+		if ($session_data instanceof EE_Session) {
340
+			$this->set('TXN_session_data', $session_data->get_session_data(null, true));
341
+		} else {
342
+			$this->set('TXN_session_data', $session_data);
343
+		}
344
+	}
345
+
346
+
347
+	/**
348
+	 * get Transaction hash salt
349
+	 *
350
+	 * @throws EE_Error
351
+	 */
352
+	public function hash_salt_()
353
+	{
354
+		return $this->get('TXN_hash_salt');
355
+	}
356
+
357
+
358
+	/**
359
+	 * Returns the transaction datetime as either:
360
+	 *            - unix timestamp format ($format = false, $gmt = true)
361
+	 *            - formatted date string including the UTC (timezone) offset ($format = true ($gmt
362
+	 *              has no affect with this option)), this also may include a timezone abbreviation if the
363
+	 *              set timezone in this class differs from what the timezone is on the blog.
364
+	 *            - formatted date string including the UTC (timezone) offset (default).
365
+	 *
366
+	 * @param boolean $format   - whether to return a unix timestamp (default) or formatted date string
367
+	 * @param boolean $gmt      - whether to return a unix timestamp with UTC offset applied (default)
368
+	 *                          or no UTC offset applied
369
+	 * @return string | int
370
+	 * @throws EE_Error
371
+	 */
372
+	public function datetime($format = false, $gmt = false)
373
+	{
374
+		if ($format) {
375
+			return $this->get_pretty('TXN_timestamp');
376
+		}
377
+		if ($gmt) {
378
+			return $this->get_raw('TXN_timestamp');
379
+		}
380
+		return $this->get('TXN_timestamp');
381
+	}
382
+
383
+
384
+	/**
385
+	 * Gets registrations on this transaction
386
+	 *
387
+	 * @param array   $query_params array of query parameters
388
+	 * @param boolean $get_cached   TRUE to retrieve cached registrations or FALSE to pull from the db
389
+	 * @return EE_Base_Class[]|EE_Registration[]
390
+	 * @throws EE_Error
391
+	 */
392
+	public function registrations($query_params = array(), $get_cached = false)
393
+	{
394
+		$query_params = (empty($query_params) || ! is_array($query_params))
395
+			? array(
396
+				'order_by' => array(
397
+					'Event.EVT_name'     => 'ASC',
398
+					'Attendee.ATT_lname' => 'ASC',
399
+					'Attendee.ATT_fname' => 'ASC',
400
+				),
401
+			)
402
+			: $query_params;
403
+		$query_params = $get_cached ? array() : $query_params;
404
+		return $this->get_many_related('Registration', $query_params);
405
+	}
406
+
407
+
408
+	/**
409
+	 * Gets all the attendees for this transaction (handy for use with EE_Attendee's get_registrations_for_event
410
+	 * function for getting attendees and how many registrations they each have for an event)
411
+	 *
412
+	 * @return mixed EE_Attendee[] by default, int if $output is set to 'COUNT'
413
+	 * @throws EE_Error
414
+	 */
415
+	public function attendees()
416
+	{
417
+		return $this->get_many_related('Attendee', array(array('Registration.Transaction.TXN_ID' => $this->ID())));
418
+	}
419
+
420
+
421
+	/**
422
+	 * Gets payments for this transaction. Unlike other such functions, order by 'DESC' by default
423
+	 *
424
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
425
+	 * @return EE_Base_Class[]|EE_Payment[]
426
+	 * @throws EE_Error
427
+	 */
428
+	public function payments($query_params = array())
429
+	{
430
+		return $this->get_many_related('Payment', $query_params);
431
+	}
432
+
433
+
434
+	/**
435
+	 * gets only approved payments for this transaction
436
+	 *
437
+	 * @return EE_Base_Class[]|EE_Payment[]
438
+	 * @throws EE_Error
439
+	 * @throws InvalidArgumentException
440
+	 * @throws ReflectionException
441
+	 * @throws InvalidDataTypeException
442
+	 * @throws InvalidInterfaceException
443
+	 */
444
+	public function approved_payments()
445
+	{
446
+		EE_Registry::instance()->load_model('Payment');
447
+		return $this->get_many_related(
448
+			'Payment',
449
+			array(
450
+				array('STS_ID' => EEM_Payment::status_id_approved),
451
+				'order_by' => array('PAY_timestamp' => 'DESC'),
452
+			)
453
+		);
454
+	}
455
+
456
+
457
+	/**
458
+	 * Gets all payments which have not been approved
459
+	 *
460
+	 * @return EE_Base_Class[]|EEI_Payment[]
461
+	 * @throws EE_Error if a model is misconfigured somehow
462
+	 */
463
+	public function pending_payments()
464
+	{
465
+		return $this->get_many_related(
466
+			'Payment',
467
+			array(
468
+				array(
469
+					'STS_ID' => EEM_Payment::status_id_pending,
470
+				),
471
+				'order_by' => array(
472
+					'PAY_timestamp' => 'DESC',
473
+				),
474
+			)
475
+		);
476
+	}
477
+
478
+
479
+	/**
480
+	 * echoes $this->pretty_status()
481
+	 *
482
+	 * @param bool $show_icons
483
+	 * @throws EE_Error
484
+	 * @throws InvalidArgumentException
485
+	 * @throws InvalidDataTypeException
486
+	 * @throws InvalidInterfaceException
487
+	 */
488
+	public function e_pretty_status($show_icons = false)
489
+	{
490
+		echo $this->pretty_status($show_icons);
491
+	}
492
+
493
+
494
+	/**
495
+	 * returns a pretty version of the status, good for displaying to users
496
+	 *
497
+	 * @param bool $show_icons
498
+	 * @return string
499
+	 * @throws EE_Error
500
+	 * @throws InvalidArgumentException
501
+	 * @throws InvalidDataTypeException
502
+	 * @throws InvalidInterfaceException
503
+	 */
504
+	public function pretty_status($show_icons = false)
505
+	{
506
+		$status = EEM_Status::instance()->localized_status(
507
+			array($this->status_ID() => __('unknown', 'event_espresso')),
508
+			false,
509
+			'sentence'
510
+		);
511
+		$icon = '';
512
+		switch ($this->status_ID()) {
513
+			case EEM_Transaction::complete_status_code:
514
+				$icon = $show_icons ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>' : '';
515
+				break;
516
+			case EEM_Transaction::incomplete_status_code:
517
+				$icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 lt-blue-text"></span>'
518
+					: '';
519
+				break;
520
+			case EEM_Transaction::abandoned_status_code:
521
+				$icon = $show_icons ? '<span class="dashicons dashicons-marker ee-icon-size-16 red-text"></span>' : '';
522
+				break;
523
+			case EEM_Transaction::failed_status_code:
524
+				$icon = $show_icons ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>' : '';
525
+				break;
526
+			case EEM_Transaction::overpaid_status_code:
527
+				$icon = $show_icons ? '<span class="dashicons dashicons-plus ee-icon-size-16 orange-text"></span>' : '';
528
+				break;
529
+		}
530
+		return $icon . $status[ $this->status_ID() ];
531
+	}
532
+
533
+
534
+	/**
535
+	 * get Transaction Status
536
+	 *
537
+	 * @throws EE_Error
538
+	 */
539
+	public function status_ID()
540
+	{
541
+		return $this->get('STS_ID');
542
+	}
543
+
544
+
545
+	/**
546
+	 * Returns TRUE or FALSE for whether or not this transaction cost any money
547
+	 *
548
+	 * @return boolean
549
+	 * @throws EE_Error
550
+	 */
551
+	public function is_free()
552
+	{
553
+		return EEH_Money::compare_floats($this->get('TXN_total'), 0, '==');
554
+	}
555
+
556
+
557
+	/**
558
+	 * Returns whether this transaction is complete
559
+	 * Useful in templates and other logic for deciding if we should ask for another payment...
560
+	 *
561
+	 * @return boolean
562
+	 * @throws EE_Error
563
+	 */
564
+	public function is_completed()
565
+	{
566
+		return $this->status_ID() === EEM_Transaction::complete_status_code;
567
+	}
568
+
569
+
570
+	/**
571
+	 * Returns whether this transaction is incomplete
572
+	 * Useful in templates and other logic for deciding if we should ask for another payment...
573
+	 *
574
+	 * @return boolean
575
+	 * @throws EE_Error
576
+	 */
577
+	public function is_incomplete()
578
+	{
579
+		return $this->status_ID() === EEM_Transaction::incomplete_status_code;
580
+	}
581
+
582
+
583
+	/**
584
+	 * Returns whether this transaction is overpaid
585
+	 * Useful in templates and other logic for deciding if monies need to be refunded
586
+	 *
587
+	 * @return boolean
588
+	 * @throws EE_Error
589
+	 */
590
+	public function is_overpaid()
591
+	{
592
+		return $this->status_ID() === EEM_Transaction::overpaid_status_code;
593
+	}
594
+
595
+
596
+	/**
597
+	 * Returns whether this transaction was abandoned
598
+	 * meaning that the transaction/registration process was somehow interrupted and never completed
599
+	 * but that contact information exists for at least one registrant
600
+	 *
601
+	 * @return boolean
602
+	 * @throws EE_Error
603
+	 */
604
+	public function is_abandoned()
605
+	{
606
+		return $this->status_ID() === EEM_Transaction::abandoned_status_code;
607
+	}
608
+
609
+
610
+	/**
611
+	 * Returns whether this transaction failed
612
+	 * meaning that the transaction/registration process was somehow interrupted and never completed
613
+	 * and that NO contact information exists for any registrants
614
+	 *
615
+	 * @return boolean
616
+	 * @throws EE_Error
617
+	 */
618
+	public function failed()
619
+	{
620
+		return $this->status_ID() === EEM_Transaction::failed_status_code;
621
+	}
622
+
623
+
624
+	/**
625
+	 * This returns the url for the invoice of this transaction
626
+	 *
627
+	 * @param string $type 'html' or 'pdf' (default is pdf)
628
+	 * @return string
629
+	 * @throws EE_Error
630
+	 */
631
+	public function invoice_url($type = 'html')
632
+	{
633
+		$REG = $this->primary_registration();
634
+		if (! $REG instanceof EE_Registration) {
635
+			return '';
636
+		}
637
+		return $REG->invoice_url($type);
638
+	}
639
+
640
+
641
+	/**
642
+	 * Gets the primary registration only
643
+	 *
644
+	 * @return EE_Base_Class|EE_Registration
645
+	 * @throws EE_Error
646
+	 */
647
+	public function primary_registration()
648
+	{
649
+		$registrations = (array) $this->get_many_related(
650
+			'Registration',
651
+			array(array('REG_count' => EEM_Registration::PRIMARY_REGISTRANT_COUNT))
652
+		);
653
+		foreach ($registrations as $registration) {
654
+			// valid registration that is NOT cancelled or declined ?
655
+			if ($registration instanceof EE_Registration
656
+				&& ! in_array($registration->status_ID(), EEM_Registration::closed_reg_statuses(), true)
657
+			) {
658
+				return $registration;
659
+			}
660
+		}
661
+		// nothing valid found, so just return first thing from array of results
662
+		return reset($registrations);
663
+	}
664
+
665
+
666
+	/**
667
+	 * Gets the URL for viewing the receipt
668
+	 *
669
+	 * @param string $type 'pdf' or 'html' (default is 'html')
670
+	 * @return string
671
+	 * @throws EE_Error
672
+	 */
673
+	public function receipt_url($type = 'html')
674
+	{
675
+		$REG = $this->primary_registration();
676
+		if (! $REG instanceof EE_Registration) {
677
+			return '';
678
+		}
679
+		return $REG->receipt_url($type);
680
+	}
681
+
682
+
683
+	/**
684
+	 * Gets the URL of the thank you page with this registration REG_url_link added as
685
+	 * a query parameter
686
+	 *
687
+	 * @return string
688
+	 * @throws EE_Error
689
+	 */
690
+	public function payment_overview_url()
691
+	{
692
+		$primary_registration = $this->primary_registration();
693
+		return $primary_registration instanceof EE_Registration ? $primary_registration->payment_overview_url() : false;
694
+	}
695
+
696
+
697
+	/**
698
+	 * @return string
699
+	 * @throws EE_Error
700
+	 */
701
+	public function gateway_response_on_transaction()
702
+	{
703
+		$payment = $this->get_first_related('Payment');
704
+		return $payment instanceof EE_Payment ? $payment->gateway_response() : '';
705
+	}
706
+
707
+
708
+	/**
709
+	 * Get the status object of this object
710
+	 *
711
+	 * @return EE_Base_Class|EE_Status
712
+	 * @throws EE_Error
713
+	 */
714
+	public function status_obj()
715
+	{
716
+		return $this->get_first_related('Status');
717
+	}
718
+
719
+
720
+	/**
721
+	 * Gets all the extra meta info on this payment
722
+	 *
723
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
724
+	 * @return EE_Base_Class[]|EE_Extra_Meta
725
+	 * @throws EE_Error
726
+	 */
727
+	public function extra_meta($query_params = array())
728
+	{
729
+		return $this->get_many_related('Extra_Meta', $query_params);
730
+	}
731
+
732
+
733
+	/**
734
+	 * Wrapper for _add_relation_to
735
+	 *
736
+	 * @param EE_Registration $registration
737
+	 * @return EE_Base_Class the relation was added to
738
+	 * @throws EE_Error
739
+	 */
740
+	public function add_registration(EE_Registration $registration)
741
+	{
742
+		return $this->_add_relation_to($registration, 'Registration');
743
+	}
744
+
745
+
746
+	/**
747
+	 * Removes the given registration from being related (even before saving this transaction).
748
+	 * If an ID/index is provided and this transaction isn't saved yet, removes it from list of cached relations
749
+	 *
750
+	 * @param int $registration_or_id
751
+	 * @return EE_Base_Class that was removed from being related
752
+	 * @throws EE_Error
753
+	 */
754
+	public function remove_registration_with_id($registration_or_id)
755
+	{
756
+		return $this->_remove_relation_to($registration_or_id, 'Registration');
757
+	}
758
+
759
+
760
+	/**
761
+	 * Gets all the line items which are for ACTUAL items
762
+	 *
763
+	 * @return EE_Line_Item[]
764
+	 * @throws EE_Error
765
+	 */
766
+	public function items_purchased()
767
+	{
768
+		return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_line_item)));
769
+	}
770
+
771
+
772
+	/**
773
+	 * Wrapper for _add_relation_to
774
+	 *
775
+	 * @param EE_Line_Item $line_item
776
+	 * @return EE_Base_Class the relation was added to
777
+	 * @throws EE_Error
778
+	 */
779
+	public function add_line_item(EE_Line_Item $line_item)
780
+	{
781
+		return $this->_add_relation_to($line_item, 'Line_Item');
782
+	}
783
+
784
+
785
+	/**
786
+	 * Gets ALL the line items related to this transaction (unstructured)
787
+	 *
788
+	 * @param array $query_params
789
+	 * @return EE_Base_Class[]|EE_Line_Item[]
790
+	 * @throws EE_Error
791
+	 */
792
+	public function line_items($query_params = array())
793
+	{
794
+		return $this->get_many_related('Line_Item', $query_params);
795
+	}
796
+
797
+
798
+	/**
799
+	 * Gets all the line items which are taxes on the total
800
+	 *
801
+	 * @return EE_Line_Item[]
802
+	 * @throws EE_Error
803
+	 */
804
+	public function tax_items()
805
+	{
806
+		return $this->line_items(array(array('LIN_type' => EEM_Line_Item::type_tax)));
807
+	}
808
+
809
+
810
+	/**
811
+	 * Gets the total line item (which is a parent of all other related line items,
812
+	 * meaning it takes them all into account on its total)
813
+	 *
814
+	 * @param bool $create_if_not_found
815
+	 * @return \EE_Line_Item
816
+	 * @throws EE_Error
817
+	 */
818
+	public function total_line_item($create_if_not_found = true)
819
+	{
820
+		$item = $this->get_first_related('Line_Item', array(array('LIN_type' => EEM_Line_Item::type_total)));
821
+		if (! $item && $create_if_not_found) {
822
+			$item = EEH_Line_Item::create_total_line_item($this);
823
+		}
824
+		return $item;
825
+	}
826
+
827
+
828
+	/**
829
+	 * Returns the total amount of tax on this transaction
830
+	 * (assumes there's only one tax subtotal line item)
831
+	 *
832
+	 * @return float
833
+	 * @throws EE_Error
834
+	 */
835
+	public function tax_total()
836
+	{
837
+		$tax_line_item = $this->tax_total_line_item();
838
+		if ($tax_line_item) {
839
+			return (float) $tax_line_item->total();
840
+		}
841
+		return (float) 0;
842
+	}
843
+
844
+
845
+	/**
846
+	 * Gets the tax subtotal line item (assumes there's only one)
847
+	 *
848
+	 * @return EE_Line_Item
849
+	 * @throws EE_Error
850
+	 */
851
+	public function tax_total_line_item()
852
+	{
853
+		return EEH_Line_Item::get_taxes_subtotal($this->total_line_item());
854
+	}
855
+
856
+
857
+	/**
858
+	 * Gets the array of billing info for the gateway and for this transaction's primary registration's attendee.
859
+	 *
860
+	 * @return EE_Form_Section_Proper
861
+	 * @throws EE_Error
862
+	 */
863
+	public function billing_info()
864
+	{
865
+		$payment_method = $this->payment_method();
866
+		if (! $payment_method) {
867
+			EE_Error::add_error(
868
+				__(
869
+					'Could not find billing info for transaction because no gateway has been used for it yet',
870
+					'event_espresso'
871
+				),
872
+				__FILE__,
873
+				__FUNCTION__,
874
+				__LINE__
875
+			);
876
+			return null;
877
+		}
878
+		$primary_reg = $this->primary_registration();
879
+		if (! $primary_reg) {
880
+			EE_Error::add_error(
881
+				__(
882
+					'Cannot get billing info for gateway %s on transaction because no primary registration exists',
883
+					'event_espresso'
884
+				),
885
+				__FILE__,
886
+				__FUNCTION__,
887
+				__LINE__
888
+			);
889
+			return null;
890
+		}
891
+		$attendee = $primary_reg->attendee();
892
+		if (! $attendee) {
893
+			EE_Error::add_error(
894
+				__(
895
+					'Cannot get billing info for gateway %s on transaction because the primary registration has no attendee exists',
896
+					'event_espresso'
897
+				),
898
+				__FILE__,
899
+				__FUNCTION__,
900
+				__LINE__
901
+			);
902
+			return null;
903
+		}
904
+		return $attendee->billing_info_for_payment_method($payment_method);
905
+	}
906
+
907
+
908
+	/**
909
+	 * Gets PMD_ID
910
+	 *
911
+	 * @return int
912
+	 * @throws EE_Error
913
+	 */
914
+	public function payment_method_ID()
915
+	{
916
+		return $this->get('PMD_ID');
917
+	}
918
+
919
+
920
+	/**
921
+	 * Sets PMD_ID
922
+	 *
923
+	 * @param int $PMD_ID
924
+	 * @throws EE_Error
925
+	 */
926
+	public function set_payment_method_ID($PMD_ID)
927
+	{
928
+		$this->set('PMD_ID', $PMD_ID);
929
+	}
930
+
931
+
932
+	/**
933
+	 * Gets the last-used payment method on this transaction
934
+	 * (we COULD just use the last-made payment, but some payment methods, namely
935
+	 * offline ones, dont' create payments)
936
+	 *
937
+	 * @return EE_Payment_Method
938
+	 * @throws EE_Error
939
+	 */
940
+	public function payment_method()
941
+	{
942
+		$pm = $this->get_first_related('Payment_Method');
943
+		if ($pm instanceof EE_Payment_Method) {
944
+			return $pm;
945
+		}
946
+		$last_payment = $this->last_payment();
947
+		if ($last_payment instanceof EE_Payment && $last_payment->payment_method()) {
948
+			return $last_payment->payment_method();
949
+		}
950
+		return null;
951
+	}
952
+
953
+
954
+	/**
955
+	 * Gets the last payment made
956
+	 *
957
+	 * @return EE_Base_Class|EE_Payment
958
+	 * @throws EE_Error
959
+	 */
960
+	public function last_payment()
961
+	{
962
+		return $this->get_first_related('Payment', array('order_by' => array('PAY_ID' => 'desc')));
963
+	}
964
+
965
+
966
+	/**
967
+	 * Gets all the line items which are unrelated to tickets on this transaction
968
+	 *
969
+	 * @return EE_Line_Item[]
970
+	 * @throws EE_Error
971
+	 * @throws InvalidArgumentException
972
+	 * @throws InvalidDataTypeException
973
+	 * @throws InvalidInterfaceException
974
+	 */
975
+	public function non_ticket_line_items()
976
+	{
977
+		return EEM_Line_Item::instance()->get_all_non_ticket_line_items_for_transaction($this->ID());
978
+	}
979
+
980
+
981
+	/**
982
+	 * possibly toggles TXN status
983
+	 *
984
+	 * @param  boolean $update whether to save the TXN
985
+	 * @return bool whether the TXN was saved
986
+	 * @throws EE_Error
987
+	 * @throws RuntimeException
988
+	 */
989
+	public function update_status_based_on_total_paid($update = true)
990
+	{
991
+		// set transaction status based on comparison of TXN_paid vs TXN_total
992
+		if (EEH_Money::compare_floats($this->paid(), $this->total(), '>')) {
993
+			$new_txn_status = EEM_Transaction::overpaid_status_code;
994
+		} elseif (EEH_Money::compare_floats($this->paid(), $this->total())) {
995
+			$new_txn_status = EEM_Transaction::complete_status_code;
996
+		} elseif (EEH_Money::compare_floats($this->paid(), $this->total(), '<')) {
997
+			$new_txn_status = EEM_Transaction::incomplete_status_code;
998
+		} else {
999
+			throw new RuntimeException(
1000
+				__('The total paid calculation for this transaction is inaccurate.', 'event_espresso')
1001
+			);
1002
+		}
1003
+		if ($new_txn_status !== $this->status_ID()) {
1004
+			$this->set_status($new_txn_status);
1005
+			if ($update) {
1006
+				return $this->save() ? true : false;
1007
+			}
1008
+		}
1009
+		return false;
1010
+	}
1011
+
1012
+
1013
+	/**
1014
+	 * Updates the transaction's status and total_paid based on all the payments
1015
+	 * that apply to it
1016
+	 *
1017
+	 * @deprecated
1018
+	 * @return array|bool
1019
+	 * @throws EE_Error
1020
+	 * @throws InvalidArgumentException
1021
+	 * @throws ReflectionException
1022
+	 * @throws InvalidDataTypeException
1023
+	 * @throws InvalidInterfaceException
1024
+	 */
1025
+	public function update_based_on_payments()
1026
+	{
1027
+		EE_Error::doing_it_wrong(
1028
+			__CLASS__ . '::' . __FUNCTION__,
1029
+			sprintf(
1030
+				__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
1031
+				'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'
1032
+			),
1033
+			'4.6.0'
1034
+		);
1035
+		/** @type EE_Transaction_Processor $transaction_processor */
1036
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
1037
+		return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment($this);
1038
+	}
1039
+
1040
+
1041
+	/**
1042
+	 * @return string
1043
+	 */
1044
+	public function old_txn_status()
1045
+	{
1046
+		return $this->_old_txn_status;
1047
+	}
1048
+
1049
+
1050
+	/**
1051
+	 * @param string $old_txn_status
1052
+	 */
1053
+	public function set_old_txn_status($old_txn_status)
1054
+	{
1055
+		// only set the first time
1056
+		if ($this->_old_txn_status === null) {
1057
+			$this->_old_txn_status = $old_txn_status;
1058
+		}
1059
+	}
1060
+
1061
+
1062
+	/**
1063
+	 * reg_status_updated
1064
+	 *
1065
+	 * @return bool
1066
+	 * @throws EE_Error
1067
+	 */
1068
+	public function txn_status_updated()
1069
+	{
1070
+		return $this->status_ID() !== $this->_old_txn_status && $this->_old_txn_status !== null;
1071
+	}
1072
+
1073
+
1074
+	/**
1075
+	 * _reg_steps_completed
1076
+	 * if $check_all is TRUE, then returns TRUE if ALL reg steps have been marked as completed,
1077
+	 * if a $reg_step_slug is provided, then this step will be skipped when testing for completion
1078
+	 * if $check_all is FALSE and a $reg_step_slug is provided, then ONLY that reg step will be tested for completion
1079
+	 *
1080
+	 * @param string $reg_step_slug
1081
+	 * @param bool   $check_all
1082
+	 * @return bool|int
1083
+	 * @throws EE_Error
1084
+	 */
1085
+	private function _reg_steps_completed($reg_step_slug = '', $check_all = true)
1086
+	{
1087
+		$reg_steps = $this->reg_steps();
1088
+		if (! is_array($reg_steps) || empty($reg_steps)) {
1089
+			return false;
1090
+		}
1091
+		// loop thru reg steps array)
1092
+		foreach ($reg_steps as $slug => $reg_step_completed) {
1093
+			// if NOT checking ALL steps (only checking one step)
1094
+			if (! $check_all) {
1095
+				// and this is the one
1096
+				if ($slug === $reg_step_slug) {
1097
+					return $reg_step_completed;
1098
+				}
1099
+				// skip to next reg step in loop
1100
+				continue;
1101
+			}
1102
+			// $check_all must be true, else we would never have gotten to this point
1103
+			if ($slug === $reg_step_slug) {
1104
+				// if we reach this point, then we are testing either:
1105
+				// all_reg_steps_completed_except() or
1106
+				// all_reg_steps_completed_except_final_step(),
1107
+				// and since this is the reg step EXCEPTION being tested
1108
+				// we want to return true (yes true) if this reg step is NOT completed
1109
+				// ie: "is everything completed except the final step?"
1110
+				// "that is correct... the final step is not completed, but all others are."
1111
+				return $reg_step_completed !== true;
1112
+			}
1113
+			if ($reg_step_completed !== true) {
1114
+				// if any reg step is NOT completed, then ALL steps are not completed
1115
+				return false;
1116
+			}
1117
+		}
1118
+		return true;
1119
+	}
1120
+
1121
+
1122
+	/**
1123
+	 * all_reg_steps_completed
1124
+	 * returns:
1125
+	 *    true if ALL reg steps have been marked as completed
1126
+	 *        or false if any step is not completed
1127
+	 *
1128
+	 * @return bool
1129
+	 * @throws EE_Error
1130
+	 */
1131
+	public function all_reg_steps_completed()
1132
+	{
1133
+		return $this->_reg_steps_completed();
1134
+	}
1135
+
1136
+
1137
+	/**
1138
+	 * all_reg_steps_completed_except
1139
+	 * returns:
1140
+	 *        true if ALL reg steps, except a particular step that you wish to skip over, have been marked as completed
1141
+	 *        or false if any other step is not completed
1142
+	 *        or false if ALL steps are completed including the exception you are testing !!!
1143
+	 *
1144
+	 * @param string $exception
1145
+	 * @return bool
1146
+	 * @throws EE_Error
1147
+	 */
1148
+	public function all_reg_steps_completed_except($exception = '')
1149
+	{
1150
+		return $this->_reg_steps_completed($exception);
1151
+	}
1152
+
1153
+
1154
+	/**
1155
+	 * all_reg_steps_completed_except
1156
+	 * returns:
1157
+	 *        true if ALL reg steps, except the final step, have been marked as completed
1158
+	 *        or false if any step is not completed
1159
+	 *    or false if ALL steps are completed including the final step !!!
1160
+	 *
1161
+	 * @return bool
1162
+	 * @throws EE_Error
1163
+	 */
1164
+	public function all_reg_steps_completed_except_final_step()
1165
+	{
1166
+		return $this->_reg_steps_completed('finalize_registration');
1167
+	}
1168
+
1169
+
1170
+	/**
1171
+	 * reg_step_completed
1172
+	 * returns:
1173
+	 *    true if a specific reg step has been marked as completed
1174
+	 *    a Unix timestamp if it has been initialized but not yet completed,
1175
+	 *    or false if it has not yet been initialized
1176
+	 *
1177
+	 * @param string $reg_step_slug
1178
+	 * @return bool|int
1179
+	 * @throws EE_Error
1180
+	 */
1181
+	public function reg_step_completed($reg_step_slug)
1182
+	{
1183
+		return $this->_reg_steps_completed($reg_step_slug, false);
1184
+	}
1185
+
1186
+
1187
+	/**
1188
+	 * completed_final_reg_step
1189
+	 * returns:
1190
+	 *    true if the finalize_registration reg step has been marked as completed
1191
+	 *    a Unix timestamp if it has been initialized but not yet completed,
1192
+	 *    or false if it has not yet been initialized
1193
+	 *
1194
+	 * @return bool|int
1195
+	 * @throws EE_Error
1196
+	 */
1197
+	public function final_reg_step_completed()
1198
+	{
1199
+		return $this->_reg_steps_completed('finalize_registration', false);
1200
+	}
1201
+
1202
+
1203
+	/**
1204
+	 * set_reg_step_initiated
1205
+	 * given a valid TXN_reg_step, this sets it's value to a unix timestamp
1206
+	 *
1207
+	 * @param string $reg_step_slug
1208
+	 * @return boolean
1209
+	 * @throws EE_Error
1210
+	 */
1211
+	public function set_reg_step_initiated($reg_step_slug)
1212
+	{
1213
+		return $this->_set_reg_step_completed_status($reg_step_slug, time());
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * set_reg_step_completed
1219
+	 * given a valid TXN_reg_step, this sets the step as completed
1220
+	 *
1221
+	 * @param string $reg_step_slug
1222
+	 * @return boolean
1223
+	 * @throws EE_Error
1224
+	 */
1225
+	public function set_reg_step_completed($reg_step_slug)
1226
+	{
1227
+		return $this->_set_reg_step_completed_status($reg_step_slug, true);
1228
+	}
1229
+
1230
+
1231
+	/**
1232
+	 * set_reg_step_completed
1233
+	 * given a valid TXN_reg_step slug, this sets the step as NOT completed
1234
+	 *
1235
+	 * @param string $reg_step_slug
1236
+	 * @return boolean
1237
+	 * @throws EE_Error
1238
+	 */
1239
+	public function set_reg_step_not_completed($reg_step_slug)
1240
+	{
1241
+		return $this->_set_reg_step_completed_status($reg_step_slug, false);
1242
+	}
1243
+
1244
+
1245
+	/**
1246
+	 * set_reg_step_completed
1247
+	 * given a valid reg step slug, this sets the TXN_reg_step completed status which is either:
1248
+	 *
1249
+	 * @param  string      $reg_step_slug
1250
+	 * @param  boolean|int $status
1251
+	 * @return boolean
1252
+	 * @throws EE_Error
1253
+	 */
1254
+	private function _set_reg_step_completed_status($reg_step_slug, $status)
1255
+	{
1256
+		// validate status
1257
+		$status = is_bool($status) || is_int($status) ? $status : false;
1258
+		// get reg steps array
1259
+		$txn_reg_steps = $this->reg_steps();
1260
+		// if reg step does NOT exist
1261
+		if (! isset($txn_reg_steps[ $reg_step_slug ])) {
1262
+			return false;
1263
+		}
1264
+		// if  we're trying to complete a step that is already completed
1265
+		if ($txn_reg_steps[ $reg_step_slug ] === true) {
1266
+			return true;
1267
+		}
1268
+		// if  we're trying to complete a step that hasn't even started
1269
+		if ($status === true && $txn_reg_steps[ $reg_step_slug ] === false) {
1270
+			return false;
1271
+		}
1272
+		// if current status value matches the incoming value (no change)
1273
+		// type casting as int means values should collapse to either 0, 1, or a timestamp like 1234567890
1274
+		if ((int) $txn_reg_steps[ $reg_step_slug ] === (int) $status) {
1275
+			// this will happen in cases where multiple AJAX requests occur during the same step
1276
+			return true;
1277
+		}
1278
+		// if we're trying to set a start time, but it has already been set...
1279
+		if (is_numeric($status) && is_numeric($txn_reg_steps[ $reg_step_slug ])) {
1280
+			// skip the update below, but don't return FALSE so that errors won't be displayed
1281
+			return true;
1282
+		}
1283
+		// update completed status
1284
+		$txn_reg_steps[ $reg_step_slug ] = $status;
1285
+		$this->set_reg_steps($txn_reg_steps);
1286
+		$this->save();
1287
+		return true;
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * remove_reg_step
1293
+	 * given a valid TXN_reg_step slug, this will remove (unset)
1294
+	 * the reg step from the TXN reg step array
1295
+	 *
1296
+	 * @param string $reg_step_slug
1297
+	 * @return void
1298
+	 * @throws EE_Error
1299
+	 */
1300
+	public function remove_reg_step($reg_step_slug)
1301
+	{
1302
+		// get reg steps array
1303
+		$txn_reg_steps = $this->reg_steps();
1304
+		unset($txn_reg_steps[ $reg_step_slug ]);
1305
+		$this->set_reg_steps($txn_reg_steps);
1306
+	}
1307
+
1308
+
1309
+	/**
1310
+	 * toggle_failed_transaction_status
1311
+	 * upgrades a TXNs status from failed to abandoned,
1312
+	 * meaning that contact information has been captured for at least one registrant
1313
+	 *
1314
+	 * @param bool $save
1315
+	 * @return bool
1316
+	 * @throws EE_Error
1317
+	 */
1318
+	public function toggle_failed_transaction_status($save = true)
1319
+	{
1320
+		// if TXN status is still set as "failed"...
1321
+		if ($this->status_ID() === EEM_Transaction::failed_status_code) {
1322
+			$this->set_status(EEM_Transaction::abandoned_status_code);
1323
+			if ($save) {
1324
+				$this->save();
1325
+			}
1326
+			return true;
1327
+		}
1328
+		return false;
1329
+	}
1330
+
1331
+
1332
+	/**
1333
+	 * toggle_abandoned_transaction_status
1334
+	 * upgrades a TXNs status from failed or abandoned to incomplete
1335
+	 *
1336
+	 * @return bool
1337
+	 * @throws EE_Error
1338
+	 */
1339
+	public function toggle_abandoned_transaction_status()
1340
+	{
1341
+		// if TXN status has not been updated already due to a payment, and is still set as "failed" or "abandoned"...
1342
+		$txn_status = $this->status_ID();
1343
+		if ($txn_status === EEM_Transaction::failed_status_code
1344
+			|| $txn_status === EEM_Transaction::abandoned_status_code
1345
+		) {
1346
+			// if a contact record for the primary registrant has been created
1347
+			if ($this->primary_registration() instanceof EE_Registration
1348
+				&& $this->primary_registration()->attendee() instanceof EE_Attendee
1349
+			) {
1350
+				$this->set_status(EEM_Transaction::incomplete_status_code);
1351
+			} else {
1352
+				// no contact record? yer abandoned!
1353
+				$this->set_status(EEM_Transaction::abandoned_status_code);
1354
+			}
1355
+			return true;
1356
+		}
1357
+		return false;
1358
+	}
1359
+
1360
+
1361
+	/**
1362
+	 * checks if an Abandoned TXN has any related payments, and if so,
1363
+	 * updates the TXN status based on the amount paid
1364
+	 *
1365
+	 * @throws EE_Error
1366
+	 * @throws InvalidDataTypeException
1367
+	 * @throws InvalidInterfaceException
1368
+	 * @throws InvalidArgumentException
1369
+	 * @throws RuntimeException
1370
+	 */
1371
+	public function verify_abandoned_transaction_status()
1372
+	{
1373
+		if ($this->status_ID() !== EEM_Transaction::abandoned_status_code) {
1374
+			return;
1375
+		}
1376
+		$payments = $this->get_many_related('Payment');
1377
+		if (! empty($payments)) {
1378
+			foreach ($payments as $payment) {
1379
+				if ($payment instanceof EE_Payment) {
1380
+					// kk this TXN should NOT be abandoned
1381
+					$this->update_status_based_on_total_paid();
1382
+					if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1383
+						EE_Error::add_attention(
1384
+							sprintf(
1385
+								esc_html__(
1386
+									'The status for Transaction #%1$d has been updated from "Abandoned" to "%2$s", because at least one payment has been made towards it. If the payment appears in the "Payment Details" table below, you may need to edit its status and/or other details as well.',
1387
+									'event_espresso'
1388
+								),
1389
+								$this->ID(),
1390
+								$this->pretty_status()
1391
+							)
1392
+						);
1393
+					}
1394
+					// get final reg step status
1395
+					$finalized = $this->final_reg_step_completed();
1396
+					// if the 'finalize_registration' step has been initiated (has a timestamp)
1397
+					// but has not yet been fully completed (TRUE)
1398
+					if (is_int($finalized) && $finalized !== false && $finalized !== true) {
1399
+						$this->set_reg_step_completed('finalize_registration');
1400
+						$this->save();
1401
+					}
1402
+				}
1403
+			}
1404
+		}
1405
+	}
1406 1406
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Venue.class.php 1 patch
Indentation   +560 added lines, -560 removed lines patch added patch discarded remove patch
@@ -10,564 +10,564 @@
 block discarded – undo
10 10
 class EE_Venue extends EE_CPT_Base implements EEI_Address
11 11
 {
12 12
 
13
-    /**
14
-     *
15
-     * @param array  $props_n_values          incoming values
16
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
17
-     *                                        used.)
18
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
19
-     *                                        date_format and the second value is the time format
20
-     * @return EE_Attendee
21
-     */
22
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
23
-    {
24
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
25
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
26
-    }
27
-
28
-
29
-    /**
30
-     * @param array  $props_n_values  incoming values from the database
31
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
32
-     *                                the website will be used.
33
-     * @return EE_Attendee
34
-     */
35
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
36
-    {
37
-        return new self($props_n_values, true, $timezone);
38
-    }
39
-
40
-
41
-    /**
42
-     * Gets name
43
-     *
44
-     * @return string
45
-     */
46
-    public function name()
47
-    {
48
-        return $this->get('VNU_name');
49
-    }
50
-
51
-
52
-    /**
53
-     * Gets phone
54
-     *
55
-     * @return string
56
-     */
57
-    public function phone()
58
-    {
59
-        return $this->get('VNU_phone');
60
-    }
61
-
62
-
63
-    /**
64
-     * venue_url
65
-     *
66
-     * @return string
67
-     */
68
-    public function venue_url()
69
-    {
70
-        return $this->get('VNU_url');
71
-    }
72
-
73
-
74
-    /**
75
-     * Gets desc
76
-     *
77
-     * @return string
78
-     */
79
-    public function description()
80
-    {
81
-        return $this->get('VNU_desc');
82
-    }
83
-
84
-
85
-    /**
86
-     * Gets short description (AKA: the excerpt)
87
-     *
88
-     * @return string
89
-     */
90
-    public function excerpt()
91
-    {
92
-        return $this->get('VNU_short_desc');
93
-    }
94
-
95
-
96
-    /**
97
-     * Gets identifier
98
-     *
99
-     * @return string
100
-     */
101
-    public function identifier()
102
-    {
103
-        return $this->get('VNU_identifier');
104
-    }
105
-
106
-
107
-    /**
108
-     * Gets address
109
-     *
110
-     * @return string
111
-     */
112
-    public function address()
113
-    {
114
-        return $this->get('VNU_address');
115
-    }
116
-
117
-
118
-    /**
119
-     * Gets address2
120
-     *
121
-     * @return string
122
-     */
123
-    public function address2()
124
-    {
125
-        return $this->get('VNU_address2');
126
-    }
127
-
128
-
129
-    /**
130
-     * Gets city
131
-     *
132
-     * @return string
133
-     */
134
-    public function city()
135
-    {
136
-        return $this->get('VNU_city');
137
-    }
138
-
139
-    /**
140
-     * Gets state
141
-     *
142
-     * @return int
143
-     */
144
-    public function state_ID()
145
-    {
146
-        return $this->get('STA_ID');
147
-    }
148
-
149
-
150
-    /**
151
-     * @return string
152
-     */
153
-    public function state_abbrev()
154
-    {
155
-        return $this->state_obj() instanceof EE_State ? $this->state_obj()->abbrev() : '';
156
-    }
157
-
158
-
159
-    /**
160
-     * @return string
161
-     */
162
-    public function state_name()
163
-    {
164
-        return $this->state_obj() instanceof EE_State ? $this->state_obj()->name() : '';
165
-    }
166
-
167
-
168
-    /**
169
-     * Gets the state for this venue
170
-     *
171
-     * @return EE_State
172
-     */
173
-    public function state_obj()
174
-    {
175
-        return $this->get_first_related('State');
176
-    }
177
-
178
-
179
-    /**
180
-     * either displays the state abbreviation or the state name, as determined
181
-     * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
182
-     * defaults to abbreviation
183
-     *
184
-     * @return string
185
-     */
186
-    public function state()
187
-    {
188
-        if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
189
-            return $this->state_abbrev();
190
-        } else {
191
-            return $this->state_name();
192
-        }
193
-    }
194
-
195
-
196
-    /**
197
-     * country_ID
198
-     *
199
-     * @return string
200
-     */
201
-    public function country_ID()
202
-    {
203
-        return $this->get('CNT_ISO');
204
-    }
205
-
206
-
207
-    /**
208
-     * @return string
209
-     */
210
-    public function country_name()
211
-    {
212
-        return $this->country_obj() instanceof EE_Country ? $this->country_obj()->name() : '';
213
-    }
214
-
215
-
216
-    /**
217
-     * Gets the country of this venue
218
-     *
219
-     * @return EE_Country
220
-     */
221
-    public function country_obj()
222
-    {
223
-        return $this->get_first_related('Country');
224
-    }
225
-
226
-
227
-    /**
228
-     * either displays the country ISO2 code or the country name, as determined
229
-     * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
230
-     * defaults to abbreviation
231
-     *
232
-     * @return string
233
-     */
234
-    public function country()
235
-    {
236
-        if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
237
-            return $this->country_ID();
238
-        } else {
239
-            return $this->country_name();
240
-        }
241
-    }
242
-
243
-
244
-    /**
245
-     * Gets zip
246
-     *
247
-     * @return string
248
-     */
249
-    public function zip()
250
-    {
251
-        return $this->get('VNU_zip');
252
-    }
253
-
254
-
255
-    /**
256
-     * Gets capacity
257
-     *
258
-     * @return int
259
-     */
260
-    public function capacity()
261
-    {
262
-        return $this->get_pretty('VNU_capacity', 'symbol');
263
-    }
264
-
265
-
266
-    /**
267
-     * Gets created
268
-     *
269
-     * @return string
270
-     */
271
-    public function created()
272
-    {
273
-        return $this->get('VNU_created');
274
-    }
275
-
276
-
277
-    /**
278
-     * Gets modified
279
-     *
280
-     * @return string
281
-     */
282
-    public function modified()
283
-    {
284
-        return $this->get('VNU_modified');
285
-    }
286
-
287
-
288
-    /**
289
-     * Gets order
290
-     *
291
-     * @return int
292
-     */
293
-    public function order()
294
-    {
295
-        return $this->get('VNU_order');
296
-    }
297
-
298
-
299
-    /**
300
-     * Gets wp_user
301
-     *
302
-     * @return int
303
-     */
304
-    public function wp_user()
305
-    {
306
-        return $this->get('VNU_wp_user');
307
-    }
308
-
309
-
310
-    /**
311
-     * @return string
312
-     */
313
-    public function virtual_phone()
314
-    {
315
-        return $this->get('VNU_virtual_phone');
316
-    }
317
-
318
-
319
-    /**
320
-     * @return string
321
-     */
322
-    public function virtual_url()
323
-    {
324
-        return $this->get('VNU_virtual_url');
325
-    }
326
-
327
-
328
-    /**
329
-     * @return bool
330
-     */
331
-    public function enable_for_gmap()
332
-    {
333
-        return $this->get('VNU_enable_for_gmap');
334
-    }
335
-
336
-
337
-    /**
338
-     * @return string
339
-     */
340
-    public function google_map_link()
341
-    {
342
-        return $this->get('VNU_google_map_link');
343
-    }
344
-
345
-
346
-    /**
347
-     * Gets all events happening at this venue. Query parameters can be added to
348
-     * fetch a subset of those events.
349
-     *
350
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
351
-     * @param bool  $upcoming
352
-     * @return EE_Event[]
353
-     */
354
-    public function events($query_params = array(), $upcoming = false)
355
-    {
356
-        if ($upcoming) {
357
-            $query_params = array(
358
-                array(
359
-                    'status'                 => 'publish',
360
-                    'Datetime.DTT_EVT_start' => array(
361
-                        '>',
362
-                        EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
363
-                    ),
364
-                ),
365
-            );
366
-        }
367
-        return $this->get_many_related('Event', $query_params);
368
-    }
369
-
370
-
371
-    /**
372
-     * Sets address
373
-     */
374
-    public function set_address($address = '')
375
-    {
376
-        $this->set('VNU_address', $address);
377
-    }
378
-
379
-
380
-    /**
381
-     * @param string $address2
382
-     */
383
-    public function set_address2($address2 = '')
384
-    {
385
-        $this->set('VNU_address2', $address2);
386
-    }
387
-
388
-
389
-    /**
390
-     * @param string $city
391
-     */
392
-    public function set_city($city = '')
393
-    {
394
-        $this->set('VNU_city', $city);
395
-    }
396
-
397
-
398
-    /**
399
-     * @param int $state
400
-     */
401
-    public function set_state_ID($state = 0)
402
-    {
403
-        $this->set('STA_ID', $state);
404
-    }
405
-
406
-
407
-    /**
408
-     * Sets the state, given either a state id or state object
409
-     *
410
-     * @param EE_State /int $state_id_or_obj
411
-     * @return EE_State
412
-     */
413
-    public function set_state_obj($state_id_or_obj)
414
-    {
415
-        return $this->_add_relation_to($state_id_or_obj, 'State');
416
-    }
417
-
418
-
419
-    /**
420
-     * @param int $country_ID
421
-     */
422
-    public function set_country_ID($country_ID = 0)
423
-    {
424
-        $this->set('CNT_ISO', $country_ID);
425
-    }
426
-
427
-
428
-    /**
429
-     * Sets the country on the venue
430
-     *
431
-     * @param EE_Country /string $country_id_or_obj
432
-     * @return EE_Country
433
-     */
434
-    public function set_country_obj($country_id_or_obj)
435
-    {
436
-        return $this->_add_relation_to($country_id_or_obj, 'Country');
437
-    }
438
-
439
-
440
-    /**
441
-     * @param string $zip
442
-     */
443
-    public function set_zip($zip = '')
444
-    {
445
-        $this->set('VNU_zip', $zip);
446
-    }
447
-
448
-
449
-    /**
450
-     * @param int $capacity
451
-     */
452
-    public function set_capacity($capacity = 0)
453
-    {
454
-        $this->set('VNU_capacity', $capacity);
455
-    }
456
-
457
-
458
-    /**
459
-     * @param string $created
460
-     */
461
-    public function set_created($created = '')
462
-    {
463
-        $this->set('VNU_created', $created);
464
-    }
465
-
466
-
467
-    /**
468
-     * @param string $desc
469
-     */
470
-    public function set_description($desc = '')
471
-    {
472
-        $this->set('VNU_desc', $desc);
473
-    }
474
-
475
-
476
-    /**
477
-     * @param string $identifier
478
-     */
479
-    public function set_identifier($identifier = '')
480
-    {
481
-        $this->set('VNU_identifier', $identifier);
482
-    }
483
-
484
-
485
-    /**
486
-     * @param string $modified
487
-     */
488
-    public function set_modified($modified = '')
489
-    {
490
-        $this->set('VNU_modified', $modified);
491
-    }
492
-
493
-
494
-    /**
495
-     * @param string $name
496
-     */
497
-    public function set_name($name = '')
498
-    {
499
-        $this->set('VNU_name', $name);
500
-    }
501
-
502
-
503
-    /**
504
-     * @param int $order
505
-     */
506
-    public function set_order($order = 0)
507
-    {
508
-        $this->set('VNU_order', $order);
509
-    }
510
-
511
-
512
-    /**
513
-     * @param string $phone
514
-     */
515
-    public function set_phone($phone = '')
516
-    {
517
-        $this->set('VNU_phone', $phone);
518
-    }
519
-
520
-
521
-    /**
522
-     * @param int $wp_user
523
-     */
524
-    public function set_wp_user($wp_user = 1)
525
-    {
526
-        $this->set('VNU_wp_user', $wp_user);
527
-    }
528
-
529
-
530
-    /**
531
-     * @param string $url
532
-     */
533
-    public function set_venue_url($url = '')
534
-    {
535
-        $this->set('VNU_url', $url);
536
-    }
537
-
538
-
539
-    /**
540
-     * @param string $phone
541
-     */
542
-    public function set_virtual_phone($phone = '')
543
-    {
544
-        $this->set('VNU_virtual_phone', $phone);
545
-    }
546
-
547
-
548
-    /**
549
-     * @param string $url
550
-     */
551
-    public function set_virtual_url($url = '')
552
-    {
553
-        $this->set('VNU_virtual_url', $url);
554
-    }
555
-
556
-
557
-    /**
558
-     * @param string $enable
559
-     */
560
-    public function set_enable_for_gmap($enable = '')
561
-    {
562
-        $this->set('VNU_enable_for_gmap', $enable);
563
-    }
564
-
565
-
566
-    /**
567
-     * @param string $google_map_link
568
-     */
569
-    public function set_google_map_link($google_map_link = '')
570
-    {
571
-        $this->set('VNU_google_map_link', $google_map_link);
572
-    }
13
+	/**
14
+	 *
15
+	 * @param array  $props_n_values          incoming values
16
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
17
+	 *                                        used.)
18
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
19
+	 *                                        date_format and the second value is the time format
20
+	 * @return EE_Attendee
21
+	 */
22
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
23
+	{
24
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
25
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
26
+	}
27
+
28
+
29
+	/**
30
+	 * @param array  $props_n_values  incoming values from the database
31
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
32
+	 *                                the website will be used.
33
+	 * @return EE_Attendee
34
+	 */
35
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
36
+	{
37
+		return new self($props_n_values, true, $timezone);
38
+	}
39
+
40
+
41
+	/**
42
+	 * Gets name
43
+	 *
44
+	 * @return string
45
+	 */
46
+	public function name()
47
+	{
48
+		return $this->get('VNU_name');
49
+	}
50
+
51
+
52
+	/**
53
+	 * Gets phone
54
+	 *
55
+	 * @return string
56
+	 */
57
+	public function phone()
58
+	{
59
+		return $this->get('VNU_phone');
60
+	}
61
+
62
+
63
+	/**
64
+	 * venue_url
65
+	 *
66
+	 * @return string
67
+	 */
68
+	public function venue_url()
69
+	{
70
+		return $this->get('VNU_url');
71
+	}
72
+
73
+
74
+	/**
75
+	 * Gets desc
76
+	 *
77
+	 * @return string
78
+	 */
79
+	public function description()
80
+	{
81
+		return $this->get('VNU_desc');
82
+	}
83
+
84
+
85
+	/**
86
+	 * Gets short description (AKA: the excerpt)
87
+	 *
88
+	 * @return string
89
+	 */
90
+	public function excerpt()
91
+	{
92
+		return $this->get('VNU_short_desc');
93
+	}
94
+
95
+
96
+	/**
97
+	 * Gets identifier
98
+	 *
99
+	 * @return string
100
+	 */
101
+	public function identifier()
102
+	{
103
+		return $this->get('VNU_identifier');
104
+	}
105
+
106
+
107
+	/**
108
+	 * Gets address
109
+	 *
110
+	 * @return string
111
+	 */
112
+	public function address()
113
+	{
114
+		return $this->get('VNU_address');
115
+	}
116
+
117
+
118
+	/**
119
+	 * Gets address2
120
+	 *
121
+	 * @return string
122
+	 */
123
+	public function address2()
124
+	{
125
+		return $this->get('VNU_address2');
126
+	}
127
+
128
+
129
+	/**
130
+	 * Gets city
131
+	 *
132
+	 * @return string
133
+	 */
134
+	public function city()
135
+	{
136
+		return $this->get('VNU_city');
137
+	}
138
+
139
+	/**
140
+	 * Gets state
141
+	 *
142
+	 * @return int
143
+	 */
144
+	public function state_ID()
145
+	{
146
+		return $this->get('STA_ID');
147
+	}
148
+
149
+
150
+	/**
151
+	 * @return string
152
+	 */
153
+	public function state_abbrev()
154
+	{
155
+		return $this->state_obj() instanceof EE_State ? $this->state_obj()->abbrev() : '';
156
+	}
157
+
158
+
159
+	/**
160
+	 * @return string
161
+	 */
162
+	public function state_name()
163
+	{
164
+		return $this->state_obj() instanceof EE_State ? $this->state_obj()->name() : '';
165
+	}
166
+
167
+
168
+	/**
169
+	 * Gets the state for this venue
170
+	 *
171
+	 * @return EE_State
172
+	 */
173
+	public function state_obj()
174
+	{
175
+		return $this->get_first_related('State');
176
+	}
177
+
178
+
179
+	/**
180
+	 * either displays the state abbreviation or the state name, as determined
181
+	 * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
182
+	 * defaults to abbreviation
183
+	 *
184
+	 * @return string
185
+	 */
186
+	public function state()
187
+	{
188
+		if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
189
+			return $this->state_abbrev();
190
+		} else {
191
+			return $this->state_name();
192
+		}
193
+	}
194
+
195
+
196
+	/**
197
+	 * country_ID
198
+	 *
199
+	 * @return string
200
+	 */
201
+	public function country_ID()
202
+	{
203
+		return $this->get('CNT_ISO');
204
+	}
205
+
206
+
207
+	/**
208
+	 * @return string
209
+	 */
210
+	public function country_name()
211
+	{
212
+		return $this->country_obj() instanceof EE_Country ? $this->country_obj()->name() : '';
213
+	}
214
+
215
+
216
+	/**
217
+	 * Gets the country of this venue
218
+	 *
219
+	 * @return EE_Country
220
+	 */
221
+	public function country_obj()
222
+	{
223
+		return $this->get_first_related('Country');
224
+	}
225
+
226
+
227
+	/**
228
+	 * either displays the country ISO2 code or the country name, as determined
229
+	 * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
230
+	 * defaults to abbreviation
231
+	 *
232
+	 * @return string
233
+	 */
234
+	public function country()
235
+	{
236
+		if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
237
+			return $this->country_ID();
238
+		} else {
239
+			return $this->country_name();
240
+		}
241
+	}
242
+
243
+
244
+	/**
245
+	 * Gets zip
246
+	 *
247
+	 * @return string
248
+	 */
249
+	public function zip()
250
+	{
251
+		return $this->get('VNU_zip');
252
+	}
253
+
254
+
255
+	/**
256
+	 * Gets capacity
257
+	 *
258
+	 * @return int
259
+	 */
260
+	public function capacity()
261
+	{
262
+		return $this->get_pretty('VNU_capacity', 'symbol');
263
+	}
264
+
265
+
266
+	/**
267
+	 * Gets created
268
+	 *
269
+	 * @return string
270
+	 */
271
+	public function created()
272
+	{
273
+		return $this->get('VNU_created');
274
+	}
275
+
276
+
277
+	/**
278
+	 * Gets modified
279
+	 *
280
+	 * @return string
281
+	 */
282
+	public function modified()
283
+	{
284
+		return $this->get('VNU_modified');
285
+	}
286
+
287
+
288
+	/**
289
+	 * Gets order
290
+	 *
291
+	 * @return int
292
+	 */
293
+	public function order()
294
+	{
295
+		return $this->get('VNU_order');
296
+	}
297
+
298
+
299
+	/**
300
+	 * Gets wp_user
301
+	 *
302
+	 * @return int
303
+	 */
304
+	public function wp_user()
305
+	{
306
+		return $this->get('VNU_wp_user');
307
+	}
308
+
309
+
310
+	/**
311
+	 * @return string
312
+	 */
313
+	public function virtual_phone()
314
+	{
315
+		return $this->get('VNU_virtual_phone');
316
+	}
317
+
318
+
319
+	/**
320
+	 * @return string
321
+	 */
322
+	public function virtual_url()
323
+	{
324
+		return $this->get('VNU_virtual_url');
325
+	}
326
+
327
+
328
+	/**
329
+	 * @return bool
330
+	 */
331
+	public function enable_for_gmap()
332
+	{
333
+		return $this->get('VNU_enable_for_gmap');
334
+	}
335
+
336
+
337
+	/**
338
+	 * @return string
339
+	 */
340
+	public function google_map_link()
341
+	{
342
+		return $this->get('VNU_google_map_link');
343
+	}
344
+
345
+
346
+	/**
347
+	 * Gets all events happening at this venue. Query parameters can be added to
348
+	 * fetch a subset of those events.
349
+	 *
350
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
351
+	 * @param bool  $upcoming
352
+	 * @return EE_Event[]
353
+	 */
354
+	public function events($query_params = array(), $upcoming = false)
355
+	{
356
+		if ($upcoming) {
357
+			$query_params = array(
358
+				array(
359
+					'status'                 => 'publish',
360
+					'Datetime.DTT_EVT_start' => array(
361
+						'>',
362
+						EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
363
+					),
364
+				),
365
+			);
366
+		}
367
+		return $this->get_many_related('Event', $query_params);
368
+	}
369
+
370
+
371
+	/**
372
+	 * Sets address
373
+	 */
374
+	public function set_address($address = '')
375
+	{
376
+		$this->set('VNU_address', $address);
377
+	}
378
+
379
+
380
+	/**
381
+	 * @param string $address2
382
+	 */
383
+	public function set_address2($address2 = '')
384
+	{
385
+		$this->set('VNU_address2', $address2);
386
+	}
387
+
388
+
389
+	/**
390
+	 * @param string $city
391
+	 */
392
+	public function set_city($city = '')
393
+	{
394
+		$this->set('VNU_city', $city);
395
+	}
396
+
397
+
398
+	/**
399
+	 * @param int $state
400
+	 */
401
+	public function set_state_ID($state = 0)
402
+	{
403
+		$this->set('STA_ID', $state);
404
+	}
405
+
406
+
407
+	/**
408
+	 * Sets the state, given either a state id or state object
409
+	 *
410
+	 * @param EE_State /int $state_id_or_obj
411
+	 * @return EE_State
412
+	 */
413
+	public function set_state_obj($state_id_or_obj)
414
+	{
415
+		return $this->_add_relation_to($state_id_or_obj, 'State');
416
+	}
417
+
418
+
419
+	/**
420
+	 * @param int $country_ID
421
+	 */
422
+	public function set_country_ID($country_ID = 0)
423
+	{
424
+		$this->set('CNT_ISO', $country_ID);
425
+	}
426
+
427
+
428
+	/**
429
+	 * Sets the country on the venue
430
+	 *
431
+	 * @param EE_Country /string $country_id_or_obj
432
+	 * @return EE_Country
433
+	 */
434
+	public function set_country_obj($country_id_or_obj)
435
+	{
436
+		return $this->_add_relation_to($country_id_or_obj, 'Country');
437
+	}
438
+
439
+
440
+	/**
441
+	 * @param string $zip
442
+	 */
443
+	public function set_zip($zip = '')
444
+	{
445
+		$this->set('VNU_zip', $zip);
446
+	}
447
+
448
+
449
+	/**
450
+	 * @param int $capacity
451
+	 */
452
+	public function set_capacity($capacity = 0)
453
+	{
454
+		$this->set('VNU_capacity', $capacity);
455
+	}
456
+
457
+
458
+	/**
459
+	 * @param string $created
460
+	 */
461
+	public function set_created($created = '')
462
+	{
463
+		$this->set('VNU_created', $created);
464
+	}
465
+
466
+
467
+	/**
468
+	 * @param string $desc
469
+	 */
470
+	public function set_description($desc = '')
471
+	{
472
+		$this->set('VNU_desc', $desc);
473
+	}
474
+
475
+
476
+	/**
477
+	 * @param string $identifier
478
+	 */
479
+	public function set_identifier($identifier = '')
480
+	{
481
+		$this->set('VNU_identifier', $identifier);
482
+	}
483
+
484
+
485
+	/**
486
+	 * @param string $modified
487
+	 */
488
+	public function set_modified($modified = '')
489
+	{
490
+		$this->set('VNU_modified', $modified);
491
+	}
492
+
493
+
494
+	/**
495
+	 * @param string $name
496
+	 */
497
+	public function set_name($name = '')
498
+	{
499
+		$this->set('VNU_name', $name);
500
+	}
501
+
502
+
503
+	/**
504
+	 * @param int $order
505
+	 */
506
+	public function set_order($order = 0)
507
+	{
508
+		$this->set('VNU_order', $order);
509
+	}
510
+
511
+
512
+	/**
513
+	 * @param string $phone
514
+	 */
515
+	public function set_phone($phone = '')
516
+	{
517
+		$this->set('VNU_phone', $phone);
518
+	}
519
+
520
+
521
+	/**
522
+	 * @param int $wp_user
523
+	 */
524
+	public function set_wp_user($wp_user = 1)
525
+	{
526
+		$this->set('VNU_wp_user', $wp_user);
527
+	}
528
+
529
+
530
+	/**
531
+	 * @param string $url
532
+	 */
533
+	public function set_venue_url($url = '')
534
+	{
535
+		$this->set('VNU_url', $url);
536
+	}
537
+
538
+
539
+	/**
540
+	 * @param string $phone
541
+	 */
542
+	public function set_virtual_phone($phone = '')
543
+	{
544
+		$this->set('VNU_virtual_phone', $phone);
545
+	}
546
+
547
+
548
+	/**
549
+	 * @param string $url
550
+	 */
551
+	public function set_virtual_url($url = '')
552
+	{
553
+		$this->set('VNU_virtual_url', $url);
554
+	}
555
+
556
+
557
+	/**
558
+	 * @param string $enable
559
+	 */
560
+	public function set_enable_for_gmap($enable = '')
561
+	{
562
+		$this->set('VNU_enable_for_gmap', $enable);
563
+	}
564
+
565
+
566
+	/**
567
+	 * @param string $google_map_link
568
+	 */
569
+	public function set_google_map_link($google_map_link = '')
570
+	{
571
+		$this->set('VNU_google_map_link', $google_map_link);
572
+	}
573 573
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Ticket.class.php 1 patch
Indentation   +1460 added lines, -1460 removed lines patch added patch discarded remove patch
@@ -12,1464 +12,1464 @@
 block discarded – undo
12 12
 class EE_Ticket extends EE_Soft_Delete_Base_Class implements EEI_Line_Item_Object, EEI_Event_Relation, EEI_Has_Icon
13 13
 {
14 14
 
15
-    /**
16
-     * The following constants are used by the ticket_status() method to indicate whether a ticket is on sale or not.
17
-     */
18
-    const sold_out = 'TKS';
19
-
20
-    /**
21
-     *
22
-     */
23
-    const expired = 'TKE';
24
-
25
-    /**
26
-     *
27
-     */
28
-    const archived = 'TKA';
29
-
30
-    /**
31
-     *
32
-     */
33
-    const pending = 'TKP';
34
-
35
-    /**
36
-     *
37
-     */
38
-    const onsale = 'TKO';
39
-
40
-    /**
41
-     * extra meta key for tracking ticket reservations
42
-     *
43
-     * @type string
44
-     */
45
-    const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
46
-
47
-    /**
48
-     * cached result from method of the same name
49
-     *
50
-     * @var float $_ticket_total_with_taxes
51
-     */
52
-    private $_ticket_total_with_taxes;
53
-
54
-
55
-    /**
56
-     * @param array  $props_n_values          incoming values
57
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
58
-     *                                        used.)
59
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
60
-     *                                        date_format and the second value is the time format
61
-     * @return EE_Ticket
62
-     * @throws \EE_Error
63
-     */
64
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
-    {
66
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
67
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
68
-    }
69
-
70
-
71
-    /**
72
-     * @param array  $props_n_values  incoming values from the database
73
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
74
-     *                                the website will be used.
75
-     * @return EE_Ticket
76
-     * @throws \EE_Error
77
-     */
78
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
79
-    {
80
-        return new self($props_n_values, true, $timezone);
81
-    }
82
-
83
-
84
-    /**
85
-     * @return bool
86
-     * @throws \EE_Error
87
-     */
88
-    public function parent()
89
-    {
90
-        return $this->get('TKT_parent');
91
-    }
92
-
93
-
94
-    /**
95
-     * return if a ticket has quantities available for purchase
96
-     *
97
-     * @param  int $DTT_ID the primary key for a particular datetime
98
-     * @return boolean
99
-     * @throws \EE_Error
100
-     */
101
-    public function available($DTT_ID = 0)
102
-    {
103
-        // are we checking availability for a particular datetime ?
104
-        if ($DTT_ID) {
105
-            // get that datetime object
106
-            $datetime = $this->get_first_related('Datetime', array(array('DTT_ID' => $DTT_ID)));
107
-            // if  ticket sales for this datetime have exceeded the reg limit...
108
-            if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
109
-                return false;
110
-            }
111
-        }
112
-        // datetime is still open for registration, but is this ticket sold out ?
113
-        return $this->qty() < 1 || $this->qty() > $this->sold() ? true : false;
114
-    }
115
-
116
-
117
-    /**
118
-     * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
119
-     *
120
-     * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
121
-     *                               relevant status const
122
-     * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
123
-     *               further processing
124
-     * @return mixed status int if the display string isn't requested
125
-     * @throws \EE_Error
126
-     */
127
-    public function ticket_status($display = false, $remaining = null)
128
-    {
129
-        $remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
130
-        if (! $remaining) {
131
-            return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
132
-        }
133
-        if ($this->get('TKT_deleted')) {
134
-            return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
135
-        }
136
-        if ($this->is_expired()) {
137
-            return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
138
-        }
139
-        if ($this->is_pending()) {
140
-            return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
141
-        }
142
-        if ($this->is_on_sale()) {
143
-            return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
144
-        }
145
-        return '';
146
-    }
147
-
148
-
149
-    /**
150
-     * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
151
-     * considering ALL the factors used for figuring that out.
152
-     *
153
-     * @access public
154
-     * @param  int $DTT_ID if an int above 0 is included here then we get a specific dtt.
155
-     * @return boolean         true = tickets remaining, false not.
156
-     * @throws \EE_Error
157
-     */
158
-    public function is_remaining($DTT_ID = 0)
159
-    {
160
-        $num_remaining = $this->remaining($DTT_ID);
161
-        if ($num_remaining === 0) {
162
-            return false;
163
-        }
164
-        if ($num_remaining > 0 && $num_remaining < $this->min()) {
165
-            return false;
166
-        }
167
-        return true;
168
-    }
169
-
170
-
171
-    /**
172
-     * return the total number of tickets available for purchase
173
-     *
174
-     * @param  int $DTT_ID the primary key for a particular datetime.
175
-     *                     set to 0 for all related datetimes
176
-     * @return int
177
-     * @throws \EE_Error
178
-     */
179
-    public function remaining($DTT_ID = 0)
180
-    {
181
-        return $this->real_quantity_on_ticket('saleable', $DTT_ID);
182
-    }
183
-
184
-
185
-    /**
186
-     * Gets min
187
-     *
188
-     * @return int
189
-     * @throws \EE_Error
190
-     */
191
-    public function min()
192
-    {
193
-        return $this->get('TKT_min');
194
-    }
195
-
196
-
197
-    /**
198
-     * return if a ticket is no longer available cause its available dates have expired.
199
-     *
200
-     * @return boolean
201
-     * @throws \EE_Error
202
-     */
203
-    public function is_expired()
204
-    {
205
-        return ($this->get_raw('TKT_end_date') < time());
206
-    }
207
-
208
-
209
-    /**
210
-     * Return if a ticket is yet to go on sale or not
211
-     *
212
-     * @return boolean
213
-     * @throws \EE_Error
214
-     */
215
-    public function is_pending()
216
-    {
217
-        return ($this->get_raw('TKT_start_date') > time());
218
-    }
219
-
220
-
221
-    /**
222
-     * Return if a ticket is on sale or not
223
-     *
224
-     * @return boolean
225
-     * @throws \EE_Error
226
-     */
227
-    public function is_on_sale()
228
-    {
229
-        return ($this->get_raw('TKT_start_date') < time() && $this->get_raw('TKT_end_date') > time());
230
-    }
231
-
232
-
233
-    /**
234
-     * This returns the chronologically last datetime that this ticket is associated with
235
-     *
236
-     * @param string $dt_frmt
237
-     * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
238
-     *                            the end date ie: Jan 01 "to" Dec 31
239
-     * @return string
240
-     * @throws \EE_Error
241
-     */
242
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
243
-    {
244
-        $first_date = $this->first_datetime() instanceof EE_Datetime ? $this->first_datetime()->start_date($dt_frmt)
245
-            : '';
246
-        $last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->end_date($dt_frmt) : '';
247
-
248
-        return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
249
-    }
250
-
251
-
252
-    /**
253
-     * This returns the chronologically first datetime that this ticket is associated with
254
-     *
255
-     * @return EE_Datetime
256
-     * @throws \EE_Error
257
-     */
258
-    public function first_datetime()
259
-    {
260
-        $datetimes = $this->datetimes(array('limit' => 1));
261
-        return reset($datetimes);
262
-    }
263
-
264
-
265
-    /**
266
-     * Gets all the datetimes this ticket can be used for attending.
267
-     * Unless otherwise specified, orders datetimes by start date.
268
-     *
269
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
270
-     * @return EE_Datetime[]|EE_Base_Class[]
271
-     * @throws \EE_Error
272
-     */
273
-    public function datetimes($query_params = array())
274
-    {
275
-        if (! isset($query_params['order_by'])) {
276
-            $query_params['order_by']['DTT_order'] = 'ASC';
277
-        }
278
-        return $this->get_many_related('Datetime', $query_params);
279
-    }
280
-
281
-
282
-    /**
283
-     * This returns the chronologically last datetime that this ticket is associated with
284
-     *
285
-     * @return EE_Datetime
286
-     * @throws \EE_Error
287
-     */
288
-    public function last_datetime()
289
-    {
290
-        $datetimes = $this->datetimes(array('limit' => 1, 'order_by' => array('DTT_EVT_start' => 'DESC')));
291
-        return end($datetimes);
292
-    }
293
-
294
-
295
-    /**
296
-     * This returns the total tickets sold depending on the given parameters.
297
-     *
298
-     * @param  string $what   Can be one of two options: 'ticket', 'datetime'.
299
-     *                        'ticket' = total ticket sales for all datetimes this ticket is related to
300
-     *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
301
-     *                        'datetime' = total ticket sales in the datetime_ticket table.
302
-     *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
303
-     *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
304
-     * @param  int    $dtt_id [optional] include the dtt_id with $what = 'datetime'.
305
-     * @return mixed (array|int)          how many tickets have sold
306
-     * @throws \EE_Error
307
-     */
308
-    public function tickets_sold($what = 'ticket', $dtt_id = null)
309
-    {
310
-        $total = 0;
311
-        $tickets_sold = $this->_all_tickets_sold();
312
-        switch ($what) {
313
-            case 'ticket':
314
-                return $tickets_sold['ticket'];
315
-                break;
316
-            case 'datetime':
317
-                if (empty($tickets_sold['datetime'])) {
318
-                    return $total;
319
-                }
320
-                if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
321
-                    EE_Error::add_error(
322
-                        __(
323
-                            'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
324
-                            'event_espresso'
325
-                        ),
326
-                        __FILE__,
327
-                        __FUNCTION__,
328
-                        __LINE__
329
-                    );
330
-                    return $total;
331
-                }
332
-                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
333
-                break;
334
-            default:
335
-                return $total;
336
-        }
337
-    }
338
-
339
-
340
-    /**
341
-     * This returns an array indexed by datetime_id for tickets sold with this ticket.
342
-     *
343
-     * @return EE_Ticket[]
344
-     * @throws \EE_Error
345
-     */
346
-    protected function _all_tickets_sold()
347
-    {
348
-        $datetimes = $this->get_many_related('Datetime');
349
-        $tickets_sold = array();
350
-        if (! empty($datetimes)) {
351
-            foreach ($datetimes as $datetime) {
352
-                $tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
353
-            }
354
-        }
355
-        // Tickets sold
356
-        $tickets_sold['ticket'] = $this->sold();
357
-        return $tickets_sold;
358
-    }
359
-
360
-
361
-    /**
362
-     * This returns the base price object for the ticket.
363
-     *
364
-     * @param  bool $return_array whether to return as an array indexed by price id or just the object.
365
-     * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
366
-     * @throws \EE_Error
367
-     */
368
-    public function base_price($return_array = false)
369
-    {
370
-        $_where = array('Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price);
371
-        return $return_array
372
-            ? $this->get_many_related('Price', array($_where))
373
-            : $this->get_first_related('Price', array($_where));
374
-    }
375
-
376
-
377
-    /**
378
-     * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
379
-     *
380
-     * @access public
381
-     * @return EE_Price[]
382
-     * @throws \EE_Error
383
-     */
384
-    public function price_modifiers()
385
-    {
386
-        $query_params = array(
387
-            0 => array(
388
-                'Price_Type.PBT_ID' => array(
389
-                    'NOT IN',
390
-                    array(EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax),
391
-                ),
392
-            ),
393
-        );
394
-        return $this->prices($query_params);
395
-    }
396
-
397
-
398
-    /**
399
-     * Gets all the prices that combine to form the final price of this ticket
400
-     *
401
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
402
-     * @return EE_Price[]|EE_Base_Class[]
403
-     * @throws \EE_Error
404
-     */
405
-    public function prices($query_params = array())
406
-    {
407
-        return $this->get_many_related('Price', $query_params);
408
-    }
409
-
410
-
411
-    /**
412
-     * Gets all the ticket applicabilities (ie, relations between datetimes and tickets)
413
-     *
414
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
415
-     * @return EE_Datetime_Ticket|EE_Base_Class[]
416
-     * @throws \EE_Error
417
-     */
418
-    public function datetime_tickets($query_params = array())
419
-    {
420
-        return $this->get_many_related('Datetime_Ticket', $query_params);
421
-    }
422
-
423
-
424
-    /**
425
-     * Gets all the datetimes from the db ordered by DTT_order
426
-     *
427
-     * @param boolean $show_expired
428
-     * @param boolean $show_deleted
429
-     * @return EE_Datetime[]
430
-     * @throws \EE_Error
431
-     */
432
-    public function datetimes_ordered($show_expired = true, $show_deleted = false)
433
-    {
434
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
435
-            $this->ID(),
436
-            $show_expired,
437
-            $show_deleted
438
-        );
439
-    }
440
-
441
-
442
-    /**
443
-     * Gets ID
444
-     *
445
-     * @return string
446
-     * @throws \EE_Error
447
-     */
448
-    public function ID()
449
-    {
450
-        return $this->get('TKT_ID');
451
-    }
452
-
453
-
454
-    /**
455
-     * get the author of the ticket.
456
-     *
457
-     * @since 4.5.0
458
-     * @return int
459
-     * @throws \EE_Error
460
-     */
461
-    public function wp_user()
462
-    {
463
-        return $this->get('TKT_wp_user');
464
-    }
465
-
466
-
467
-    /**
468
-     * Gets the template for the ticket
469
-     *
470
-     * @return EE_Ticket_Template|EE_Base_Class
471
-     * @throws \EE_Error
472
-     */
473
-    public function template()
474
-    {
475
-        return $this->get_first_related('Ticket_Template');
476
-    }
477
-
478
-
479
-    /**
480
-     * Simply returns an array of EE_Price objects that are taxes.
481
-     *
482
-     * @return EE_Price[]
483
-     * @throws \EE_Error
484
-     */
485
-    public function get_ticket_taxes_for_admin()
486
-    {
487
-        return EE_Taxes::get_taxes_for_admin();
488
-    }
489
-
490
-
491
-    /**
492
-     * @return float
493
-     * @throws \EE_Error
494
-     */
495
-    public function ticket_price()
496
-    {
497
-        return $this->get('TKT_price');
498
-    }
499
-
500
-
501
-    /**
502
-     * @return mixed
503
-     * @throws \EE_Error
504
-     */
505
-    public function pretty_price()
506
-    {
507
-        return $this->get_pretty('TKT_price');
508
-    }
509
-
510
-
511
-    /**
512
-     * @return bool
513
-     * @throws \EE_Error
514
-     */
515
-    public function is_free()
516
-    {
517
-        return $this->get_ticket_total_with_taxes() === (float) 0;
518
-    }
519
-
520
-
521
-    /**
522
-     * get_ticket_total_with_taxes
523
-     *
524
-     * @param bool $no_cache
525
-     * @return float
526
-     * @throws \EE_Error
527
-     */
528
-    public function get_ticket_total_with_taxes($no_cache = false)
529
-    {
530
-        if ($this->_ticket_total_with_taxes === null || $no_cache) {
531
-            $this->_ticket_total_with_taxes = $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin();
532
-        }
533
-        return (float) $this->_ticket_total_with_taxes;
534
-    }
535
-
536
-
537
-    public function ensure_TKT_Price_correct()
538
-    {
539
-        $this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
540
-        $this->save();
541
-    }
542
-
543
-
544
-    /**
545
-     * @return float
546
-     * @throws \EE_Error
547
-     */
548
-    public function get_ticket_subtotal()
549
-    {
550
-        return EE_Taxes::get_subtotal_for_admin($this);
551
-    }
552
-
553
-
554
-    /**
555
-     * Returns the total taxes applied to this ticket
556
-     *
557
-     * @return float
558
-     * @throws \EE_Error
559
-     */
560
-    public function get_ticket_taxes_total_for_admin()
561
-    {
562
-        return EE_Taxes::get_total_taxes_for_admin($this);
563
-    }
564
-
565
-
566
-    /**
567
-     * Sets name
568
-     *
569
-     * @param string $name
570
-     * @throws \EE_Error
571
-     */
572
-    public function set_name($name)
573
-    {
574
-        $this->set('TKT_name', $name);
575
-    }
576
-
577
-
578
-    /**
579
-     * Gets description
580
-     *
581
-     * @return string
582
-     * @throws \EE_Error
583
-     */
584
-    public function description()
585
-    {
586
-        return $this->get('TKT_description');
587
-    }
588
-
589
-
590
-    /**
591
-     * Sets description
592
-     *
593
-     * @param string $description
594
-     * @throws \EE_Error
595
-     */
596
-    public function set_description($description)
597
-    {
598
-        $this->set('TKT_description', $description);
599
-    }
600
-
601
-
602
-    /**
603
-     * Gets start_date
604
-     *
605
-     * @param string $dt_frmt
606
-     * @param string $tm_frmt
607
-     * @return string
608
-     * @throws \EE_Error
609
-     */
610
-    public function start_date($dt_frmt = '', $tm_frmt = '')
611
-    {
612
-        return $this->_get_datetime('TKT_start_date', $dt_frmt, $tm_frmt);
613
-    }
614
-
615
-
616
-    /**
617
-     * Sets start_date
618
-     *
619
-     * @param string $start_date
620
-     * @return void
621
-     * @throws \EE_Error
622
-     */
623
-    public function set_start_date($start_date)
624
-    {
625
-        $this->_set_date_time('B', $start_date, 'TKT_start_date');
626
-    }
627
-
628
-
629
-    /**
630
-     * Gets end_date
631
-     *
632
-     * @param string $dt_frmt
633
-     * @param string $tm_frmt
634
-     * @return string
635
-     * @throws \EE_Error
636
-     */
637
-    public function end_date($dt_frmt = '', $tm_frmt = '')
638
-    {
639
-        return $this->_get_datetime('TKT_end_date', $dt_frmt, $tm_frmt);
640
-    }
641
-
642
-
643
-    /**
644
-     * Sets end_date
645
-     *
646
-     * @param string $end_date
647
-     * @return void
648
-     * @throws \EE_Error
649
-     */
650
-    public function set_end_date($end_date)
651
-    {
652
-        $this->_set_date_time('B', $end_date, 'TKT_end_date');
653
-    }
654
-
655
-
656
-    /**
657
-     * Sets sell until time
658
-     *
659
-     * @since 4.5.0
660
-     * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
661
-     * @throws \EE_Error
662
-     */
663
-    public function set_end_time($time)
664
-    {
665
-        $this->_set_time_for($time, 'TKT_end_date');
666
-    }
667
-
668
-
669
-    /**
670
-     * Sets min
671
-     *
672
-     * @param int $min
673
-     * @return void
674
-     * @throws \EE_Error
675
-     */
676
-    public function set_min($min)
677
-    {
678
-        $this->set('TKT_min', $min);
679
-    }
680
-
681
-
682
-    /**
683
-     * Gets max
684
-     *
685
-     * @return int
686
-     * @throws \EE_Error
687
-     */
688
-    public function max()
689
-    {
690
-        return $this->get('TKT_max');
691
-    }
692
-
693
-
694
-    /**
695
-     * Sets max
696
-     *
697
-     * @param int $max
698
-     * @return void
699
-     * @throws \EE_Error
700
-     */
701
-    public function set_max($max)
702
-    {
703
-        $this->set('TKT_max', $max);
704
-    }
705
-
706
-
707
-    /**
708
-     * Sets price
709
-     *
710
-     * @param float $price
711
-     * @return void
712
-     * @throws \EE_Error
713
-     */
714
-    public function set_price($price)
715
-    {
716
-        $this->set('TKT_price', $price);
717
-    }
718
-
719
-
720
-    /**
721
-     * Gets sold
722
-     *
723
-     * @return int
724
-     * @throws \EE_Error
725
-     */
726
-    public function sold()
727
-    {
728
-        return $this->get_raw('TKT_sold');
729
-    }
730
-
731
-
732
-    /**
733
-     * Sets sold
734
-     *
735
-     * @param int $sold
736
-     * @return void
737
-     * @throws \EE_Error
738
-     */
739
-    public function set_sold($sold)
740
-    {
741
-        // sold can not go below zero
742
-        $sold = max(0, $sold);
743
-        $this->set('TKT_sold', $sold);
744
-    }
745
-
746
-
747
-    /**
748
-     * increments sold by amount passed by $qty
749
-     *
750
-     * @param int $qty
751
-     * @return void
752
-     * @throws \EE_Error
753
-     */
754
-    public function increase_sold($qty = 1)
755
-    {
756
-        $sold = $this->sold() + $qty;
757
-        // remove ticket reservation, but don't adjust datetime reservations,  because that will happen
758
-        // via \EE_Datetime::increase_sold() when \EE_Ticket::_increase_sold_for_datetimes() is called
759
-        $this->decrease_reserved($qty, false, "TKT: {$this->ID()} (ln:" . __LINE__ . ')');
760
-        $this->_increase_sold_for_datetimes($qty);
761
-        $this->set_sold($sold);
762
-        do_action(
763
-            'AHEE__EE_Ticket__increase_sold',
764
-            $this,
765
-            $qty,
766
-            $sold
767
-        );
768
-    }
769
-
770
-
771
-    /**
772
-     * Increases sold on related datetimes
773
-     *
774
-     * @param int $qty
775
-     * @return void
776
-     * @throws \EE_Error
777
-     */
778
-    protected function _increase_sold_for_datetimes($qty = 1)
779
-    {
780
-        $datetimes = $this->datetimes();
781
-        if (is_array($datetimes)) {
782
-            foreach ($datetimes as $datetime) {
783
-                if ($datetime instanceof EE_Datetime) {
784
-                    $datetime->increase_sold($qty);
785
-                    $datetime->save();
786
-                }
787
-            }
788
-        }
789
-    }
790
-
791
-
792
-    /**
793
-     * decrements (subtracts) sold by amount passed by $qty
794
-     *
795
-     * @param int $qty
796
-     * @return void
797
-     * @throws \EE_Error
798
-     */
799
-    public function decrease_sold($qty = 1)
800
-    {
801
-        $sold = $this->sold() - $qty;
802
-        $this->_decrease_sold_for_datetimes($qty);
803
-        $this->set_sold($sold);
804
-        do_action(
805
-            'AHEE__EE_Ticket__decrease_sold',
806
-            $this,
807
-            $qty,
808
-            $sold
809
-        );
810
-    }
811
-
812
-
813
-    /**
814
-     * Decreases sold on related datetimes
815
-     *
816
-     * @param int $qty
817
-     * @return void
818
-     * @throws \EE_Error
819
-     */
820
-    protected function _decrease_sold_for_datetimes($qty = 1)
821
-    {
822
-        $datetimes = $this->datetimes();
823
-        if (is_array($datetimes)) {
824
-            foreach ($datetimes as $datetime) {
825
-                if ($datetime instanceof EE_Datetime) {
826
-                    $datetime->decrease_sold($qty);
827
-                    $datetime->save();
828
-                }
829
-            }
830
-        }
831
-    }
832
-
833
-
834
-    /**
835
-     * Gets qty of reserved tickets
836
-     *
837
-     * @return int
838
-     * @throws \EE_Error
839
-     */
840
-    public function reserved()
841
-    {
842
-        return $this->get_raw('TKT_reserved');
843
-    }
844
-
845
-
846
-    /**
847
-     * Sets reserved
848
-     *
849
-     * @param int $reserved
850
-     * @return void
851
-     * @throws \EE_Error
852
-     */
853
-    public function set_reserved($reserved)
854
-    {
855
-        // reserved can not go below zero
856
-        $reserved = max(0, (int) $reserved);
857
-        $this->set('TKT_reserved', $reserved);
858
-    }
859
-
860
-
861
-    /**
862
-     * increments reserved by amount passed by $qty
863
-     *
864
-     * @param int    $qty
865
-     * @param string $source
866
-     * @return void
867
-     * @throws EE_Error
868
-     * @throws InvalidArgumentException
869
-     * @throws ReflectionException
870
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
871
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
872
-     */
873
-    public function increase_reserved($qty = 1, $source = 'unknown')
874
-    {
875
-        $qty = absint($qty);
876
-        $reserved = $this->reserved() + $qty;
877
-        if ($reserved
878
-            && $this->add_extra_meta(
879
-                EE_Ticket::META_KEY_TICKET_RESERVATIONS,
880
-                "{$qty} from {$source}"
881
-            )
882
-        ) {
883
-            $this->_increase_reserved_for_datetimes($qty);
884
-            $this->set_reserved($reserved);
885
-            do_action(
886
-                'AHEE__EE_Ticket__increase_reserved',
887
-                $this,
888
-                $qty,
889
-                $reserved
890
-            );
891
-        }
892
-    }
893
-
894
-
895
-    /**
896
-     * Increases sold on related datetimes
897
-     *
898
-     * @param int $qty
899
-     * @return void
900
-     * @throws \EE_Error
901
-     */
902
-    protected function _increase_reserved_for_datetimes($qty = 1)
903
-    {
904
-        $datetimes = $this->datetimes();
905
-        if (is_array($datetimes)) {
906
-            foreach ($datetimes as $datetime) {
907
-                if ($datetime instanceof EE_Datetime) {
908
-                    $datetime->increase_reserved($qty);
909
-                    $datetime->save();
910
-                }
911
-            }
912
-        }
913
-    }
914
-
915
-
916
-    /**
917
-     * decrements (subtracts) reserved by amount passed by $qty
918
-     *
919
-     * @param int    $qty
920
-     * @param bool   $adjust_datetimes
921
-     * @param string $source
922
-     * @return void
923
-     * @throws EE_Error
924
-     * @throws InvalidArgumentException
925
-     * @throws ReflectionException
926
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
927
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
928
-     */
929
-    public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
930
-    {
931
-        $reserved = $this->reserved() - absint($qty);
932
-        if ($this->add_extra_meta(
933
-            EE_Ticket::META_KEY_TICKET_RESERVATIONS,
934
-            "-{$qty} from {$source}"
935
-        )) {
936
-            if ($adjust_datetimes) {
937
-                $this->_decrease_reserved_for_datetimes($qty);
938
-            }
939
-            $this->set_reserved($reserved);
940
-            do_action(
941
-                'AHEE__EE_Ticket__decrease_reserved',
942
-                $this,
943
-                $qty,
944
-                $reserved
945
-            );
946
-        }
947
-    }
948
-
949
-
950
-    /**
951
-     * Increases sold on related datetimes
952
-     *
953
-     * @param int $qty
954
-     * @return void
955
-     * @throws \EE_Error
956
-     */
957
-    protected function _decrease_reserved_for_datetimes($qty = 1)
958
-    {
959
-        $datetimes = $this->datetimes();
960
-        if (is_array($datetimes)) {
961
-            foreach ($datetimes as $datetime) {
962
-                if ($datetime instanceof EE_Datetime) {
963
-                    $datetime->decrease_reserved($qty);
964
-                    $datetime->save();
965
-                }
966
-            }
967
-        }
968
-    }
969
-
970
-
971
-    /**
972
-     * Gets ticket quantity
973
-     *
974
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
975
-     *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
976
-     *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
977
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
978
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
979
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
980
-     * @return int
981
-     * @throws \EE_Error
982
-     */
983
-    public function qty($context = '')
984
-    {
985
-        switch ($context) {
986
-            case 'reg_limit':
987
-                return $this->real_quantity_on_ticket();
988
-            case 'saleable':
989
-                return $this->real_quantity_on_ticket('saleable');
990
-            default:
991
-                return $this->get_raw('TKT_qty');
992
-        }
993
-    }
994
-
995
-
996
-    /**
997
-     * Gets ticket quantity
998
-     *
999
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1000
-     *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1001
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1002
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1003
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1004
-     * @param  int   $DTT_ID      the primary key for a particular datetime.
1005
-     *                            set to 0 for all related datetimes
1006
-     * @return int
1007
-     * @throws \EE_Error
1008
-     */
1009
-    public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1010
-    {
1011
-        $raw = $this->get_raw('TKT_qty');
1012
-        // return immediately if it's zero
1013
-        if ($raw === 0) {
1014
-            return $raw;
1015
-        }
1016
-        // echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1017
-        // ensure qty doesn't exceed raw value for THIS ticket
1018
-        $qty = min(EE_INF, $raw);
1019
-        // echo "\n . qty: " . $qty . '<br />';
1020
-        // calculate this ticket's total sales and reservations
1021
-        $sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1022
-        // echo "\n . sold: " . $this->sold() . '<br />';
1023
-        // echo "\n . reserved: " . $this->reserved() . '<br />';
1024
-        // echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1025
-        // first we need to calculate the maximum number of tickets available for the datetime
1026
-        // do we want data for one datetime or all of them ?
1027
-        $query_params = $DTT_ID ? array(array('DTT_ID' => $DTT_ID)) : array();
1028
-        $datetimes = $this->datetimes($query_params);
1029
-        if (is_array($datetimes) && ! empty($datetimes)) {
1030
-            foreach ($datetimes as $datetime) {
1031
-                if ($datetime instanceof EE_Datetime) {
1032
-                    $datetime->refresh_from_db();
1033
-                    // echo "\n . . datetime name: " . $datetime->name() . '<br />';
1034
-                    // echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1035
-                    // initialize with no restrictions for each datetime
1036
-                    // but adjust datetime qty based on datetime reg limit
1037
-                    $datetime_qty = min(EE_INF, $datetime->reg_limit());
1038
-                    // echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1039
-                    // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1040
-                    // if we want the actual saleable amount, then we need to consider OTHER ticket sales
1041
-                    // and reservations for this datetime, that do NOT include sales and reservations
1042
-                    // for this ticket (so we add $this->sold() and $this->reserved() back in)
1043
-                    if ($context === 'saleable') {
1044
-                        $datetime_qty = max(
1045
-                            $datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1046
-                            0
1047
-                        );
1048
-                        // echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1049
-                        // echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1050
-                        // echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1051
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1052
-                        $datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1053
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1054
-                    }
1055
-                    $qty = min($datetime_qty, $qty);
1056
-                    // echo "\n . . qty: " . $qty . '<br />';
1057
-                }
1058
-            }
1059
-        }
1060
-        // NOW that we know the  maximum number of tickets available for the datetime
1061
-        // we can finally factor in the details for this specific ticket
1062
-        if ($qty > 0 && $context === 'saleable') {
1063
-            // and subtract the sales for THIS ticket
1064
-            $qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1065
-            // echo "\n . qty: " . $qty . '<br />';
1066
-        }
1067
-        // echo "\nFINAL QTY: " . $qty . "<br /><br />";
1068
-        return $qty;
1069
-    }
1070
-
1071
-
1072
-    /**
1073
-     * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1074
-     *
1075
-     * @param int $qty
1076
-     * @return void
1077
-     * @throws \EE_Error
1078
-     */
1079
-    public function set_qty($qty)
1080
-    {
1081
-        $datetimes = $this->datetimes();
1082
-        foreach ($datetimes as $datetime) {
1083
-            if ($datetime instanceof EE_Datetime) {
1084
-                $qty = min($qty, $datetime->reg_limit());
1085
-            }
1086
-        }
1087
-        $this->set('TKT_qty', $qty);
1088
-    }
1089
-
1090
-
1091
-    /**
1092
-     * Gets uses
1093
-     *
1094
-     * @return int
1095
-     * @throws \EE_Error
1096
-     */
1097
-    public function uses()
1098
-    {
1099
-        return $this->get('TKT_uses');
1100
-    }
1101
-
1102
-
1103
-    /**
1104
-     * Sets uses
1105
-     *
1106
-     * @param int $uses
1107
-     * @return void
1108
-     * @throws \EE_Error
1109
-     */
1110
-    public function set_uses($uses)
1111
-    {
1112
-        $this->set('TKT_uses', $uses);
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * returns whether ticket is required or not.
1118
-     *
1119
-     * @return boolean
1120
-     * @throws \EE_Error
1121
-     */
1122
-    public function required()
1123
-    {
1124
-        return $this->get('TKT_required');
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * sets the TKT_required property
1130
-     *
1131
-     * @param boolean $required
1132
-     * @return void
1133
-     * @throws \EE_Error
1134
-     */
1135
-    public function set_required($required)
1136
-    {
1137
-        $this->set('TKT_required', $required);
1138
-    }
1139
-
1140
-
1141
-    /**
1142
-     * Gets taxable
1143
-     *
1144
-     * @return boolean
1145
-     * @throws \EE_Error
1146
-     */
1147
-    public function taxable()
1148
-    {
1149
-        return $this->get('TKT_taxable');
1150
-    }
1151
-
1152
-
1153
-    /**
1154
-     * Sets taxable
1155
-     *
1156
-     * @param boolean $taxable
1157
-     * @return void
1158
-     * @throws \EE_Error
1159
-     */
1160
-    public function set_taxable($taxable)
1161
-    {
1162
-        $this->set('TKT_taxable', $taxable);
1163
-    }
1164
-
1165
-
1166
-    /**
1167
-     * Gets is_default
1168
-     *
1169
-     * @return boolean
1170
-     * @throws \EE_Error
1171
-     */
1172
-    public function is_default()
1173
-    {
1174
-        return $this->get('TKT_is_default');
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     * Sets is_default
1180
-     *
1181
-     * @param boolean $is_default
1182
-     * @return void
1183
-     * @throws \EE_Error
1184
-     */
1185
-    public function set_is_default($is_default)
1186
-    {
1187
-        $this->set('TKT_is_default', $is_default);
1188
-    }
1189
-
1190
-
1191
-    /**
1192
-     * Gets order
1193
-     *
1194
-     * @return int
1195
-     * @throws \EE_Error
1196
-     */
1197
-    public function order()
1198
-    {
1199
-        return $this->get('TKT_order');
1200
-    }
1201
-
1202
-
1203
-    /**
1204
-     * Sets order
1205
-     *
1206
-     * @param int $order
1207
-     * @return void
1208
-     * @throws \EE_Error
1209
-     */
1210
-    public function set_order($order)
1211
-    {
1212
-        $this->set('TKT_order', $order);
1213
-    }
1214
-
1215
-
1216
-    /**
1217
-     * Gets row
1218
-     *
1219
-     * @return int
1220
-     * @throws \EE_Error
1221
-     */
1222
-    public function row()
1223
-    {
1224
-        return $this->get('TKT_row');
1225
-    }
1226
-
1227
-
1228
-    /**
1229
-     * Sets row
1230
-     *
1231
-     * @param int $row
1232
-     * @return void
1233
-     * @throws \EE_Error
1234
-     */
1235
-    public function set_row($row)
1236
-    {
1237
-        $this->set('TKT_row', $row);
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * Gets deleted
1243
-     *
1244
-     * @return boolean
1245
-     * @throws \EE_Error
1246
-     */
1247
-    public function deleted()
1248
-    {
1249
-        return $this->get('TKT_deleted');
1250
-    }
1251
-
1252
-
1253
-    /**
1254
-     * Sets deleted
1255
-     *
1256
-     * @param boolean $deleted
1257
-     * @return void
1258
-     * @throws \EE_Error
1259
-     */
1260
-    public function set_deleted($deleted)
1261
-    {
1262
-        $this->set('TKT_deleted', $deleted);
1263
-    }
1264
-
1265
-
1266
-    /**
1267
-     * Gets parent
1268
-     *
1269
-     * @return int
1270
-     * @throws \EE_Error
1271
-     */
1272
-    public function parent_ID()
1273
-    {
1274
-        return $this->get('TKT_parent');
1275
-    }
1276
-
1277
-
1278
-    /**
1279
-     * Sets parent
1280
-     *
1281
-     * @param int $parent
1282
-     * @return void
1283
-     * @throws \EE_Error
1284
-     */
1285
-    public function set_parent_ID($parent)
1286
-    {
1287
-        $this->set('TKT_parent', $parent);
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * Gets a string which is handy for showing in gateways etc that describes the ticket.
1293
-     *
1294
-     * @return string
1295
-     * @throws \EE_Error
1296
-     */
1297
-    public function name_and_info()
1298
-    {
1299
-        $times = array();
1300
-        foreach ($this->datetimes() as $datetime) {
1301
-            $times[] = $datetime->start_date_and_time();
1302
-        }
1303
-        return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1304
-    }
1305
-
1306
-
1307
-    /**
1308
-     * Gets name
1309
-     *
1310
-     * @return string
1311
-     * @throws \EE_Error
1312
-     */
1313
-    public function name()
1314
-    {
1315
-        return $this->get('TKT_name');
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * Gets price
1321
-     *
1322
-     * @return float
1323
-     * @throws \EE_Error
1324
-     */
1325
-    public function price()
1326
-    {
1327
-        return $this->get('TKT_price');
1328
-    }
1329
-
1330
-
1331
-    /**
1332
-     * Gets all the registrations for this ticket
1333
-     *
1334
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1335
-     * @return EE_Registration[]|EE_Base_Class[]
1336
-     * @throws \EE_Error
1337
-     */
1338
-    public function registrations($query_params = array())
1339
-    {
1340
-        return $this->get_many_related('Registration', $query_params);
1341
-    }
1342
-
1343
-
1344
-    /**
1345
-     * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1346
-     * into account
1347
-     *
1348
-     * @return int
1349
-     * @throws \EE_Error
1350
-     */
1351
-    public function update_tickets_sold()
1352
-    {
1353
-        $count_regs_for_this_ticket = $this->count_registrations(
1354
-            array(
1355
-                array(
1356
-                    'STS_ID'      => EEM_Registration::status_id_approved,
1357
-                    'REG_deleted' => 0,
1358
-                ),
1359
-            )
1360
-        );
1361
-        $sold = $this->sold();
1362
-        if ($count_regs_for_this_ticket > $sold) {
1363
-            $this->increase_sold($count_regs_for_this_ticket - $sold);
1364
-            $this->save();
1365
-        } elseif ($count_regs_for_this_ticket < $sold) {
1366
-            $this->decrease_sold($count_regs_for_this_ticket - $sold);
1367
-            $this->save();
1368
-        }
1369
-        return $count_regs_for_this_ticket;
1370
-    }
1371
-
1372
-
1373
-    /**
1374
-     * Counts the registrations for this ticket
1375
-     *
1376
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1377
-     * @return int
1378
-     */
1379
-    public function count_registrations($query_params = array())
1380
-    {
1381
-        return $this->count_related('Registration', $query_params);
1382
-    }
1383
-
1384
-
1385
-    /**
1386
-     * Implementation for EEI_Has_Icon interface method.
1387
-     *
1388
-     * @see EEI_Visual_Representation for comments
1389
-     * @return string
1390
-     */
1391
-    public function get_icon()
1392
-    {
1393
-        return '<span class="dashicons dashicons-tickets-alt"></span>';
1394
-    }
1395
-
1396
-
1397
-    /**
1398
-     * Implementation of the EEI_Event_Relation interface method
1399
-     *
1400
-     * @see EEI_Event_Relation for comments
1401
-     * @return EE_Event
1402
-     * @throws \EE_Error
1403
-     * @throws UnexpectedEntityException
1404
-     */
1405
-    public function get_related_event()
1406
-    {
1407
-        // get one datetime to use for getting the event
1408
-        $datetime = $this->first_datetime();
1409
-        if (! $datetime instanceof \EE_Datetime) {
1410
-            throw new UnexpectedEntityException(
1411
-                $datetime,
1412
-                'EE_Datetime',
1413
-                sprintf(
1414
-                    __('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1415
-                    $this->name()
1416
-                )
1417
-            );
1418
-        }
1419
-        $event = $datetime->event();
1420
-        if (! $event instanceof \EE_Event) {
1421
-            throw new UnexpectedEntityException(
1422
-                $event,
1423
-                'EE_Event',
1424
-                sprintf(
1425
-                    __('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1426
-                    $this->name()
1427
-                )
1428
-            );
1429
-        }
1430
-        return $event;
1431
-    }
1432
-
1433
-
1434
-    /**
1435
-     * Implementation of the EEI_Event_Relation interface method
1436
-     *
1437
-     * @see EEI_Event_Relation for comments
1438
-     * @return string
1439
-     * @throws UnexpectedEntityException
1440
-     * @throws \EE_Error
1441
-     */
1442
-    public function get_event_name()
1443
-    {
1444
-        $event = $this->get_related_event();
1445
-        return $event instanceof EE_Event ? $event->name() : '';
1446
-    }
1447
-
1448
-
1449
-    /**
1450
-     * Implementation of the EEI_Event_Relation interface method
1451
-     *
1452
-     * @see EEI_Event_Relation for comments
1453
-     * @return int
1454
-     * @throws UnexpectedEntityException
1455
-     * @throws \EE_Error
1456
-     */
1457
-    public function get_event_ID()
1458
-    {
1459
-        $event = $this->get_related_event();
1460
-        return $event instanceof EE_Event ? $event->ID() : 0;
1461
-    }
1462
-
1463
-
1464
-    /**
1465
-     * This simply returns whether a ticket can be permanently deleted or not.
1466
-     * The criteria for determining this is whether the ticket has any related registrations.
1467
-     * If there are none then it can be permanently deleted.
1468
-     *
1469
-     * @return bool
1470
-     */
1471
-    public function is_permanently_deleteable()
1472
-    {
1473
-        return $this->count_registrations() === 0;
1474
-    }
15
+	/**
16
+	 * The following constants are used by the ticket_status() method to indicate whether a ticket is on sale or not.
17
+	 */
18
+	const sold_out = 'TKS';
19
+
20
+	/**
21
+	 *
22
+	 */
23
+	const expired = 'TKE';
24
+
25
+	/**
26
+	 *
27
+	 */
28
+	const archived = 'TKA';
29
+
30
+	/**
31
+	 *
32
+	 */
33
+	const pending = 'TKP';
34
+
35
+	/**
36
+	 *
37
+	 */
38
+	const onsale = 'TKO';
39
+
40
+	/**
41
+	 * extra meta key for tracking ticket reservations
42
+	 *
43
+	 * @type string
44
+	 */
45
+	const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
46
+
47
+	/**
48
+	 * cached result from method of the same name
49
+	 *
50
+	 * @var float $_ticket_total_with_taxes
51
+	 */
52
+	private $_ticket_total_with_taxes;
53
+
54
+
55
+	/**
56
+	 * @param array  $props_n_values          incoming values
57
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
58
+	 *                                        used.)
59
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
60
+	 *                                        date_format and the second value is the time format
61
+	 * @return EE_Ticket
62
+	 * @throws \EE_Error
63
+	 */
64
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
+	{
66
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
67
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param array  $props_n_values  incoming values from the database
73
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
74
+	 *                                the website will be used.
75
+	 * @return EE_Ticket
76
+	 * @throws \EE_Error
77
+	 */
78
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
79
+	{
80
+		return new self($props_n_values, true, $timezone);
81
+	}
82
+
83
+
84
+	/**
85
+	 * @return bool
86
+	 * @throws \EE_Error
87
+	 */
88
+	public function parent()
89
+	{
90
+		return $this->get('TKT_parent');
91
+	}
92
+
93
+
94
+	/**
95
+	 * return if a ticket has quantities available for purchase
96
+	 *
97
+	 * @param  int $DTT_ID the primary key for a particular datetime
98
+	 * @return boolean
99
+	 * @throws \EE_Error
100
+	 */
101
+	public function available($DTT_ID = 0)
102
+	{
103
+		// are we checking availability for a particular datetime ?
104
+		if ($DTT_ID) {
105
+			// get that datetime object
106
+			$datetime = $this->get_first_related('Datetime', array(array('DTT_ID' => $DTT_ID)));
107
+			// if  ticket sales for this datetime have exceeded the reg limit...
108
+			if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
109
+				return false;
110
+			}
111
+		}
112
+		// datetime is still open for registration, but is this ticket sold out ?
113
+		return $this->qty() < 1 || $this->qty() > $this->sold() ? true : false;
114
+	}
115
+
116
+
117
+	/**
118
+	 * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
119
+	 *
120
+	 * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
121
+	 *                               relevant status const
122
+	 * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
123
+	 *               further processing
124
+	 * @return mixed status int if the display string isn't requested
125
+	 * @throws \EE_Error
126
+	 */
127
+	public function ticket_status($display = false, $remaining = null)
128
+	{
129
+		$remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
130
+		if (! $remaining) {
131
+			return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
132
+		}
133
+		if ($this->get('TKT_deleted')) {
134
+			return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
135
+		}
136
+		if ($this->is_expired()) {
137
+			return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
138
+		}
139
+		if ($this->is_pending()) {
140
+			return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
141
+		}
142
+		if ($this->is_on_sale()) {
143
+			return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
144
+		}
145
+		return '';
146
+	}
147
+
148
+
149
+	/**
150
+	 * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
151
+	 * considering ALL the factors used for figuring that out.
152
+	 *
153
+	 * @access public
154
+	 * @param  int $DTT_ID if an int above 0 is included here then we get a specific dtt.
155
+	 * @return boolean         true = tickets remaining, false not.
156
+	 * @throws \EE_Error
157
+	 */
158
+	public function is_remaining($DTT_ID = 0)
159
+	{
160
+		$num_remaining = $this->remaining($DTT_ID);
161
+		if ($num_remaining === 0) {
162
+			return false;
163
+		}
164
+		if ($num_remaining > 0 && $num_remaining < $this->min()) {
165
+			return false;
166
+		}
167
+		return true;
168
+	}
169
+
170
+
171
+	/**
172
+	 * return the total number of tickets available for purchase
173
+	 *
174
+	 * @param  int $DTT_ID the primary key for a particular datetime.
175
+	 *                     set to 0 for all related datetimes
176
+	 * @return int
177
+	 * @throws \EE_Error
178
+	 */
179
+	public function remaining($DTT_ID = 0)
180
+	{
181
+		return $this->real_quantity_on_ticket('saleable', $DTT_ID);
182
+	}
183
+
184
+
185
+	/**
186
+	 * Gets min
187
+	 *
188
+	 * @return int
189
+	 * @throws \EE_Error
190
+	 */
191
+	public function min()
192
+	{
193
+		return $this->get('TKT_min');
194
+	}
195
+
196
+
197
+	/**
198
+	 * return if a ticket is no longer available cause its available dates have expired.
199
+	 *
200
+	 * @return boolean
201
+	 * @throws \EE_Error
202
+	 */
203
+	public function is_expired()
204
+	{
205
+		return ($this->get_raw('TKT_end_date') < time());
206
+	}
207
+
208
+
209
+	/**
210
+	 * Return if a ticket is yet to go on sale or not
211
+	 *
212
+	 * @return boolean
213
+	 * @throws \EE_Error
214
+	 */
215
+	public function is_pending()
216
+	{
217
+		return ($this->get_raw('TKT_start_date') > time());
218
+	}
219
+
220
+
221
+	/**
222
+	 * Return if a ticket is on sale or not
223
+	 *
224
+	 * @return boolean
225
+	 * @throws \EE_Error
226
+	 */
227
+	public function is_on_sale()
228
+	{
229
+		return ($this->get_raw('TKT_start_date') < time() && $this->get_raw('TKT_end_date') > time());
230
+	}
231
+
232
+
233
+	/**
234
+	 * This returns the chronologically last datetime that this ticket is associated with
235
+	 *
236
+	 * @param string $dt_frmt
237
+	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
238
+	 *                            the end date ie: Jan 01 "to" Dec 31
239
+	 * @return string
240
+	 * @throws \EE_Error
241
+	 */
242
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
243
+	{
244
+		$first_date = $this->first_datetime() instanceof EE_Datetime ? $this->first_datetime()->start_date($dt_frmt)
245
+			: '';
246
+		$last_date = $this->last_datetime() instanceof EE_Datetime ? $this->last_datetime()->end_date($dt_frmt) : '';
247
+
248
+		return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
249
+	}
250
+
251
+
252
+	/**
253
+	 * This returns the chronologically first datetime that this ticket is associated with
254
+	 *
255
+	 * @return EE_Datetime
256
+	 * @throws \EE_Error
257
+	 */
258
+	public function first_datetime()
259
+	{
260
+		$datetimes = $this->datetimes(array('limit' => 1));
261
+		return reset($datetimes);
262
+	}
263
+
264
+
265
+	/**
266
+	 * Gets all the datetimes this ticket can be used for attending.
267
+	 * Unless otherwise specified, orders datetimes by start date.
268
+	 *
269
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
270
+	 * @return EE_Datetime[]|EE_Base_Class[]
271
+	 * @throws \EE_Error
272
+	 */
273
+	public function datetimes($query_params = array())
274
+	{
275
+		if (! isset($query_params['order_by'])) {
276
+			$query_params['order_by']['DTT_order'] = 'ASC';
277
+		}
278
+		return $this->get_many_related('Datetime', $query_params);
279
+	}
280
+
281
+
282
+	/**
283
+	 * This returns the chronologically last datetime that this ticket is associated with
284
+	 *
285
+	 * @return EE_Datetime
286
+	 * @throws \EE_Error
287
+	 */
288
+	public function last_datetime()
289
+	{
290
+		$datetimes = $this->datetimes(array('limit' => 1, 'order_by' => array('DTT_EVT_start' => 'DESC')));
291
+		return end($datetimes);
292
+	}
293
+
294
+
295
+	/**
296
+	 * This returns the total tickets sold depending on the given parameters.
297
+	 *
298
+	 * @param  string $what   Can be one of two options: 'ticket', 'datetime'.
299
+	 *                        'ticket' = total ticket sales for all datetimes this ticket is related to
300
+	 *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
301
+	 *                        'datetime' = total ticket sales in the datetime_ticket table.
302
+	 *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
303
+	 *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
304
+	 * @param  int    $dtt_id [optional] include the dtt_id with $what = 'datetime'.
305
+	 * @return mixed (array|int)          how many tickets have sold
306
+	 * @throws \EE_Error
307
+	 */
308
+	public function tickets_sold($what = 'ticket', $dtt_id = null)
309
+	{
310
+		$total = 0;
311
+		$tickets_sold = $this->_all_tickets_sold();
312
+		switch ($what) {
313
+			case 'ticket':
314
+				return $tickets_sold['ticket'];
315
+				break;
316
+			case 'datetime':
317
+				if (empty($tickets_sold['datetime'])) {
318
+					return $total;
319
+				}
320
+				if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
321
+					EE_Error::add_error(
322
+						__(
323
+							'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
324
+							'event_espresso'
325
+						),
326
+						__FILE__,
327
+						__FUNCTION__,
328
+						__LINE__
329
+					);
330
+					return $total;
331
+				}
332
+				return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
333
+				break;
334
+			default:
335
+				return $total;
336
+		}
337
+	}
338
+
339
+
340
+	/**
341
+	 * This returns an array indexed by datetime_id for tickets sold with this ticket.
342
+	 *
343
+	 * @return EE_Ticket[]
344
+	 * @throws \EE_Error
345
+	 */
346
+	protected function _all_tickets_sold()
347
+	{
348
+		$datetimes = $this->get_many_related('Datetime');
349
+		$tickets_sold = array();
350
+		if (! empty($datetimes)) {
351
+			foreach ($datetimes as $datetime) {
352
+				$tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
353
+			}
354
+		}
355
+		// Tickets sold
356
+		$tickets_sold['ticket'] = $this->sold();
357
+		return $tickets_sold;
358
+	}
359
+
360
+
361
+	/**
362
+	 * This returns the base price object for the ticket.
363
+	 *
364
+	 * @param  bool $return_array whether to return as an array indexed by price id or just the object.
365
+	 * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
366
+	 * @throws \EE_Error
367
+	 */
368
+	public function base_price($return_array = false)
369
+	{
370
+		$_where = array('Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price);
371
+		return $return_array
372
+			? $this->get_many_related('Price', array($_where))
373
+			: $this->get_first_related('Price', array($_where));
374
+	}
375
+
376
+
377
+	/**
378
+	 * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
379
+	 *
380
+	 * @access public
381
+	 * @return EE_Price[]
382
+	 * @throws \EE_Error
383
+	 */
384
+	public function price_modifiers()
385
+	{
386
+		$query_params = array(
387
+			0 => array(
388
+				'Price_Type.PBT_ID' => array(
389
+					'NOT IN',
390
+					array(EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax),
391
+				),
392
+			),
393
+		);
394
+		return $this->prices($query_params);
395
+	}
396
+
397
+
398
+	/**
399
+	 * Gets all the prices that combine to form the final price of this ticket
400
+	 *
401
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
402
+	 * @return EE_Price[]|EE_Base_Class[]
403
+	 * @throws \EE_Error
404
+	 */
405
+	public function prices($query_params = array())
406
+	{
407
+		return $this->get_many_related('Price', $query_params);
408
+	}
409
+
410
+
411
+	/**
412
+	 * Gets all the ticket applicabilities (ie, relations between datetimes and tickets)
413
+	 *
414
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
415
+	 * @return EE_Datetime_Ticket|EE_Base_Class[]
416
+	 * @throws \EE_Error
417
+	 */
418
+	public function datetime_tickets($query_params = array())
419
+	{
420
+		return $this->get_many_related('Datetime_Ticket', $query_params);
421
+	}
422
+
423
+
424
+	/**
425
+	 * Gets all the datetimes from the db ordered by DTT_order
426
+	 *
427
+	 * @param boolean $show_expired
428
+	 * @param boolean $show_deleted
429
+	 * @return EE_Datetime[]
430
+	 * @throws \EE_Error
431
+	 */
432
+	public function datetimes_ordered($show_expired = true, $show_deleted = false)
433
+	{
434
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
435
+			$this->ID(),
436
+			$show_expired,
437
+			$show_deleted
438
+		);
439
+	}
440
+
441
+
442
+	/**
443
+	 * Gets ID
444
+	 *
445
+	 * @return string
446
+	 * @throws \EE_Error
447
+	 */
448
+	public function ID()
449
+	{
450
+		return $this->get('TKT_ID');
451
+	}
452
+
453
+
454
+	/**
455
+	 * get the author of the ticket.
456
+	 *
457
+	 * @since 4.5.0
458
+	 * @return int
459
+	 * @throws \EE_Error
460
+	 */
461
+	public function wp_user()
462
+	{
463
+		return $this->get('TKT_wp_user');
464
+	}
465
+
466
+
467
+	/**
468
+	 * Gets the template for the ticket
469
+	 *
470
+	 * @return EE_Ticket_Template|EE_Base_Class
471
+	 * @throws \EE_Error
472
+	 */
473
+	public function template()
474
+	{
475
+		return $this->get_first_related('Ticket_Template');
476
+	}
477
+
478
+
479
+	/**
480
+	 * Simply returns an array of EE_Price objects that are taxes.
481
+	 *
482
+	 * @return EE_Price[]
483
+	 * @throws \EE_Error
484
+	 */
485
+	public function get_ticket_taxes_for_admin()
486
+	{
487
+		return EE_Taxes::get_taxes_for_admin();
488
+	}
489
+
490
+
491
+	/**
492
+	 * @return float
493
+	 * @throws \EE_Error
494
+	 */
495
+	public function ticket_price()
496
+	{
497
+		return $this->get('TKT_price');
498
+	}
499
+
500
+
501
+	/**
502
+	 * @return mixed
503
+	 * @throws \EE_Error
504
+	 */
505
+	public function pretty_price()
506
+	{
507
+		return $this->get_pretty('TKT_price');
508
+	}
509
+
510
+
511
+	/**
512
+	 * @return bool
513
+	 * @throws \EE_Error
514
+	 */
515
+	public function is_free()
516
+	{
517
+		return $this->get_ticket_total_with_taxes() === (float) 0;
518
+	}
519
+
520
+
521
+	/**
522
+	 * get_ticket_total_with_taxes
523
+	 *
524
+	 * @param bool $no_cache
525
+	 * @return float
526
+	 * @throws \EE_Error
527
+	 */
528
+	public function get_ticket_total_with_taxes($no_cache = false)
529
+	{
530
+		if ($this->_ticket_total_with_taxes === null || $no_cache) {
531
+			$this->_ticket_total_with_taxes = $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin();
532
+		}
533
+		return (float) $this->_ticket_total_with_taxes;
534
+	}
535
+
536
+
537
+	public function ensure_TKT_Price_correct()
538
+	{
539
+		$this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
540
+		$this->save();
541
+	}
542
+
543
+
544
+	/**
545
+	 * @return float
546
+	 * @throws \EE_Error
547
+	 */
548
+	public function get_ticket_subtotal()
549
+	{
550
+		return EE_Taxes::get_subtotal_for_admin($this);
551
+	}
552
+
553
+
554
+	/**
555
+	 * Returns the total taxes applied to this ticket
556
+	 *
557
+	 * @return float
558
+	 * @throws \EE_Error
559
+	 */
560
+	public function get_ticket_taxes_total_for_admin()
561
+	{
562
+		return EE_Taxes::get_total_taxes_for_admin($this);
563
+	}
564
+
565
+
566
+	/**
567
+	 * Sets name
568
+	 *
569
+	 * @param string $name
570
+	 * @throws \EE_Error
571
+	 */
572
+	public function set_name($name)
573
+	{
574
+		$this->set('TKT_name', $name);
575
+	}
576
+
577
+
578
+	/**
579
+	 * Gets description
580
+	 *
581
+	 * @return string
582
+	 * @throws \EE_Error
583
+	 */
584
+	public function description()
585
+	{
586
+		return $this->get('TKT_description');
587
+	}
588
+
589
+
590
+	/**
591
+	 * Sets description
592
+	 *
593
+	 * @param string $description
594
+	 * @throws \EE_Error
595
+	 */
596
+	public function set_description($description)
597
+	{
598
+		$this->set('TKT_description', $description);
599
+	}
600
+
601
+
602
+	/**
603
+	 * Gets start_date
604
+	 *
605
+	 * @param string $dt_frmt
606
+	 * @param string $tm_frmt
607
+	 * @return string
608
+	 * @throws \EE_Error
609
+	 */
610
+	public function start_date($dt_frmt = '', $tm_frmt = '')
611
+	{
612
+		return $this->_get_datetime('TKT_start_date', $dt_frmt, $tm_frmt);
613
+	}
614
+
615
+
616
+	/**
617
+	 * Sets start_date
618
+	 *
619
+	 * @param string $start_date
620
+	 * @return void
621
+	 * @throws \EE_Error
622
+	 */
623
+	public function set_start_date($start_date)
624
+	{
625
+		$this->_set_date_time('B', $start_date, 'TKT_start_date');
626
+	}
627
+
628
+
629
+	/**
630
+	 * Gets end_date
631
+	 *
632
+	 * @param string $dt_frmt
633
+	 * @param string $tm_frmt
634
+	 * @return string
635
+	 * @throws \EE_Error
636
+	 */
637
+	public function end_date($dt_frmt = '', $tm_frmt = '')
638
+	{
639
+		return $this->_get_datetime('TKT_end_date', $dt_frmt, $tm_frmt);
640
+	}
641
+
642
+
643
+	/**
644
+	 * Sets end_date
645
+	 *
646
+	 * @param string $end_date
647
+	 * @return void
648
+	 * @throws \EE_Error
649
+	 */
650
+	public function set_end_date($end_date)
651
+	{
652
+		$this->_set_date_time('B', $end_date, 'TKT_end_date');
653
+	}
654
+
655
+
656
+	/**
657
+	 * Sets sell until time
658
+	 *
659
+	 * @since 4.5.0
660
+	 * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
661
+	 * @throws \EE_Error
662
+	 */
663
+	public function set_end_time($time)
664
+	{
665
+		$this->_set_time_for($time, 'TKT_end_date');
666
+	}
667
+
668
+
669
+	/**
670
+	 * Sets min
671
+	 *
672
+	 * @param int $min
673
+	 * @return void
674
+	 * @throws \EE_Error
675
+	 */
676
+	public function set_min($min)
677
+	{
678
+		$this->set('TKT_min', $min);
679
+	}
680
+
681
+
682
+	/**
683
+	 * Gets max
684
+	 *
685
+	 * @return int
686
+	 * @throws \EE_Error
687
+	 */
688
+	public function max()
689
+	{
690
+		return $this->get('TKT_max');
691
+	}
692
+
693
+
694
+	/**
695
+	 * Sets max
696
+	 *
697
+	 * @param int $max
698
+	 * @return void
699
+	 * @throws \EE_Error
700
+	 */
701
+	public function set_max($max)
702
+	{
703
+		$this->set('TKT_max', $max);
704
+	}
705
+
706
+
707
+	/**
708
+	 * Sets price
709
+	 *
710
+	 * @param float $price
711
+	 * @return void
712
+	 * @throws \EE_Error
713
+	 */
714
+	public function set_price($price)
715
+	{
716
+		$this->set('TKT_price', $price);
717
+	}
718
+
719
+
720
+	/**
721
+	 * Gets sold
722
+	 *
723
+	 * @return int
724
+	 * @throws \EE_Error
725
+	 */
726
+	public function sold()
727
+	{
728
+		return $this->get_raw('TKT_sold');
729
+	}
730
+
731
+
732
+	/**
733
+	 * Sets sold
734
+	 *
735
+	 * @param int $sold
736
+	 * @return void
737
+	 * @throws \EE_Error
738
+	 */
739
+	public function set_sold($sold)
740
+	{
741
+		// sold can not go below zero
742
+		$sold = max(0, $sold);
743
+		$this->set('TKT_sold', $sold);
744
+	}
745
+
746
+
747
+	/**
748
+	 * increments sold by amount passed by $qty
749
+	 *
750
+	 * @param int $qty
751
+	 * @return void
752
+	 * @throws \EE_Error
753
+	 */
754
+	public function increase_sold($qty = 1)
755
+	{
756
+		$sold = $this->sold() + $qty;
757
+		// remove ticket reservation, but don't adjust datetime reservations,  because that will happen
758
+		// via \EE_Datetime::increase_sold() when \EE_Ticket::_increase_sold_for_datetimes() is called
759
+		$this->decrease_reserved($qty, false, "TKT: {$this->ID()} (ln:" . __LINE__ . ')');
760
+		$this->_increase_sold_for_datetimes($qty);
761
+		$this->set_sold($sold);
762
+		do_action(
763
+			'AHEE__EE_Ticket__increase_sold',
764
+			$this,
765
+			$qty,
766
+			$sold
767
+		);
768
+	}
769
+
770
+
771
+	/**
772
+	 * Increases sold on related datetimes
773
+	 *
774
+	 * @param int $qty
775
+	 * @return void
776
+	 * @throws \EE_Error
777
+	 */
778
+	protected function _increase_sold_for_datetimes($qty = 1)
779
+	{
780
+		$datetimes = $this->datetimes();
781
+		if (is_array($datetimes)) {
782
+			foreach ($datetimes as $datetime) {
783
+				if ($datetime instanceof EE_Datetime) {
784
+					$datetime->increase_sold($qty);
785
+					$datetime->save();
786
+				}
787
+			}
788
+		}
789
+	}
790
+
791
+
792
+	/**
793
+	 * decrements (subtracts) sold by amount passed by $qty
794
+	 *
795
+	 * @param int $qty
796
+	 * @return void
797
+	 * @throws \EE_Error
798
+	 */
799
+	public function decrease_sold($qty = 1)
800
+	{
801
+		$sold = $this->sold() - $qty;
802
+		$this->_decrease_sold_for_datetimes($qty);
803
+		$this->set_sold($sold);
804
+		do_action(
805
+			'AHEE__EE_Ticket__decrease_sold',
806
+			$this,
807
+			$qty,
808
+			$sold
809
+		);
810
+	}
811
+
812
+
813
+	/**
814
+	 * Decreases sold on related datetimes
815
+	 *
816
+	 * @param int $qty
817
+	 * @return void
818
+	 * @throws \EE_Error
819
+	 */
820
+	protected function _decrease_sold_for_datetimes($qty = 1)
821
+	{
822
+		$datetimes = $this->datetimes();
823
+		if (is_array($datetimes)) {
824
+			foreach ($datetimes as $datetime) {
825
+				if ($datetime instanceof EE_Datetime) {
826
+					$datetime->decrease_sold($qty);
827
+					$datetime->save();
828
+				}
829
+			}
830
+		}
831
+	}
832
+
833
+
834
+	/**
835
+	 * Gets qty of reserved tickets
836
+	 *
837
+	 * @return int
838
+	 * @throws \EE_Error
839
+	 */
840
+	public function reserved()
841
+	{
842
+		return $this->get_raw('TKT_reserved');
843
+	}
844
+
845
+
846
+	/**
847
+	 * Sets reserved
848
+	 *
849
+	 * @param int $reserved
850
+	 * @return void
851
+	 * @throws \EE_Error
852
+	 */
853
+	public function set_reserved($reserved)
854
+	{
855
+		// reserved can not go below zero
856
+		$reserved = max(0, (int) $reserved);
857
+		$this->set('TKT_reserved', $reserved);
858
+	}
859
+
860
+
861
+	/**
862
+	 * increments reserved by amount passed by $qty
863
+	 *
864
+	 * @param int    $qty
865
+	 * @param string $source
866
+	 * @return void
867
+	 * @throws EE_Error
868
+	 * @throws InvalidArgumentException
869
+	 * @throws ReflectionException
870
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
871
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
872
+	 */
873
+	public function increase_reserved($qty = 1, $source = 'unknown')
874
+	{
875
+		$qty = absint($qty);
876
+		$reserved = $this->reserved() + $qty;
877
+		if ($reserved
878
+			&& $this->add_extra_meta(
879
+				EE_Ticket::META_KEY_TICKET_RESERVATIONS,
880
+				"{$qty} from {$source}"
881
+			)
882
+		) {
883
+			$this->_increase_reserved_for_datetimes($qty);
884
+			$this->set_reserved($reserved);
885
+			do_action(
886
+				'AHEE__EE_Ticket__increase_reserved',
887
+				$this,
888
+				$qty,
889
+				$reserved
890
+			);
891
+		}
892
+	}
893
+
894
+
895
+	/**
896
+	 * Increases sold on related datetimes
897
+	 *
898
+	 * @param int $qty
899
+	 * @return void
900
+	 * @throws \EE_Error
901
+	 */
902
+	protected function _increase_reserved_for_datetimes($qty = 1)
903
+	{
904
+		$datetimes = $this->datetimes();
905
+		if (is_array($datetimes)) {
906
+			foreach ($datetimes as $datetime) {
907
+				if ($datetime instanceof EE_Datetime) {
908
+					$datetime->increase_reserved($qty);
909
+					$datetime->save();
910
+				}
911
+			}
912
+		}
913
+	}
914
+
915
+
916
+	/**
917
+	 * decrements (subtracts) reserved by amount passed by $qty
918
+	 *
919
+	 * @param int    $qty
920
+	 * @param bool   $adjust_datetimes
921
+	 * @param string $source
922
+	 * @return void
923
+	 * @throws EE_Error
924
+	 * @throws InvalidArgumentException
925
+	 * @throws ReflectionException
926
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
927
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
928
+	 */
929
+	public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
930
+	{
931
+		$reserved = $this->reserved() - absint($qty);
932
+		if ($this->add_extra_meta(
933
+			EE_Ticket::META_KEY_TICKET_RESERVATIONS,
934
+			"-{$qty} from {$source}"
935
+		)) {
936
+			if ($adjust_datetimes) {
937
+				$this->_decrease_reserved_for_datetimes($qty);
938
+			}
939
+			$this->set_reserved($reserved);
940
+			do_action(
941
+				'AHEE__EE_Ticket__decrease_reserved',
942
+				$this,
943
+				$qty,
944
+				$reserved
945
+			);
946
+		}
947
+	}
948
+
949
+
950
+	/**
951
+	 * Increases sold on related datetimes
952
+	 *
953
+	 * @param int $qty
954
+	 * @return void
955
+	 * @throws \EE_Error
956
+	 */
957
+	protected function _decrease_reserved_for_datetimes($qty = 1)
958
+	{
959
+		$datetimes = $this->datetimes();
960
+		if (is_array($datetimes)) {
961
+			foreach ($datetimes as $datetime) {
962
+				if ($datetime instanceof EE_Datetime) {
963
+					$datetime->decrease_reserved($qty);
964
+					$datetime->save();
965
+				}
966
+			}
967
+		}
968
+	}
969
+
970
+
971
+	/**
972
+	 * Gets ticket quantity
973
+	 *
974
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
975
+	 *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
976
+	 *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
977
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
978
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
979
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
980
+	 * @return int
981
+	 * @throws \EE_Error
982
+	 */
983
+	public function qty($context = '')
984
+	{
985
+		switch ($context) {
986
+			case 'reg_limit':
987
+				return $this->real_quantity_on_ticket();
988
+			case 'saleable':
989
+				return $this->real_quantity_on_ticket('saleable');
990
+			default:
991
+				return $this->get_raw('TKT_qty');
992
+		}
993
+	}
994
+
995
+
996
+	/**
997
+	 * Gets ticket quantity
998
+	 *
999
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1000
+	 *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1001
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1002
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1003
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1004
+	 * @param  int   $DTT_ID      the primary key for a particular datetime.
1005
+	 *                            set to 0 for all related datetimes
1006
+	 * @return int
1007
+	 * @throws \EE_Error
1008
+	 */
1009
+	public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1010
+	{
1011
+		$raw = $this->get_raw('TKT_qty');
1012
+		// return immediately if it's zero
1013
+		if ($raw === 0) {
1014
+			return $raw;
1015
+		}
1016
+		// echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1017
+		// ensure qty doesn't exceed raw value for THIS ticket
1018
+		$qty = min(EE_INF, $raw);
1019
+		// echo "\n . qty: " . $qty . '<br />';
1020
+		// calculate this ticket's total sales and reservations
1021
+		$sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1022
+		// echo "\n . sold: " . $this->sold() . '<br />';
1023
+		// echo "\n . reserved: " . $this->reserved() . '<br />';
1024
+		// echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1025
+		// first we need to calculate the maximum number of tickets available for the datetime
1026
+		// do we want data for one datetime or all of them ?
1027
+		$query_params = $DTT_ID ? array(array('DTT_ID' => $DTT_ID)) : array();
1028
+		$datetimes = $this->datetimes($query_params);
1029
+		if (is_array($datetimes) && ! empty($datetimes)) {
1030
+			foreach ($datetimes as $datetime) {
1031
+				if ($datetime instanceof EE_Datetime) {
1032
+					$datetime->refresh_from_db();
1033
+					// echo "\n . . datetime name: " . $datetime->name() . '<br />';
1034
+					// echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1035
+					// initialize with no restrictions for each datetime
1036
+					// but adjust datetime qty based on datetime reg limit
1037
+					$datetime_qty = min(EE_INF, $datetime->reg_limit());
1038
+					// echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1039
+					// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1040
+					// if we want the actual saleable amount, then we need to consider OTHER ticket sales
1041
+					// and reservations for this datetime, that do NOT include sales and reservations
1042
+					// for this ticket (so we add $this->sold() and $this->reserved() back in)
1043
+					if ($context === 'saleable') {
1044
+						$datetime_qty = max(
1045
+							$datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1046
+							0
1047
+						);
1048
+						// echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1049
+						// echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1050
+						// echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1051
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1052
+						$datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1053
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1054
+					}
1055
+					$qty = min($datetime_qty, $qty);
1056
+					// echo "\n . . qty: " . $qty . '<br />';
1057
+				}
1058
+			}
1059
+		}
1060
+		// NOW that we know the  maximum number of tickets available for the datetime
1061
+		// we can finally factor in the details for this specific ticket
1062
+		if ($qty > 0 && $context === 'saleable') {
1063
+			// and subtract the sales for THIS ticket
1064
+			$qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1065
+			// echo "\n . qty: " . $qty . '<br />';
1066
+		}
1067
+		// echo "\nFINAL QTY: " . $qty . "<br /><br />";
1068
+		return $qty;
1069
+	}
1070
+
1071
+
1072
+	/**
1073
+	 * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1074
+	 *
1075
+	 * @param int $qty
1076
+	 * @return void
1077
+	 * @throws \EE_Error
1078
+	 */
1079
+	public function set_qty($qty)
1080
+	{
1081
+		$datetimes = $this->datetimes();
1082
+		foreach ($datetimes as $datetime) {
1083
+			if ($datetime instanceof EE_Datetime) {
1084
+				$qty = min($qty, $datetime->reg_limit());
1085
+			}
1086
+		}
1087
+		$this->set('TKT_qty', $qty);
1088
+	}
1089
+
1090
+
1091
+	/**
1092
+	 * Gets uses
1093
+	 *
1094
+	 * @return int
1095
+	 * @throws \EE_Error
1096
+	 */
1097
+	public function uses()
1098
+	{
1099
+		return $this->get('TKT_uses');
1100
+	}
1101
+
1102
+
1103
+	/**
1104
+	 * Sets uses
1105
+	 *
1106
+	 * @param int $uses
1107
+	 * @return void
1108
+	 * @throws \EE_Error
1109
+	 */
1110
+	public function set_uses($uses)
1111
+	{
1112
+		$this->set('TKT_uses', $uses);
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * returns whether ticket is required or not.
1118
+	 *
1119
+	 * @return boolean
1120
+	 * @throws \EE_Error
1121
+	 */
1122
+	public function required()
1123
+	{
1124
+		return $this->get('TKT_required');
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * sets the TKT_required property
1130
+	 *
1131
+	 * @param boolean $required
1132
+	 * @return void
1133
+	 * @throws \EE_Error
1134
+	 */
1135
+	public function set_required($required)
1136
+	{
1137
+		$this->set('TKT_required', $required);
1138
+	}
1139
+
1140
+
1141
+	/**
1142
+	 * Gets taxable
1143
+	 *
1144
+	 * @return boolean
1145
+	 * @throws \EE_Error
1146
+	 */
1147
+	public function taxable()
1148
+	{
1149
+		return $this->get('TKT_taxable');
1150
+	}
1151
+
1152
+
1153
+	/**
1154
+	 * Sets taxable
1155
+	 *
1156
+	 * @param boolean $taxable
1157
+	 * @return void
1158
+	 * @throws \EE_Error
1159
+	 */
1160
+	public function set_taxable($taxable)
1161
+	{
1162
+		$this->set('TKT_taxable', $taxable);
1163
+	}
1164
+
1165
+
1166
+	/**
1167
+	 * Gets is_default
1168
+	 *
1169
+	 * @return boolean
1170
+	 * @throws \EE_Error
1171
+	 */
1172
+	public function is_default()
1173
+	{
1174
+		return $this->get('TKT_is_default');
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 * Sets is_default
1180
+	 *
1181
+	 * @param boolean $is_default
1182
+	 * @return void
1183
+	 * @throws \EE_Error
1184
+	 */
1185
+	public function set_is_default($is_default)
1186
+	{
1187
+		$this->set('TKT_is_default', $is_default);
1188
+	}
1189
+
1190
+
1191
+	/**
1192
+	 * Gets order
1193
+	 *
1194
+	 * @return int
1195
+	 * @throws \EE_Error
1196
+	 */
1197
+	public function order()
1198
+	{
1199
+		return $this->get('TKT_order');
1200
+	}
1201
+
1202
+
1203
+	/**
1204
+	 * Sets order
1205
+	 *
1206
+	 * @param int $order
1207
+	 * @return void
1208
+	 * @throws \EE_Error
1209
+	 */
1210
+	public function set_order($order)
1211
+	{
1212
+		$this->set('TKT_order', $order);
1213
+	}
1214
+
1215
+
1216
+	/**
1217
+	 * Gets row
1218
+	 *
1219
+	 * @return int
1220
+	 * @throws \EE_Error
1221
+	 */
1222
+	public function row()
1223
+	{
1224
+		return $this->get('TKT_row');
1225
+	}
1226
+
1227
+
1228
+	/**
1229
+	 * Sets row
1230
+	 *
1231
+	 * @param int $row
1232
+	 * @return void
1233
+	 * @throws \EE_Error
1234
+	 */
1235
+	public function set_row($row)
1236
+	{
1237
+		$this->set('TKT_row', $row);
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * Gets deleted
1243
+	 *
1244
+	 * @return boolean
1245
+	 * @throws \EE_Error
1246
+	 */
1247
+	public function deleted()
1248
+	{
1249
+		return $this->get('TKT_deleted');
1250
+	}
1251
+
1252
+
1253
+	/**
1254
+	 * Sets deleted
1255
+	 *
1256
+	 * @param boolean $deleted
1257
+	 * @return void
1258
+	 * @throws \EE_Error
1259
+	 */
1260
+	public function set_deleted($deleted)
1261
+	{
1262
+		$this->set('TKT_deleted', $deleted);
1263
+	}
1264
+
1265
+
1266
+	/**
1267
+	 * Gets parent
1268
+	 *
1269
+	 * @return int
1270
+	 * @throws \EE_Error
1271
+	 */
1272
+	public function parent_ID()
1273
+	{
1274
+		return $this->get('TKT_parent');
1275
+	}
1276
+
1277
+
1278
+	/**
1279
+	 * Sets parent
1280
+	 *
1281
+	 * @param int $parent
1282
+	 * @return void
1283
+	 * @throws \EE_Error
1284
+	 */
1285
+	public function set_parent_ID($parent)
1286
+	{
1287
+		$this->set('TKT_parent', $parent);
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * Gets a string which is handy for showing in gateways etc that describes the ticket.
1293
+	 *
1294
+	 * @return string
1295
+	 * @throws \EE_Error
1296
+	 */
1297
+	public function name_and_info()
1298
+	{
1299
+		$times = array();
1300
+		foreach ($this->datetimes() as $datetime) {
1301
+			$times[] = $datetime->start_date_and_time();
1302
+		}
1303
+		return $this->name() . ' @ ' . implode(', ', $times) . ' for ' . $this->pretty_price();
1304
+	}
1305
+
1306
+
1307
+	/**
1308
+	 * Gets name
1309
+	 *
1310
+	 * @return string
1311
+	 * @throws \EE_Error
1312
+	 */
1313
+	public function name()
1314
+	{
1315
+		return $this->get('TKT_name');
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * Gets price
1321
+	 *
1322
+	 * @return float
1323
+	 * @throws \EE_Error
1324
+	 */
1325
+	public function price()
1326
+	{
1327
+		return $this->get('TKT_price');
1328
+	}
1329
+
1330
+
1331
+	/**
1332
+	 * Gets all the registrations for this ticket
1333
+	 *
1334
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1335
+	 * @return EE_Registration[]|EE_Base_Class[]
1336
+	 * @throws \EE_Error
1337
+	 */
1338
+	public function registrations($query_params = array())
1339
+	{
1340
+		return $this->get_many_related('Registration', $query_params);
1341
+	}
1342
+
1343
+
1344
+	/**
1345
+	 * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1346
+	 * into account
1347
+	 *
1348
+	 * @return int
1349
+	 * @throws \EE_Error
1350
+	 */
1351
+	public function update_tickets_sold()
1352
+	{
1353
+		$count_regs_for_this_ticket = $this->count_registrations(
1354
+			array(
1355
+				array(
1356
+					'STS_ID'      => EEM_Registration::status_id_approved,
1357
+					'REG_deleted' => 0,
1358
+				),
1359
+			)
1360
+		);
1361
+		$sold = $this->sold();
1362
+		if ($count_regs_for_this_ticket > $sold) {
1363
+			$this->increase_sold($count_regs_for_this_ticket - $sold);
1364
+			$this->save();
1365
+		} elseif ($count_regs_for_this_ticket < $sold) {
1366
+			$this->decrease_sold($count_regs_for_this_ticket - $sold);
1367
+			$this->save();
1368
+		}
1369
+		return $count_regs_for_this_ticket;
1370
+	}
1371
+
1372
+
1373
+	/**
1374
+	 * Counts the registrations for this ticket
1375
+	 *
1376
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1377
+	 * @return int
1378
+	 */
1379
+	public function count_registrations($query_params = array())
1380
+	{
1381
+		return $this->count_related('Registration', $query_params);
1382
+	}
1383
+
1384
+
1385
+	/**
1386
+	 * Implementation for EEI_Has_Icon interface method.
1387
+	 *
1388
+	 * @see EEI_Visual_Representation for comments
1389
+	 * @return string
1390
+	 */
1391
+	public function get_icon()
1392
+	{
1393
+		return '<span class="dashicons dashicons-tickets-alt"></span>';
1394
+	}
1395
+
1396
+
1397
+	/**
1398
+	 * Implementation of the EEI_Event_Relation interface method
1399
+	 *
1400
+	 * @see EEI_Event_Relation for comments
1401
+	 * @return EE_Event
1402
+	 * @throws \EE_Error
1403
+	 * @throws UnexpectedEntityException
1404
+	 */
1405
+	public function get_related_event()
1406
+	{
1407
+		// get one datetime to use for getting the event
1408
+		$datetime = $this->first_datetime();
1409
+		if (! $datetime instanceof \EE_Datetime) {
1410
+			throw new UnexpectedEntityException(
1411
+				$datetime,
1412
+				'EE_Datetime',
1413
+				sprintf(
1414
+					__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1415
+					$this->name()
1416
+				)
1417
+			);
1418
+		}
1419
+		$event = $datetime->event();
1420
+		if (! $event instanceof \EE_Event) {
1421
+			throw new UnexpectedEntityException(
1422
+				$event,
1423
+				'EE_Event',
1424
+				sprintf(
1425
+					__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1426
+					$this->name()
1427
+				)
1428
+			);
1429
+		}
1430
+		return $event;
1431
+	}
1432
+
1433
+
1434
+	/**
1435
+	 * Implementation of the EEI_Event_Relation interface method
1436
+	 *
1437
+	 * @see EEI_Event_Relation for comments
1438
+	 * @return string
1439
+	 * @throws UnexpectedEntityException
1440
+	 * @throws \EE_Error
1441
+	 */
1442
+	public function get_event_name()
1443
+	{
1444
+		$event = $this->get_related_event();
1445
+		return $event instanceof EE_Event ? $event->name() : '';
1446
+	}
1447
+
1448
+
1449
+	/**
1450
+	 * Implementation of the EEI_Event_Relation interface method
1451
+	 *
1452
+	 * @see EEI_Event_Relation for comments
1453
+	 * @return int
1454
+	 * @throws UnexpectedEntityException
1455
+	 * @throws \EE_Error
1456
+	 */
1457
+	public function get_event_ID()
1458
+	{
1459
+		$event = $this->get_related_event();
1460
+		return $event instanceof EE_Event ? $event->ID() : 0;
1461
+	}
1462
+
1463
+
1464
+	/**
1465
+	 * This simply returns whether a ticket can be permanently deleted or not.
1466
+	 * The criteria for determining this is whether the ticket has any related registrations.
1467
+	 * If there are none then it can be permanently deleted.
1468
+	 *
1469
+	 * @return bool
1470
+	 */
1471
+	public function is_permanently_deleteable()
1472
+	{
1473
+		return $this->count_registrations() === 0;
1474
+	}
1475 1475
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 1 patch
Indentation   +1351 added lines, -1351 removed lines patch added patch discarded remove patch
@@ -13,1355 +13,1355 @@
 block discarded – undo
13 13
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
14 14
 {
15 15
 
16
-    /**
17
-     * cached value for the the logical active status for the event
18
-     *
19
-     * @see get_active_status()
20
-     * @var string
21
-     */
22
-    protected $_active_status = '';
23
-
24
-    /**
25
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
26
-     *
27
-     * @var EE_Datetime
28
-     */
29
-    protected $_Primary_Datetime;
30
-
31
-    /**
32
-     * @var EventSpacesCalculator $available_spaces_calculator
33
-     */
34
-    protected $available_spaces_calculator;
35
-
36
-
37
-    /**
38
-     * @param array  $props_n_values          incoming values
39
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
40
-     *                                        used.)
41
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
42
-     *                                        date_format and the second value is the time format
43
-     * @return EE_Event
44
-     * @throws EE_Error
45
-     */
46
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
47
-    {
48
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
49
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
50
-    }
51
-
52
-
53
-    /**
54
-     * @param array  $props_n_values  incoming values from the database
55
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
56
-     *                                the website will be used.
57
-     * @return EE_Event
58
-     * @throws EE_Error
59
-     */
60
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
61
-    {
62
-        return new self($props_n_values, true, $timezone);
63
-    }
64
-
65
-
66
-    /**
67
-     * @return EventSpacesCalculator
68
-     * @throws \EE_Error
69
-     */
70
-    public function getAvailableSpacesCalculator()
71
-    {
72
-        if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
73
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
74
-        }
75
-        return $this->available_spaces_calculator;
76
-    }
77
-
78
-
79
-    /**
80
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
81
-     *
82
-     * @param string $field_name
83
-     * @param mixed  $field_value
84
-     * @param bool   $use_default
85
-     * @throws EE_Error
86
-     */
87
-    public function set($field_name, $field_value, $use_default = false)
88
-    {
89
-        switch ($field_name) {
90
-            case 'status':
91
-                $this->set_status($field_value, $use_default);
92
-                break;
93
-            default:
94
-                parent::set($field_name, $field_value, $use_default);
95
-        }
96
-    }
97
-
98
-
99
-    /**
100
-     *    set_status
101
-     * Checks if event status is being changed to SOLD OUT
102
-     * and updates event meta data with previous event status
103
-     * so that we can revert things if/when the event is no longer sold out
104
-     *
105
-     * @access public
106
-     * @param string $new_status
107
-     * @param bool   $use_default
108
-     * @return void
109
-     * @throws EE_Error
110
-     */
111
-    public function set_status($new_status = null, $use_default = false)
112
-    {
113
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
114
-        if (empty($new_status) && ! $use_default) {
115
-            return;
116
-        }
117
-        // get current Event status
118
-        $old_status = $this->status();
119
-        // if status has changed
120
-        if ($old_status !== $new_status) {
121
-            // TO sold_out
122
-            if ($new_status === EEM_Event::sold_out) {
123
-                // save the previous event status so that we can revert if the event is no longer sold out
124
-                $this->add_post_meta('_previous_event_status', $old_status);
125
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
126
-                // OR FROM  sold_out
127
-            } elseif ($old_status === EEM_Event::sold_out) {
128
-                $this->delete_post_meta('_previous_event_status');
129
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
130
-            }
131
-            // clear out the active status so that it gets reset the next time it is requested
132
-            $this->_active_status = null;
133
-            // update status
134
-            parent::set('status', $new_status, $use_default);
135
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
136
-            return;
137
-        }
138
-        // even though the old value matches the new value, it's still good to
139
-        // allow the parent set method to have a say
140
-        parent::set('status', $new_status, $use_default);
141
-    }
142
-
143
-
144
-    /**
145
-     * Gets all the datetimes for this event
146
-     *
147
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
148
-     * @return EE_Base_Class[]|EE_Datetime[]
149
-     * @throws EE_Error
150
-     */
151
-    public function datetimes($query_params = array())
152
-    {
153
-        return $this->get_many_related('Datetime', $query_params);
154
-    }
155
-
156
-
157
-    /**
158
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
159
-     *
160
-     * @return EE_Base_Class[]|EE_Datetime[]
161
-     * @throws EE_Error
162
-     */
163
-    public function datetimes_in_chronological_order()
164
-    {
165
-        return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
166
-    }
167
-
168
-
169
-    /**
170
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
171
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
172
-     * after running our query, so that this timezone isn't set for EVERY query
173
-     * on EEM_Datetime for the rest of the request, no?
174
-     *
175
-     * @param boolean $show_expired whether or not to include expired events
176
-     * @param boolean $show_deleted whether or not to include deleted events
177
-     * @param null    $limit
178
-     * @return EE_Datetime[]
179
-     * @throws EE_Error
180
-     */
181
-    public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
182
-    {
183
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
184
-            $this->ID(),
185
-            $show_expired,
186
-            $show_deleted,
187
-            $limit
188
-        );
189
-    }
190
-
191
-
192
-    /**
193
-     * Returns one related datetime. Mostly only used by some legacy code.
194
-     *
195
-     * @return EE_Base_Class|EE_Datetime
196
-     * @throws EE_Error
197
-     */
198
-    public function first_datetime()
199
-    {
200
-        return $this->get_first_related('Datetime');
201
-    }
202
-
203
-
204
-    /**
205
-     * Returns the 'primary' datetime for the event
206
-     *
207
-     * @param bool $try_to_exclude_expired
208
-     * @param bool $try_to_exclude_deleted
209
-     * @return EE_Datetime
210
-     * @throws EE_Error
211
-     */
212
-    public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
213
-    {
214
-        if (! empty($this->_Primary_Datetime)) {
215
-            return $this->_Primary_Datetime;
216
-        }
217
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
218
-            $this->ID(),
219
-            $try_to_exclude_expired,
220
-            $try_to_exclude_deleted
221
-        );
222
-        return $this->_Primary_Datetime;
223
-    }
224
-
225
-
226
-    /**
227
-     * Gets all the tickets available for purchase of this event
228
-     *
229
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
230
-     * @return EE_Base_Class[]|EE_Ticket[]
231
-     * @throws EE_Error
232
-     */
233
-    public function tickets($query_params = array())
234
-    {
235
-        // first get all datetimes
236
-        $datetimes = $this->datetimes_ordered();
237
-        if (! $datetimes) {
238
-            return array();
239
-        }
240
-        $datetime_ids = array();
241
-        foreach ($datetimes as $datetime) {
242
-            $datetime_ids[] = $datetime->ID();
243
-        }
244
-        $where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
245
-        // if incoming $query_params has where conditions let's merge but not override existing.
246
-        if (is_array($query_params) && isset($query_params[0])) {
247
-            $where_params = array_merge($query_params[0], $where_params);
248
-            unset($query_params[0]);
249
-        }
250
-        // now add $where_params to $query_params
251
-        $query_params[0] = $where_params;
252
-        return EEM_Ticket::instance()->get_all($query_params);
253
-    }
254
-
255
-
256
-    /**
257
-     * get all unexpired untrashed tickets
258
-     *
259
-     * @return EE_Ticket[]
260
-     * @throws EE_Error
261
-     */
262
-    public function active_tickets()
263
-    {
264
-        return $this->tickets(
265
-            array(
266
-                array(
267
-                    'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
268
-                    'TKT_deleted'  => false,
269
-                ),
270
-            )
271
-        );
272
-    }
273
-
274
-
275
-    /**
276
-     * @return bool
277
-     * @throws EE_Error
278
-     */
279
-    public function additional_limit()
280
-    {
281
-        return $this->get('EVT_additional_limit');
282
-    }
283
-
284
-
285
-    /**
286
-     * @return bool
287
-     * @throws EE_Error
288
-     */
289
-    public function allow_overflow()
290
-    {
291
-        return $this->get('EVT_allow_overflow');
292
-    }
293
-
294
-
295
-    /**
296
-     * @return bool
297
-     * @throws EE_Error
298
-     */
299
-    public function created()
300
-    {
301
-        return $this->get('EVT_created');
302
-    }
303
-
304
-
305
-    /**
306
-     * @return bool
307
-     * @throws EE_Error
308
-     */
309
-    public function description()
310
-    {
311
-        return $this->get('EVT_desc');
312
-    }
313
-
314
-
315
-    /**
316
-     * Runs do_shortcode and wpautop on the description
317
-     *
318
-     * @return string of html
319
-     * @throws EE_Error
320
-     */
321
-    public function description_filtered()
322
-    {
323
-        return $this->get_pretty('EVT_desc');
324
-    }
325
-
326
-
327
-    /**
328
-     * @return bool
329
-     * @throws EE_Error
330
-     */
331
-    public function display_description()
332
-    {
333
-        return $this->get('EVT_display_desc');
334
-    }
335
-
336
-
337
-    /**
338
-     * @return bool
339
-     * @throws EE_Error
340
-     */
341
-    public function display_ticket_selector()
342
-    {
343
-        return (bool) $this->get('EVT_display_ticket_selector');
344
-    }
345
-
346
-
347
-    /**
348
-     * @return bool
349
-     * @throws EE_Error
350
-     */
351
-    public function external_url()
352
-    {
353
-        return $this->get('EVT_external_URL');
354
-    }
355
-
356
-
357
-    /**
358
-     * @return bool
359
-     * @throws EE_Error
360
-     */
361
-    public function member_only()
362
-    {
363
-        return $this->get('EVT_member_only');
364
-    }
365
-
366
-
367
-    /**
368
-     * @return bool
369
-     * @throws EE_Error
370
-     */
371
-    public function phone()
372
-    {
373
-        return $this->get('EVT_phone');
374
-    }
375
-
376
-
377
-    /**
378
-     * @return bool
379
-     * @throws EE_Error
380
-     */
381
-    public function modified()
382
-    {
383
-        return $this->get('EVT_modified');
384
-    }
385
-
386
-
387
-    /**
388
-     * @return bool
389
-     * @throws EE_Error
390
-     */
391
-    public function name()
392
-    {
393
-        return $this->get('EVT_name');
394
-    }
395
-
396
-
397
-    /**
398
-     * @return bool
399
-     * @throws EE_Error
400
-     */
401
-    public function order()
402
-    {
403
-        return $this->get('EVT_order');
404
-    }
405
-
406
-
407
-    /**
408
-     * @return bool|string
409
-     * @throws EE_Error
410
-     */
411
-    public function default_registration_status()
412
-    {
413
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
414
-        return ! empty($event_default_registration_status)
415
-            ? $event_default_registration_status
416
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
417
-    }
418
-
419
-
420
-    /**
421
-     * @param int  $num_words
422
-     * @param null $more
423
-     * @param bool $not_full_desc
424
-     * @return bool|string
425
-     * @throws EE_Error
426
-     */
427
-    public function short_description($num_words = 55, $more = null, $not_full_desc = false)
428
-    {
429
-        $short_desc = $this->get('EVT_short_desc');
430
-        if (! empty($short_desc) || $not_full_desc) {
431
-            return $short_desc;
432
-        }
433
-        $full_desc = $this->get('EVT_desc');
434
-        return wp_trim_words($full_desc, $num_words, $more);
435
-    }
436
-
437
-
438
-    /**
439
-     * @return bool
440
-     * @throws EE_Error
441
-     */
442
-    public function slug()
443
-    {
444
-        return $this->get('EVT_slug');
445
-    }
446
-
447
-
448
-    /**
449
-     * @return bool
450
-     * @throws EE_Error
451
-     */
452
-    public function timezone_string()
453
-    {
454
-        return $this->get('EVT_timezone_string');
455
-    }
456
-
457
-
458
-    /**
459
-     * @return bool
460
-     * @throws EE_Error
461
-     */
462
-    public function visible_on()
463
-    {
464
-        return $this->get('EVT_visible_on');
465
-    }
466
-
467
-
468
-    /**
469
-     * @return int
470
-     * @throws EE_Error
471
-     */
472
-    public function wp_user()
473
-    {
474
-        return $this->get('EVT_wp_user');
475
-    }
476
-
477
-
478
-    /**
479
-     * @return bool
480
-     * @throws EE_Error
481
-     */
482
-    public function donations()
483
-    {
484
-        return $this->get('EVT_donations');
485
-    }
486
-
487
-
488
-    /**
489
-     * @param $limit
490
-     * @throws EE_Error
491
-     */
492
-    public function set_additional_limit($limit)
493
-    {
494
-        $this->set('EVT_additional_limit', $limit);
495
-    }
496
-
497
-
498
-    /**
499
-     * @param $created
500
-     * @throws EE_Error
501
-     */
502
-    public function set_created($created)
503
-    {
504
-        $this->set('EVT_created', $created);
505
-    }
506
-
507
-
508
-    /**
509
-     * @param $desc
510
-     * @throws EE_Error
511
-     */
512
-    public function set_description($desc)
513
-    {
514
-        $this->set('EVT_desc', $desc);
515
-    }
516
-
517
-
518
-    /**
519
-     * @param $display_desc
520
-     * @throws EE_Error
521
-     */
522
-    public function set_display_description($display_desc)
523
-    {
524
-        $this->set('EVT_display_desc', $display_desc);
525
-    }
526
-
527
-
528
-    /**
529
-     * @param $display_ticket_selector
530
-     * @throws EE_Error
531
-     */
532
-    public function set_display_ticket_selector($display_ticket_selector)
533
-    {
534
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
535
-    }
536
-
537
-
538
-    /**
539
-     * @param $external_url
540
-     * @throws EE_Error
541
-     */
542
-    public function set_external_url($external_url)
543
-    {
544
-        $this->set('EVT_external_URL', $external_url);
545
-    }
546
-
547
-
548
-    /**
549
-     * @param $member_only
550
-     * @throws EE_Error
551
-     */
552
-    public function set_member_only($member_only)
553
-    {
554
-        $this->set('EVT_member_only', $member_only);
555
-    }
556
-
557
-
558
-    /**
559
-     * @param $event_phone
560
-     * @throws EE_Error
561
-     */
562
-    public function set_event_phone($event_phone)
563
-    {
564
-        $this->set('EVT_phone', $event_phone);
565
-    }
566
-
567
-
568
-    /**
569
-     * @param $modified
570
-     * @throws EE_Error
571
-     */
572
-    public function set_modified($modified)
573
-    {
574
-        $this->set('EVT_modified', $modified);
575
-    }
576
-
577
-
578
-    /**
579
-     * @param $name
580
-     * @throws EE_Error
581
-     */
582
-    public function set_name($name)
583
-    {
584
-        $this->set('EVT_name', $name);
585
-    }
586
-
587
-
588
-    /**
589
-     * @param $order
590
-     * @throws EE_Error
591
-     */
592
-    public function set_order($order)
593
-    {
594
-        $this->set('EVT_order', $order);
595
-    }
596
-
597
-
598
-    /**
599
-     * @param $short_desc
600
-     * @throws EE_Error
601
-     */
602
-    public function set_short_description($short_desc)
603
-    {
604
-        $this->set('EVT_short_desc', $short_desc);
605
-    }
606
-
607
-
608
-    /**
609
-     * @param $slug
610
-     * @throws EE_Error
611
-     */
612
-    public function set_slug($slug)
613
-    {
614
-        $this->set('EVT_slug', $slug);
615
-    }
616
-
617
-
618
-    /**
619
-     * @param $timezone_string
620
-     * @throws EE_Error
621
-     */
622
-    public function set_timezone_string($timezone_string)
623
-    {
624
-        $this->set('EVT_timezone_string', $timezone_string);
625
-    }
626
-
627
-
628
-    /**
629
-     * @param $visible_on
630
-     * @throws EE_Error
631
-     */
632
-    public function set_visible_on($visible_on)
633
-    {
634
-        $this->set('EVT_visible_on', $visible_on);
635
-    }
636
-
637
-
638
-    /**
639
-     * @param $wp_user
640
-     * @throws EE_Error
641
-     */
642
-    public function set_wp_user($wp_user)
643
-    {
644
-        $this->set('EVT_wp_user', $wp_user);
645
-    }
646
-
647
-
648
-    /**
649
-     * @param $default_registration_status
650
-     * @throws EE_Error
651
-     */
652
-    public function set_default_registration_status($default_registration_status)
653
-    {
654
-        $this->set('EVT_default_registration_status', $default_registration_status);
655
-    }
656
-
657
-
658
-    /**
659
-     * @param $donations
660
-     * @throws EE_Error
661
-     */
662
-    public function set_donations($donations)
663
-    {
664
-        $this->set('EVT_donations', $donations);
665
-    }
666
-
667
-
668
-    /**
669
-     * Adds a venue to this event
670
-     *
671
-     * @param EE_Venue /int $venue_id_or_obj
672
-     * @return EE_Base_Class|EE_Venue
673
-     * @throws EE_Error
674
-     */
675
-    public function add_venue($venue_id_or_obj)
676
-    {
677
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
678
-    }
679
-
680
-
681
-    /**
682
-     * Removes a venue from the event
683
-     *
684
-     * @param EE_Venue /int $venue_id_or_obj
685
-     * @return EE_Base_Class|EE_Venue
686
-     * @throws EE_Error
687
-     */
688
-    public function remove_venue($venue_id_or_obj)
689
-    {
690
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
691
-    }
692
-
693
-
694
-    /**
695
-     * Gets all the venues related ot the event. May provide additional $query_params if desired
696
-     *
697
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
698
-     * @return EE_Base_Class[]|EE_Venue[]
699
-     * @throws EE_Error
700
-     */
701
-    public function venues($query_params = array())
702
-    {
703
-        return $this->get_many_related('Venue', $query_params);
704
-    }
705
-
706
-
707
-    /**
708
-     * check if event id is present and if event is published
709
-     *
710
-     * @access public
711
-     * @return boolean true yes, false no
712
-     * @throws EE_Error
713
-     */
714
-    private function _has_ID_and_is_published()
715
-    {
716
-        // first check if event id is present and not NULL,
717
-        // then check if this event is published (or any of the equivalent "published" statuses)
718
-        return
719
-            $this->ID() && $this->ID() !== null
720
-            && (
721
-                $this->status() === 'publish'
722
-                || $this->status() === EEM_Event::sold_out
723
-                || $this->status() === EEM_Event::postponed
724
-                || $this->status() === EEM_Event::cancelled
725
-            );
726
-    }
727
-
728
-
729
-    /**
730
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
731
-     *
732
-     * @access public
733
-     * @return boolean true yes, false no
734
-     * @throws EE_Error
735
-     */
736
-    public function is_upcoming()
737
-    {
738
-        // check if event id is present and if this event is published
739
-        if ($this->is_inactive()) {
740
-            return false;
741
-        }
742
-        // set initial value
743
-        $upcoming = false;
744
-        // next let's get all datetimes and loop through them
745
-        $datetimes = $this->datetimes_in_chronological_order();
746
-        foreach ($datetimes as $datetime) {
747
-            if ($datetime instanceof EE_Datetime) {
748
-                // if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
749
-                if ($datetime->is_expired()) {
750
-                    continue;
751
-                }
752
-                // if this dtt is active then we return false.
753
-                if ($datetime->is_active()) {
754
-                    return false;
755
-                }
756
-                // otherwise let's check upcoming status
757
-                $upcoming = $datetime->is_upcoming();
758
-            }
759
-        }
760
-        return $upcoming;
761
-    }
762
-
763
-
764
-    /**
765
-     * @return bool
766
-     * @throws EE_Error
767
-     */
768
-    public function is_active()
769
-    {
770
-        // check if event id is present and if this event is published
771
-        if ($this->is_inactive()) {
772
-            return false;
773
-        }
774
-        // set initial value
775
-        $active = false;
776
-        // next let's get all datetimes and loop through them
777
-        $datetimes = $this->datetimes_in_chronological_order();
778
-        foreach ($datetimes as $datetime) {
779
-            if ($datetime instanceof EE_Datetime) {
780
-                // if this dtt is expired then we continue cause one of the other datetimes might be active.
781
-                if ($datetime->is_expired()) {
782
-                    continue;
783
-                }
784
-                // if this dtt is upcoming then we return false.
785
-                if ($datetime->is_upcoming()) {
786
-                    return false;
787
-                }
788
-                // otherwise let's check active status
789
-                $active = $datetime->is_active();
790
-            }
791
-        }
792
-        return $active;
793
-    }
794
-
795
-
796
-    /**
797
-     * @return bool
798
-     * @throws EE_Error
799
-     */
800
-    public function is_expired()
801
-    {
802
-        // check if event id is present and if this event is published
803
-        if ($this->is_inactive()) {
804
-            return false;
805
-        }
806
-        // set initial value
807
-        $expired = false;
808
-        // first let's get all datetimes and loop through them
809
-        $datetimes = $this->datetimes_in_chronological_order();
810
-        foreach ($datetimes as $datetime) {
811
-            if ($datetime instanceof EE_Datetime) {
812
-                // if this dtt is upcoming or active then we return false.
813
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
814
-                    return false;
815
-                }
816
-                // otherwise let's check active status
817
-                $expired = $datetime->is_expired();
818
-            }
819
-        }
820
-        return $expired;
821
-    }
822
-
823
-
824
-    /**
825
-     * @return bool
826
-     * @throws EE_Error
827
-     */
828
-    public function is_inactive()
829
-    {
830
-        // check if event id is present and if this event is published
831
-        if ($this->_has_ID_and_is_published()) {
832
-            return false;
833
-        }
834
-        return true;
835
-    }
836
-
837
-
838
-    /**
839
-     * calculate spaces remaining based on "saleable" tickets
840
-     *
841
-     * @param array $tickets
842
-     * @param bool  $filtered
843
-     * @return int|float
844
-     * @throws EE_Error
845
-     * @throws DomainException
846
-     * @throws UnexpectedEntityException
847
-     */
848
-    public function spaces_remaining($tickets = array(), $filtered = true)
849
-    {
850
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
851
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
852
-        return $filtered
853
-            ? apply_filters(
854
-                'FHEE_EE_Event__spaces_remaining',
855
-                $spaces_remaining,
856
-                $this,
857
-                $tickets
858
-            )
859
-            : $spaces_remaining;
860
-    }
861
-
862
-
863
-    /**
864
-     *    perform_sold_out_status_check
865
-     *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
866
-     *    available... if NOT, then the event status will get toggled to 'sold_out'
867
-     *
868
-     * @return bool    return the ACTUAL sold out state.
869
-     * @throws EE_Error
870
-     * @throws DomainException
871
-     * @throws UnexpectedEntityException
872
-     */
873
-    public function perform_sold_out_status_check()
874
-    {
875
-        // get all unexpired untrashed tickets
876
-        $tickets = $this->tickets(
877
-            array(
878
-                array('TKT_deleted' => false),
879
-                'order_by' => array('TKT_qty' => 'ASC'),
880
-            )
881
-        );
882
-        $all_expired = true;
883
-        foreach ($tickets as $ticket) {
884
-            if (! $ticket->is_expired()) {
885
-                $all_expired = false;
886
-                break;
887
-            }
888
-        }
889
-        // if all the tickets are just expired, then don't update the event status to sold out
890
-        if ($all_expired) {
891
-            return true;
892
-        }
893
-        $spaces_remaining = $this->spaces_remaining($tickets);
894
-        if ($spaces_remaining < 1) {
895
-            $this->set_status(EEM_Event::sold_out);
896
-            $this->save();
897
-            $sold_out = true;
898
-        } else {
899
-            $sold_out = false;
900
-            // was event previously marked as sold out ?
901
-            if ($this->status() === EEM_Event::sold_out) {
902
-                // revert status to previous value, if it was set
903
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
904
-                if ($previous_event_status) {
905
-                    $this->set_status($previous_event_status);
906
-                    $this->save();
907
-                }
908
-            }
909
-        }
910
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
911
-        return $sold_out;
912
-    }
913
-
914
-
915
-    /**
916
-     * This returns the total remaining spaces for sale on this event.
917
-     *
918
-     * @uses EE_Event::total_available_spaces()
919
-     * @return float|int
920
-     * @throws EE_Error
921
-     * @throws DomainException
922
-     * @throws UnexpectedEntityException
923
-     */
924
-    public function spaces_remaining_for_sale()
925
-    {
926
-        return $this->total_available_spaces(true);
927
-    }
928
-
929
-
930
-    /**
931
-     * This returns the total spaces available for an event
932
-     * while considering all the qtys on the tickets and the reg limits
933
-     * on the datetimes attached to this event.
934
-     *
935
-     * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
936
-     *                              If this is false, then we return the most tickets that could ever be sold
937
-     *                              for this event with the datetime and tickets setup on the event under optimal
938
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
939
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
940
-     *                              may appear to equal remaining tickets.  However, the more tickets are
941
-     *                              sold out, the more accurate the "live" total is.
942
-     * @return float|int
943
-     * @throws EE_Error
944
-     * @throws DomainException
945
-     * @throws UnexpectedEntityException
946
-     */
947
-    public function total_available_spaces($consider_sold = false)
948
-    {
949
-        $spaces_available = $consider_sold
950
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
951
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
952
-        return apply_filters(
953
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
954
-            $spaces_available,
955
-            $this,
956
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
957
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
958
-        );
959
-    }
960
-
961
-
962
-    /**
963
-     * Checks if the event is set to sold out
964
-     *
965
-     * @param  bool $actual whether or not to perform calculations to not only figure the
966
-     *                      actual status but also to flip the status if necessary to sold
967
-     *                      out If false, we just check the existing status of the event
968
-     * @return boolean
969
-     * @throws EE_Error
970
-     */
971
-    public function is_sold_out($actual = false)
972
-    {
973
-        if (! $actual) {
974
-            return $this->status() === EEM_Event::sold_out;
975
-        }
976
-        return $this->perform_sold_out_status_check();
977
-    }
978
-
979
-
980
-    /**
981
-     * Checks if the event is marked as postponed
982
-     *
983
-     * @return boolean
984
-     */
985
-    public function is_postponed()
986
-    {
987
-        return $this->status() === EEM_Event::postponed;
988
-    }
989
-
990
-
991
-    /**
992
-     * Checks if the event is marked as cancelled
993
-     *
994
-     * @return boolean
995
-     */
996
-    public function is_cancelled()
997
-    {
998
-        return $this->status() === EEM_Event::cancelled;
999
-    }
1000
-
1001
-
1002
-    /**
1003
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
1004
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1005
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1006
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1007
-     * the event is considered expired.
1008
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1009
-     * status set on the EVENT when it is not published and thus is done
1010
-     *
1011
-     * @param bool $reset
1012
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1013
-     * @throws EE_Error
1014
-     */
1015
-    public function get_active_status($reset = false)
1016
-    {
1017
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1018
-        if (! empty($this->_active_status) && ! $reset) {
1019
-            return $this->_active_status;
1020
-        }
1021
-        // first check if event id is present on this object
1022
-        if (! $this->ID()) {
1023
-            return false;
1024
-        }
1025
-        $where_params_for_event = array(array('EVT_ID' => $this->ID()));
1026
-        // if event is published:
1027
-        if ($this->status() === 'publish') {
1028
-            // active?
1029
-            if (EEM_Datetime::instance()->get_datetime_count_for_status(
1030
-                EE_Datetime::active,
1031
-                $where_params_for_event
1032
-            ) > 0) {
1033
-                $this->_active_status = EE_Datetime::active;
1034
-            } else {
1035
-                // upcoming?
1036
-                if (EEM_Datetime::instance()->get_datetime_count_for_status(
1037
-                    EE_Datetime::upcoming,
1038
-                    $where_params_for_event
1039
-                ) > 0) {
1040
-                    $this->_active_status = EE_Datetime::upcoming;
1041
-                } else {
1042
-                    // expired?
1043
-                    if (EEM_Datetime::instance()->get_datetime_count_for_status(
1044
-                        EE_Datetime::expired,
1045
-                        $where_params_for_event
1046
-                    ) > 0
1047
-                    ) {
1048
-                        $this->_active_status = EE_Datetime::expired;
1049
-                    } else {
1050
-                        // it would be odd if things make it this far because it basically means there are no datetime's
1051
-                        // attached to the event.  So in this case it will just be considered inactive.
1052
-                        $this->_active_status = EE_Datetime::inactive;
1053
-                    }
1054
-                }
1055
-            }
1056
-        } else {
1057
-            // the event is not published, so let's just set it's active status according to its' post status
1058
-            switch ($this->status()) {
1059
-                case EEM_Event::sold_out:
1060
-                    $this->_active_status = EE_Datetime::sold_out;
1061
-                    break;
1062
-                case EEM_Event::cancelled:
1063
-                    $this->_active_status = EE_Datetime::cancelled;
1064
-                    break;
1065
-                case EEM_Event::postponed:
1066
-                    $this->_active_status = EE_Datetime::postponed;
1067
-                    break;
1068
-                default:
1069
-                    $this->_active_status = EE_Datetime::inactive;
1070
-            }
1071
-        }
1072
-        return $this->_active_status;
1073
-    }
1074
-
1075
-
1076
-    /**
1077
-     *    pretty_active_status
1078
-     *
1079
-     * @access public
1080
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1081
-     * @return mixed void|string
1082
-     * @throws EE_Error
1083
-     */
1084
-    public function pretty_active_status($echo = true)
1085
-    {
1086
-        $active_status = $this->get_active_status();
1087
-        $status = '<span class="ee-status event-active-status-'
1088
-                  . $active_status
1089
-                  . '">'
1090
-                  . EEH_Template::pretty_status($active_status, false, 'sentence')
1091
-                  . '</span>';
1092
-        if ($echo) {
1093
-            echo $status;
1094
-            return '';
1095
-        }
1096
-        return $status;
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     * @return bool|int
1102
-     * @throws EE_Error
1103
-     */
1104
-    public function get_number_of_tickets_sold()
1105
-    {
1106
-        $tkt_sold = 0;
1107
-        if (! $this->ID()) {
1108
-            return 0;
1109
-        }
1110
-        $datetimes = $this->datetimes();
1111
-        foreach ($datetimes as $datetime) {
1112
-            if ($datetime instanceof EE_Datetime) {
1113
-                $tkt_sold += $datetime->sold();
1114
-            }
1115
-        }
1116
-        return $tkt_sold;
1117
-    }
1118
-
1119
-
1120
-    /**
1121
-     * This just returns a count of all the registrations for this event
1122
-     *
1123
-     * @access  public
1124
-     * @return int
1125
-     * @throws EE_Error
1126
-     */
1127
-    public function get_count_of_all_registrations()
1128
-    {
1129
-        return EEM_Event::instance()->count_related($this, 'Registration');
1130
-    }
1131
-
1132
-
1133
-    /**
1134
-     * This returns the ticket with the earliest start time that is
1135
-     * available for this event (across all datetimes attached to the event)
1136
-     *
1137
-     * @return EE_Base_Class|EE_Ticket|null
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function get_ticket_with_earliest_start_time()
1141
-    {
1142
-        $where['Datetime.EVT_ID'] = $this->ID();
1143
-        $query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1144
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
-    }
1146
-
1147
-
1148
-    /**
1149
-     * This returns the ticket with the latest end time that is available
1150
-     * for this event (across all datetimes attached to the event)
1151
-     *
1152
-     * @return EE_Base_Class|EE_Ticket|null
1153
-     * @throws EE_Error
1154
-     */
1155
-    public function get_ticket_with_latest_end_time()
1156
-    {
1157
-        $where['Datetime.EVT_ID'] = $this->ID();
1158
-        $query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1159
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * This returns the number of different ticket types currently on sale for this event.
1165
-     *
1166
-     * @return int
1167
-     * @throws EE_Error
1168
-     */
1169
-    public function countTicketsOnSale()
1170
-    {
1171
-        $where = array(
1172
-            'Datetime.EVT_ID' => $this->ID(),
1173
-            'TKT_start_date'  => array('<', time()),
1174
-            'TKT_end_date'    => array('>', time()),
1175
-        );
1176
-        return EEM_Ticket::instance()->count(array($where));
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * This returns whether there are any tickets on sale for this event.
1182
-     *
1183
-     * @return bool true = YES tickets on sale.
1184
-     * @throws EE_Error
1185
-     */
1186
-    public function tickets_on_sale()
1187
-    {
1188
-        return $this->countTicketsOnSale() > 0;
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1194
-     * to check for an external URL first
1195
-     *
1196
-     * @return string
1197
-     * @throws EE_Error
1198
-     */
1199
-    public function get_permalink()
1200
-    {
1201
-        if ($this->external_url()) {
1202
-            return $this->external_url();
1203
-        }
1204
-        return parent::get_permalink();
1205
-    }
1206
-
1207
-
1208
-    /**
1209
-     * Gets the first term for 'espresso_event_categories' we can find
1210
-     *
1211
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1212
-     * @return EE_Base_Class|EE_Term|null
1213
-     * @throws EE_Error
1214
-     */
1215
-    public function first_event_category($query_params = array())
1216
-    {
1217
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1218
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1219
-        return EEM_Term::instance()->get_one($query_params);
1220
-    }
1221
-
1222
-
1223
-    /**
1224
-     * Gets all terms for 'espresso_event_categories' we can find
1225
-     *
1226
-     * @param array $query_params
1227
-     * @return EE_Base_Class[]|EE_Term[]
1228
-     * @throws EE_Error
1229
-     */
1230
-    public function get_all_event_categories($query_params = array())
1231
-    {
1232
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1233
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1234
-        return EEM_Term::instance()->get_all($query_params);
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     * Adds a question group to this event
1240
-     *
1241
-     * @param EE_Question_Group|int $question_group_id_or_obj
1242
-     * @param bool                  $for_primary if true, the question group will be added for the primary
1243
-     *                                           registrant, if false will be added for others. default: false
1244
-     * @return EE_Base_Class|EE_Question_Group
1245
-     * @throws EE_Error
1246
-     */
1247
-    public function add_question_group($question_group_id_or_obj, $for_primary = false)
1248
-    {
1249
-        $extra = $for_primary
1250
-            ? array('EQG_primary' => 1)
1251
-            : array();
1252
-        return $this->_add_relation_to($question_group_id_or_obj, 'Question_Group', $extra);
1253
-    }
1254
-
1255
-
1256
-    /**
1257
-     * Removes a question group from the event
1258
-     *
1259
-     * @param EE_Question_Group|int $question_group_id_or_obj
1260
-     * @param bool                  $for_primary if true, the question group will be removed from the primary
1261
-     *                                           registrant, if false will be removed from others. default: false
1262
-     * @return EE_Base_Class|EE_Question_Group
1263
-     * @throws EE_Error
1264
-     */
1265
-    public function remove_question_group($question_group_id_or_obj, $for_primary = false)
1266
-    {
1267
-        $where = $for_primary
1268
-            ? array('EQG_primary' => 1)
1269
-            : array();
1270
-        return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group', $where);
1271
-    }
1272
-
1273
-
1274
-    /**
1275
-     * Gets all the question groups, ordering them by QSG_order ascending
1276
-     *
1277
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1278
-     * @return EE_Base_Class[]|EE_Question_Group[]
1279
-     * @throws EE_Error
1280
-     */
1281
-    public function question_groups($query_params = array())
1282
-    {
1283
-        $query_params = ! empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1284
-        return $this->get_many_related('Question_Group', $query_params);
1285
-    }
1286
-
1287
-
1288
-    /**
1289
-     * Implementation for EEI_Has_Icon interface method.
1290
-     *
1291
-     * @see EEI_Visual_Representation for comments
1292
-     * @return string
1293
-     */
1294
-    public function get_icon()
1295
-    {
1296
-        return '<span class="dashicons dashicons-flag"></span>';
1297
-    }
1298
-
1299
-
1300
-    /**
1301
-     * Implementation for EEI_Admin_Links interface method.
1302
-     *
1303
-     * @see EEI_Admin_Links for comments
1304
-     * @return string
1305
-     * @throws EE_Error
1306
-     */
1307
-    public function get_admin_details_link()
1308
-    {
1309
-        return $this->get_admin_edit_link();
1310
-    }
1311
-
1312
-
1313
-    /**
1314
-     * Implementation for EEI_Admin_Links interface method.
1315
-     *
1316
-     * @see EEI_Admin_Links for comments
1317
-     * @return string
1318
-     * @throws EE_Error
1319
-     */
1320
-    public function get_admin_edit_link()
1321
-    {
1322
-        return EEH_URL::add_query_args_and_nonce(
1323
-            array(
1324
-                'page'   => 'espresso_events',
1325
-                'action' => 'edit',
1326
-                'post'   => $this->ID(),
1327
-            ),
1328
-            admin_url('admin.php')
1329
-        );
1330
-    }
1331
-
1332
-
1333
-    /**
1334
-     * Implementation for EEI_Admin_Links interface method.
1335
-     *
1336
-     * @see EEI_Admin_Links for comments
1337
-     * @return string
1338
-     */
1339
-    public function get_admin_settings_link()
1340
-    {
1341
-        return EEH_URL::add_query_args_and_nonce(
1342
-            array(
1343
-                'page'   => 'espresso_events',
1344
-                'action' => 'default_event_settings',
1345
-            ),
1346
-            admin_url('admin.php')
1347
-        );
1348
-    }
1349
-
1350
-
1351
-    /**
1352
-     * Implementation for EEI_Admin_Links interface method.
1353
-     *
1354
-     * @see EEI_Admin_Links for comments
1355
-     * @return string
1356
-     */
1357
-    public function get_admin_overview_link()
1358
-    {
1359
-        return EEH_URL::add_query_args_and_nonce(
1360
-            array(
1361
-                'page'   => 'espresso_events',
1362
-                'action' => 'default',
1363
-            ),
1364
-            admin_url('admin.php')
1365
-        );
1366
-    }
16
+	/**
17
+	 * cached value for the the logical active status for the event
18
+	 *
19
+	 * @see get_active_status()
20
+	 * @var string
21
+	 */
22
+	protected $_active_status = '';
23
+
24
+	/**
25
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
26
+	 *
27
+	 * @var EE_Datetime
28
+	 */
29
+	protected $_Primary_Datetime;
30
+
31
+	/**
32
+	 * @var EventSpacesCalculator $available_spaces_calculator
33
+	 */
34
+	protected $available_spaces_calculator;
35
+
36
+
37
+	/**
38
+	 * @param array  $props_n_values          incoming values
39
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
40
+	 *                                        used.)
41
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
42
+	 *                                        date_format and the second value is the time format
43
+	 * @return EE_Event
44
+	 * @throws EE_Error
45
+	 */
46
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
47
+	{
48
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
49
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
50
+	}
51
+
52
+
53
+	/**
54
+	 * @param array  $props_n_values  incoming values from the database
55
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
56
+	 *                                the website will be used.
57
+	 * @return EE_Event
58
+	 * @throws EE_Error
59
+	 */
60
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
61
+	{
62
+		return new self($props_n_values, true, $timezone);
63
+	}
64
+
65
+
66
+	/**
67
+	 * @return EventSpacesCalculator
68
+	 * @throws \EE_Error
69
+	 */
70
+	public function getAvailableSpacesCalculator()
71
+	{
72
+		if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
73
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
74
+		}
75
+		return $this->available_spaces_calculator;
76
+	}
77
+
78
+
79
+	/**
80
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
81
+	 *
82
+	 * @param string $field_name
83
+	 * @param mixed  $field_value
84
+	 * @param bool   $use_default
85
+	 * @throws EE_Error
86
+	 */
87
+	public function set($field_name, $field_value, $use_default = false)
88
+	{
89
+		switch ($field_name) {
90
+			case 'status':
91
+				$this->set_status($field_value, $use_default);
92
+				break;
93
+			default:
94
+				parent::set($field_name, $field_value, $use_default);
95
+		}
96
+	}
97
+
98
+
99
+	/**
100
+	 *    set_status
101
+	 * Checks if event status is being changed to SOLD OUT
102
+	 * and updates event meta data with previous event status
103
+	 * so that we can revert things if/when the event is no longer sold out
104
+	 *
105
+	 * @access public
106
+	 * @param string $new_status
107
+	 * @param bool   $use_default
108
+	 * @return void
109
+	 * @throws EE_Error
110
+	 */
111
+	public function set_status($new_status = null, $use_default = false)
112
+	{
113
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
114
+		if (empty($new_status) && ! $use_default) {
115
+			return;
116
+		}
117
+		// get current Event status
118
+		$old_status = $this->status();
119
+		// if status has changed
120
+		if ($old_status !== $new_status) {
121
+			// TO sold_out
122
+			if ($new_status === EEM_Event::sold_out) {
123
+				// save the previous event status so that we can revert if the event is no longer sold out
124
+				$this->add_post_meta('_previous_event_status', $old_status);
125
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
126
+				// OR FROM  sold_out
127
+			} elseif ($old_status === EEM_Event::sold_out) {
128
+				$this->delete_post_meta('_previous_event_status');
129
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
130
+			}
131
+			// clear out the active status so that it gets reset the next time it is requested
132
+			$this->_active_status = null;
133
+			// update status
134
+			parent::set('status', $new_status, $use_default);
135
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
136
+			return;
137
+		}
138
+		// even though the old value matches the new value, it's still good to
139
+		// allow the parent set method to have a say
140
+		parent::set('status', $new_status, $use_default);
141
+	}
142
+
143
+
144
+	/**
145
+	 * Gets all the datetimes for this event
146
+	 *
147
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
148
+	 * @return EE_Base_Class[]|EE_Datetime[]
149
+	 * @throws EE_Error
150
+	 */
151
+	public function datetimes($query_params = array())
152
+	{
153
+		return $this->get_many_related('Datetime', $query_params);
154
+	}
155
+
156
+
157
+	/**
158
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
159
+	 *
160
+	 * @return EE_Base_Class[]|EE_Datetime[]
161
+	 * @throws EE_Error
162
+	 */
163
+	public function datetimes_in_chronological_order()
164
+	{
165
+		return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
166
+	}
167
+
168
+
169
+	/**
170
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
171
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
172
+	 * after running our query, so that this timezone isn't set for EVERY query
173
+	 * on EEM_Datetime for the rest of the request, no?
174
+	 *
175
+	 * @param boolean $show_expired whether or not to include expired events
176
+	 * @param boolean $show_deleted whether or not to include deleted events
177
+	 * @param null    $limit
178
+	 * @return EE_Datetime[]
179
+	 * @throws EE_Error
180
+	 */
181
+	public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
182
+	{
183
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
184
+			$this->ID(),
185
+			$show_expired,
186
+			$show_deleted,
187
+			$limit
188
+		);
189
+	}
190
+
191
+
192
+	/**
193
+	 * Returns one related datetime. Mostly only used by some legacy code.
194
+	 *
195
+	 * @return EE_Base_Class|EE_Datetime
196
+	 * @throws EE_Error
197
+	 */
198
+	public function first_datetime()
199
+	{
200
+		return $this->get_first_related('Datetime');
201
+	}
202
+
203
+
204
+	/**
205
+	 * Returns the 'primary' datetime for the event
206
+	 *
207
+	 * @param bool $try_to_exclude_expired
208
+	 * @param bool $try_to_exclude_deleted
209
+	 * @return EE_Datetime
210
+	 * @throws EE_Error
211
+	 */
212
+	public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
213
+	{
214
+		if (! empty($this->_Primary_Datetime)) {
215
+			return $this->_Primary_Datetime;
216
+		}
217
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
218
+			$this->ID(),
219
+			$try_to_exclude_expired,
220
+			$try_to_exclude_deleted
221
+		);
222
+		return $this->_Primary_Datetime;
223
+	}
224
+
225
+
226
+	/**
227
+	 * Gets all the tickets available for purchase of this event
228
+	 *
229
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
230
+	 * @return EE_Base_Class[]|EE_Ticket[]
231
+	 * @throws EE_Error
232
+	 */
233
+	public function tickets($query_params = array())
234
+	{
235
+		// first get all datetimes
236
+		$datetimes = $this->datetimes_ordered();
237
+		if (! $datetimes) {
238
+			return array();
239
+		}
240
+		$datetime_ids = array();
241
+		foreach ($datetimes as $datetime) {
242
+			$datetime_ids[] = $datetime->ID();
243
+		}
244
+		$where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
245
+		// if incoming $query_params has where conditions let's merge but not override existing.
246
+		if (is_array($query_params) && isset($query_params[0])) {
247
+			$where_params = array_merge($query_params[0], $where_params);
248
+			unset($query_params[0]);
249
+		}
250
+		// now add $where_params to $query_params
251
+		$query_params[0] = $where_params;
252
+		return EEM_Ticket::instance()->get_all($query_params);
253
+	}
254
+
255
+
256
+	/**
257
+	 * get all unexpired untrashed tickets
258
+	 *
259
+	 * @return EE_Ticket[]
260
+	 * @throws EE_Error
261
+	 */
262
+	public function active_tickets()
263
+	{
264
+		return $this->tickets(
265
+			array(
266
+				array(
267
+					'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
268
+					'TKT_deleted'  => false,
269
+				),
270
+			)
271
+		);
272
+	}
273
+
274
+
275
+	/**
276
+	 * @return bool
277
+	 * @throws EE_Error
278
+	 */
279
+	public function additional_limit()
280
+	{
281
+		return $this->get('EVT_additional_limit');
282
+	}
283
+
284
+
285
+	/**
286
+	 * @return bool
287
+	 * @throws EE_Error
288
+	 */
289
+	public function allow_overflow()
290
+	{
291
+		return $this->get('EVT_allow_overflow');
292
+	}
293
+
294
+
295
+	/**
296
+	 * @return bool
297
+	 * @throws EE_Error
298
+	 */
299
+	public function created()
300
+	{
301
+		return $this->get('EVT_created');
302
+	}
303
+
304
+
305
+	/**
306
+	 * @return bool
307
+	 * @throws EE_Error
308
+	 */
309
+	public function description()
310
+	{
311
+		return $this->get('EVT_desc');
312
+	}
313
+
314
+
315
+	/**
316
+	 * Runs do_shortcode and wpautop on the description
317
+	 *
318
+	 * @return string of html
319
+	 * @throws EE_Error
320
+	 */
321
+	public function description_filtered()
322
+	{
323
+		return $this->get_pretty('EVT_desc');
324
+	}
325
+
326
+
327
+	/**
328
+	 * @return bool
329
+	 * @throws EE_Error
330
+	 */
331
+	public function display_description()
332
+	{
333
+		return $this->get('EVT_display_desc');
334
+	}
335
+
336
+
337
+	/**
338
+	 * @return bool
339
+	 * @throws EE_Error
340
+	 */
341
+	public function display_ticket_selector()
342
+	{
343
+		return (bool) $this->get('EVT_display_ticket_selector');
344
+	}
345
+
346
+
347
+	/**
348
+	 * @return bool
349
+	 * @throws EE_Error
350
+	 */
351
+	public function external_url()
352
+	{
353
+		return $this->get('EVT_external_URL');
354
+	}
355
+
356
+
357
+	/**
358
+	 * @return bool
359
+	 * @throws EE_Error
360
+	 */
361
+	public function member_only()
362
+	{
363
+		return $this->get('EVT_member_only');
364
+	}
365
+
366
+
367
+	/**
368
+	 * @return bool
369
+	 * @throws EE_Error
370
+	 */
371
+	public function phone()
372
+	{
373
+		return $this->get('EVT_phone');
374
+	}
375
+
376
+
377
+	/**
378
+	 * @return bool
379
+	 * @throws EE_Error
380
+	 */
381
+	public function modified()
382
+	{
383
+		return $this->get('EVT_modified');
384
+	}
385
+
386
+
387
+	/**
388
+	 * @return bool
389
+	 * @throws EE_Error
390
+	 */
391
+	public function name()
392
+	{
393
+		return $this->get('EVT_name');
394
+	}
395
+
396
+
397
+	/**
398
+	 * @return bool
399
+	 * @throws EE_Error
400
+	 */
401
+	public function order()
402
+	{
403
+		return $this->get('EVT_order');
404
+	}
405
+
406
+
407
+	/**
408
+	 * @return bool|string
409
+	 * @throws EE_Error
410
+	 */
411
+	public function default_registration_status()
412
+	{
413
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
414
+		return ! empty($event_default_registration_status)
415
+			? $event_default_registration_status
416
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
417
+	}
418
+
419
+
420
+	/**
421
+	 * @param int  $num_words
422
+	 * @param null $more
423
+	 * @param bool $not_full_desc
424
+	 * @return bool|string
425
+	 * @throws EE_Error
426
+	 */
427
+	public function short_description($num_words = 55, $more = null, $not_full_desc = false)
428
+	{
429
+		$short_desc = $this->get('EVT_short_desc');
430
+		if (! empty($short_desc) || $not_full_desc) {
431
+			return $short_desc;
432
+		}
433
+		$full_desc = $this->get('EVT_desc');
434
+		return wp_trim_words($full_desc, $num_words, $more);
435
+	}
436
+
437
+
438
+	/**
439
+	 * @return bool
440
+	 * @throws EE_Error
441
+	 */
442
+	public function slug()
443
+	{
444
+		return $this->get('EVT_slug');
445
+	}
446
+
447
+
448
+	/**
449
+	 * @return bool
450
+	 * @throws EE_Error
451
+	 */
452
+	public function timezone_string()
453
+	{
454
+		return $this->get('EVT_timezone_string');
455
+	}
456
+
457
+
458
+	/**
459
+	 * @return bool
460
+	 * @throws EE_Error
461
+	 */
462
+	public function visible_on()
463
+	{
464
+		return $this->get('EVT_visible_on');
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return int
470
+	 * @throws EE_Error
471
+	 */
472
+	public function wp_user()
473
+	{
474
+		return $this->get('EVT_wp_user');
475
+	}
476
+
477
+
478
+	/**
479
+	 * @return bool
480
+	 * @throws EE_Error
481
+	 */
482
+	public function donations()
483
+	{
484
+		return $this->get('EVT_donations');
485
+	}
486
+
487
+
488
+	/**
489
+	 * @param $limit
490
+	 * @throws EE_Error
491
+	 */
492
+	public function set_additional_limit($limit)
493
+	{
494
+		$this->set('EVT_additional_limit', $limit);
495
+	}
496
+
497
+
498
+	/**
499
+	 * @param $created
500
+	 * @throws EE_Error
501
+	 */
502
+	public function set_created($created)
503
+	{
504
+		$this->set('EVT_created', $created);
505
+	}
506
+
507
+
508
+	/**
509
+	 * @param $desc
510
+	 * @throws EE_Error
511
+	 */
512
+	public function set_description($desc)
513
+	{
514
+		$this->set('EVT_desc', $desc);
515
+	}
516
+
517
+
518
+	/**
519
+	 * @param $display_desc
520
+	 * @throws EE_Error
521
+	 */
522
+	public function set_display_description($display_desc)
523
+	{
524
+		$this->set('EVT_display_desc', $display_desc);
525
+	}
526
+
527
+
528
+	/**
529
+	 * @param $display_ticket_selector
530
+	 * @throws EE_Error
531
+	 */
532
+	public function set_display_ticket_selector($display_ticket_selector)
533
+	{
534
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
535
+	}
536
+
537
+
538
+	/**
539
+	 * @param $external_url
540
+	 * @throws EE_Error
541
+	 */
542
+	public function set_external_url($external_url)
543
+	{
544
+		$this->set('EVT_external_URL', $external_url);
545
+	}
546
+
547
+
548
+	/**
549
+	 * @param $member_only
550
+	 * @throws EE_Error
551
+	 */
552
+	public function set_member_only($member_only)
553
+	{
554
+		$this->set('EVT_member_only', $member_only);
555
+	}
556
+
557
+
558
+	/**
559
+	 * @param $event_phone
560
+	 * @throws EE_Error
561
+	 */
562
+	public function set_event_phone($event_phone)
563
+	{
564
+		$this->set('EVT_phone', $event_phone);
565
+	}
566
+
567
+
568
+	/**
569
+	 * @param $modified
570
+	 * @throws EE_Error
571
+	 */
572
+	public function set_modified($modified)
573
+	{
574
+		$this->set('EVT_modified', $modified);
575
+	}
576
+
577
+
578
+	/**
579
+	 * @param $name
580
+	 * @throws EE_Error
581
+	 */
582
+	public function set_name($name)
583
+	{
584
+		$this->set('EVT_name', $name);
585
+	}
586
+
587
+
588
+	/**
589
+	 * @param $order
590
+	 * @throws EE_Error
591
+	 */
592
+	public function set_order($order)
593
+	{
594
+		$this->set('EVT_order', $order);
595
+	}
596
+
597
+
598
+	/**
599
+	 * @param $short_desc
600
+	 * @throws EE_Error
601
+	 */
602
+	public function set_short_description($short_desc)
603
+	{
604
+		$this->set('EVT_short_desc', $short_desc);
605
+	}
606
+
607
+
608
+	/**
609
+	 * @param $slug
610
+	 * @throws EE_Error
611
+	 */
612
+	public function set_slug($slug)
613
+	{
614
+		$this->set('EVT_slug', $slug);
615
+	}
616
+
617
+
618
+	/**
619
+	 * @param $timezone_string
620
+	 * @throws EE_Error
621
+	 */
622
+	public function set_timezone_string($timezone_string)
623
+	{
624
+		$this->set('EVT_timezone_string', $timezone_string);
625
+	}
626
+
627
+
628
+	/**
629
+	 * @param $visible_on
630
+	 * @throws EE_Error
631
+	 */
632
+	public function set_visible_on($visible_on)
633
+	{
634
+		$this->set('EVT_visible_on', $visible_on);
635
+	}
636
+
637
+
638
+	/**
639
+	 * @param $wp_user
640
+	 * @throws EE_Error
641
+	 */
642
+	public function set_wp_user($wp_user)
643
+	{
644
+		$this->set('EVT_wp_user', $wp_user);
645
+	}
646
+
647
+
648
+	/**
649
+	 * @param $default_registration_status
650
+	 * @throws EE_Error
651
+	 */
652
+	public function set_default_registration_status($default_registration_status)
653
+	{
654
+		$this->set('EVT_default_registration_status', $default_registration_status);
655
+	}
656
+
657
+
658
+	/**
659
+	 * @param $donations
660
+	 * @throws EE_Error
661
+	 */
662
+	public function set_donations($donations)
663
+	{
664
+		$this->set('EVT_donations', $donations);
665
+	}
666
+
667
+
668
+	/**
669
+	 * Adds a venue to this event
670
+	 *
671
+	 * @param EE_Venue /int $venue_id_or_obj
672
+	 * @return EE_Base_Class|EE_Venue
673
+	 * @throws EE_Error
674
+	 */
675
+	public function add_venue($venue_id_or_obj)
676
+	{
677
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
678
+	}
679
+
680
+
681
+	/**
682
+	 * Removes a venue from the event
683
+	 *
684
+	 * @param EE_Venue /int $venue_id_or_obj
685
+	 * @return EE_Base_Class|EE_Venue
686
+	 * @throws EE_Error
687
+	 */
688
+	public function remove_venue($venue_id_or_obj)
689
+	{
690
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
691
+	}
692
+
693
+
694
+	/**
695
+	 * Gets all the venues related ot the event. May provide additional $query_params if desired
696
+	 *
697
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
698
+	 * @return EE_Base_Class[]|EE_Venue[]
699
+	 * @throws EE_Error
700
+	 */
701
+	public function venues($query_params = array())
702
+	{
703
+		return $this->get_many_related('Venue', $query_params);
704
+	}
705
+
706
+
707
+	/**
708
+	 * check if event id is present and if event is published
709
+	 *
710
+	 * @access public
711
+	 * @return boolean true yes, false no
712
+	 * @throws EE_Error
713
+	 */
714
+	private function _has_ID_and_is_published()
715
+	{
716
+		// first check if event id is present and not NULL,
717
+		// then check if this event is published (or any of the equivalent "published" statuses)
718
+		return
719
+			$this->ID() && $this->ID() !== null
720
+			&& (
721
+				$this->status() === 'publish'
722
+				|| $this->status() === EEM_Event::sold_out
723
+				|| $this->status() === EEM_Event::postponed
724
+				|| $this->status() === EEM_Event::cancelled
725
+			);
726
+	}
727
+
728
+
729
+	/**
730
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
731
+	 *
732
+	 * @access public
733
+	 * @return boolean true yes, false no
734
+	 * @throws EE_Error
735
+	 */
736
+	public function is_upcoming()
737
+	{
738
+		// check if event id is present and if this event is published
739
+		if ($this->is_inactive()) {
740
+			return false;
741
+		}
742
+		// set initial value
743
+		$upcoming = false;
744
+		// next let's get all datetimes and loop through them
745
+		$datetimes = $this->datetimes_in_chronological_order();
746
+		foreach ($datetimes as $datetime) {
747
+			if ($datetime instanceof EE_Datetime) {
748
+				// if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
749
+				if ($datetime->is_expired()) {
750
+					continue;
751
+				}
752
+				// if this dtt is active then we return false.
753
+				if ($datetime->is_active()) {
754
+					return false;
755
+				}
756
+				// otherwise let's check upcoming status
757
+				$upcoming = $datetime->is_upcoming();
758
+			}
759
+		}
760
+		return $upcoming;
761
+	}
762
+
763
+
764
+	/**
765
+	 * @return bool
766
+	 * @throws EE_Error
767
+	 */
768
+	public function is_active()
769
+	{
770
+		// check if event id is present and if this event is published
771
+		if ($this->is_inactive()) {
772
+			return false;
773
+		}
774
+		// set initial value
775
+		$active = false;
776
+		// next let's get all datetimes and loop through them
777
+		$datetimes = $this->datetimes_in_chronological_order();
778
+		foreach ($datetimes as $datetime) {
779
+			if ($datetime instanceof EE_Datetime) {
780
+				// if this dtt is expired then we continue cause one of the other datetimes might be active.
781
+				if ($datetime->is_expired()) {
782
+					continue;
783
+				}
784
+				// if this dtt is upcoming then we return false.
785
+				if ($datetime->is_upcoming()) {
786
+					return false;
787
+				}
788
+				// otherwise let's check active status
789
+				$active = $datetime->is_active();
790
+			}
791
+		}
792
+		return $active;
793
+	}
794
+
795
+
796
+	/**
797
+	 * @return bool
798
+	 * @throws EE_Error
799
+	 */
800
+	public function is_expired()
801
+	{
802
+		// check if event id is present and if this event is published
803
+		if ($this->is_inactive()) {
804
+			return false;
805
+		}
806
+		// set initial value
807
+		$expired = false;
808
+		// first let's get all datetimes and loop through them
809
+		$datetimes = $this->datetimes_in_chronological_order();
810
+		foreach ($datetimes as $datetime) {
811
+			if ($datetime instanceof EE_Datetime) {
812
+				// if this dtt is upcoming or active then we return false.
813
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
814
+					return false;
815
+				}
816
+				// otherwise let's check active status
817
+				$expired = $datetime->is_expired();
818
+			}
819
+		}
820
+		return $expired;
821
+	}
822
+
823
+
824
+	/**
825
+	 * @return bool
826
+	 * @throws EE_Error
827
+	 */
828
+	public function is_inactive()
829
+	{
830
+		// check if event id is present and if this event is published
831
+		if ($this->_has_ID_and_is_published()) {
832
+			return false;
833
+		}
834
+		return true;
835
+	}
836
+
837
+
838
+	/**
839
+	 * calculate spaces remaining based on "saleable" tickets
840
+	 *
841
+	 * @param array $tickets
842
+	 * @param bool  $filtered
843
+	 * @return int|float
844
+	 * @throws EE_Error
845
+	 * @throws DomainException
846
+	 * @throws UnexpectedEntityException
847
+	 */
848
+	public function spaces_remaining($tickets = array(), $filtered = true)
849
+	{
850
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
851
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
852
+		return $filtered
853
+			? apply_filters(
854
+				'FHEE_EE_Event__spaces_remaining',
855
+				$spaces_remaining,
856
+				$this,
857
+				$tickets
858
+			)
859
+			: $spaces_remaining;
860
+	}
861
+
862
+
863
+	/**
864
+	 *    perform_sold_out_status_check
865
+	 *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
866
+	 *    available... if NOT, then the event status will get toggled to 'sold_out'
867
+	 *
868
+	 * @return bool    return the ACTUAL sold out state.
869
+	 * @throws EE_Error
870
+	 * @throws DomainException
871
+	 * @throws UnexpectedEntityException
872
+	 */
873
+	public function perform_sold_out_status_check()
874
+	{
875
+		// get all unexpired untrashed tickets
876
+		$tickets = $this->tickets(
877
+			array(
878
+				array('TKT_deleted' => false),
879
+				'order_by' => array('TKT_qty' => 'ASC'),
880
+			)
881
+		);
882
+		$all_expired = true;
883
+		foreach ($tickets as $ticket) {
884
+			if (! $ticket->is_expired()) {
885
+				$all_expired = false;
886
+				break;
887
+			}
888
+		}
889
+		// if all the tickets are just expired, then don't update the event status to sold out
890
+		if ($all_expired) {
891
+			return true;
892
+		}
893
+		$spaces_remaining = $this->spaces_remaining($tickets);
894
+		if ($spaces_remaining < 1) {
895
+			$this->set_status(EEM_Event::sold_out);
896
+			$this->save();
897
+			$sold_out = true;
898
+		} else {
899
+			$sold_out = false;
900
+			// was event previously marked as sold out ?
901
+			if ($this->status() === EEM_Event::sold_out) {
902
+				// revert status to previous value, if it was set
903
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
904
+				if ($previous_event_status) {
905
+					$this->set_status($previous_event_status);
906
+					$this->save();
907
+				}
908
+			}
909
+		}
910
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
911
+		return $sold_out;
912
+	}
913
+
914
+
915
+	/**
916
+	 * This returns the total remaining spaces for sale on this event.
917
+	 *
918
+	 * @uses EE_Event::total_available_spaces()
919
+	 * @return float|int
920
+	 * @throws EE_Error
921
+	 * @throws DomainException
922
+	 * @throws UnexpectedEntityException
923
+	 */
924
+	public function spaces_remaining_for_sale()
925
+	{
926
+		return $this->total_available_spaces(true);
927
+	}
928
+
929
+
930
+	/**
931
+	 * This returns the total spaces available for an event
932
+	 * while considering all the qtys on the tickets and the reg limits
933
+	 * on the datetimes attached to this event.
934
+	 *
935
+	 * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
936
+	 *                              If this is false, then we return the most tickets that could ever be sold
937
+	 *                              for this event with the datetime and tickets setup on the event under optimal
938
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
939
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
940
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
941
+	 *                              sold out, the more accurate the "live" total is.
942
+	 * @return float|int
943
+	 * @throws EE_Error
944
+	 * @throws DomainException
945
+	 * @throws UnexpectedEntityException
946
+	 */
947
+	public function total_available_spaces($consider_sold = false)
948
+	{
949
+		$spaces_available = $consider_sold
950
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
951
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
952
+		return apply_filters(
953
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
954
+			$spaces_available,
955
+			$this,
956
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
957
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
958
+		);
959
+	}
960
+
961
+
962
+	/**
963
+	 * Checks if the event is set to sold out
964
+	 *
965
+	 * @param  bool $actual whether or not to perform calculations to not only figure the
966
+	 *                      actual status but also to flip the status if necessary to sold
967
+	 *                      out If false, we just check the existing status of the event
968
+	 * @return boolean
969
+	 * @throws EE_Error
970
+	 */
971
+	public function is_sold_out($actual = false)
972
+	{
973
+		if (! $actual) {
974
+			return $this->status() === EEM_Event::sold_out;
975
+		}
976
+		return $this->perform_sold_out_status_check();
977
+	}
978
+
979
+
980
+	/**
981
+	 * Checks if the event is marked as postponed
982
+	 *
983
+	 * @return boolean
984
+	 */
985
+	public function is_postponed()
986
+	{
987
+		return $this->status() === EEM_Event::postponed;
988
+	}
989
+
990
+
991
+	/**
992
+	 * Checks if the event is marked as cancelled
993
+	 *
994
+	 * @return boolean
995
+	 */
996
+	public function is_cancelled()
997
+	{
998
+		return $this->status() === EEM_Event::cancelled;
999
+	}
1000
+
1001
+
1002
+	/**
1003
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
1004
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1005
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1006
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1007
+	 * the event is considered expired.
1008
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1009
+	 * status set on the EVENT when it is not published and thus is done
1010
+	 *
1011
+	 * @param bool $reset
1012
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1013
+	 * @throws EE_Error
1014
+	 */
1015
+	public function get_active_status($reset = false)
1016
+	{
1017
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1018
+		if (! empty($this->_active_status) && ! $reset) {
1019
+			return $this->_active_status;
1020
+		}
1021
+		// first check if event id is present on this object
1022
+		if (! $this->ID()) {
1023
+			return false;
1024
+		}
1025
+		$where_params_for_event = array(array('EVT_ID' => $this->ID()));
1026
+		// if event is published:
1027
+		if ($this->status() === 'publish') {
1028
+			// active?
1029
+			if (EEM_Datetime::instance()->get_datetime_count_for_status(
1030
+				EE_Datetime::active,
1031
+				$where_params_for_event
1032
+			) > 0) {
1033
+				$this->_active_status = EE_Datetime::active;
1034
+			} else {
1035
+				// upcoming?
1036
+				if (EEM_Datetime::instance()->get_datetime_count_for_status(
1037
+					EE_Datetime::upcoming,
1038
+					$where_params_for_event
1039
+				) > 0) {
1040
+					$this->_active_status = EE_Datetime::upcoming;
1041
+				} else {
1042
+					// expired?
1043
+					if (EEM_Datetime::instance()->get_datetime_count_for_status(
1044
+						EE_Datetime::expired,
1045
+						$where_params_for_event
1046
+					) > 0
1047
+					) {
1048
+						$this->_active_status = EE_Datetime::expired;
1049
+					} else {
1050
+						// it would be odd if things make it this far because it basically means there are no datetime's
1051
+						// attached to the event.  So in this case it will just be considered inactive.
1052
+						$this->_active_status = EE_Datetime::inactive;
1053
+					}
1054
+				}
1055
+			}
1056
+		} else {
1057
+			// the event is not published, so let's just set it's active status according to its' post status
1058
+			switch ($this->status()) {
1059
+				case EEM_Event::sold_out:
1060
+					$this->_active_status = EE_Datetime::sold_out;
1061
+					break;
1062
+				case EEM_Event::cancelled:
1063
+					$this->_active_status = EE_Datetime::cancelled;
1064
+					break;
1065
+				case EEM_Event::postponed:
1066
+					$this->_active_status = EE_Datetime::postponed;
1067
+					break;
1068
+				default:
1069
+					$this->_active_status = EE_Datetime::inactive;
1070
+			}
1071
+		}
1072
+		return $this->_active_status;
1073
+	}
1074
+
1075
+
1076
+	/**
1077
+	 *    pretty_active_status
1078
+	 *
1079
+	 * @access public
1080
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1081
+	 * @return mixed void|string
1082
+	 * @throws EE_Error
1083
+	 */
1084
+	public function pretty_active_status($echo = true)
1085
+	{
1086
+		$active_status = $this->get_active_status();
1087
+		$status = '<span class="ee-status event-active-status-'
1088
+				  . $active_status
1089
+				  . '">'
1090
+				  . EEH_Template::pretty_status($active_status, false, 'sentence')
1091
+				  . '</span>';
1092
+		if ($echo) {
1093
+			echo $status;
1094
+			return '';
1095
+		}
1096
+		return $status;
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 * @return bool|int
1102
+	 * @throws EE_Error
1103
+	 */
1104
+	public function get_number_of_tickets_sold()
1105
+	{
1106
+		$tkt_sold = 0;
1107
+		if (! $this->ID()) {
1108
+			return 0;
1109
+		}
1110
+		$datetimes = $this->datetimes();
1111
+		foreach ($datetimes as $datetime) {
1112
+			if ($datetime instanceof EE_Datetime) {
1113
+				$tkt_sold += $datetime->sold();
1114
+			}
1115
+		}
1116
+		return $tkt_sold;
1117
+	}
1118
+
1119
+
1120
+	/**
1121
+	 * This just returns a count of all the registrations for this event
1122
+	 *
1123
+	 * @access  public
1124
+	 * @return int
1125
+	 * @throws EE_Error
1126
+	 */
1127
+	public function get_count_of_all_registrations()
1128
+	{
1129
+		return EEM_Event::instance()->count_related($this, 'Registration');
1130
+	}
1131
+
1132
+
1133
+	/**
1134
+	 * This returns the ticket with the earliest start time that is
1135
+	 * available for this event (across all datetimes attached to the event)
1136
+	 *
1137
+	 * @return EE_Base_Class|EE_Ticket|null
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function get_ticket_with_earliest_start_time()
1141
+	{
1142
+		$where['Datetime.EVT_ID'] = $this->ID();
1143
+		$query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1144
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
+	}
1146
+
1147
+
1148
+	/**
1149
+	 * This returns the ticket with the latest end time that is available
1150
+	 * for this event (across all datetimes attached to the event)
1151
+	 *
1152
+	 * @return EE_Base_Class|EE_Ticket|null
1153
+	 * @throws EE_Error
1154
+	 */
1155
+	public function get_ticket_with_latest_end_time()
1156
+	{
1157
+		$where['Datetime.EVT_ID'] = $this->ID();
1158
+		$query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1159
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * This returns the number of different ticket types currently on sale for this event.
1165
+	 *
1166
+	 * @return int
1167
+	 * @throws EE_Error
1168
+	 */
1169
+	public function countTicketsOnSale()
1170
+	{
1171
+		$where = array(
1172
+			'Datetime.EVT_ID' => $this->ID(),
1173
+			'TKT_start_date'  => array('<', time()),
1174
+			'TKT_end_date'    => array('>', time()),
1175
+		);
1176
+		return EEM_Ticket::instance()->count(array($where));
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * This returns whether there are any tickets on sale for this event.
1182
+	 *
1183
+	 * @return bool true = YES tickets on sale.
1184
+	 * @throws EE_Error
1185
+	 */
1186
+	public function tickets_on_sale()
1187
+	{
1188
+		return $this->countTicketsOnSale() > 0;
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1194
+	 * to check for an external URL first
1195
+	 *
1196
+	 * @return string
1197
+	 * @throws EE_Error
1198
+	 */
1199
+	public function get_permalink()
1200
+	{
1201
+		if ($this->external_url()) {
1202
+			return $this->external_url();
1203
+		}
1204
+		return parent::get_permalink();
1205
+	}
1206
+
1207
+
1208
+	/**
1209
+	 * Gets the first term for 'espresso_event_categories' we can find
1210
+	 *
1211
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1212
+	 * @return EE_Base_Class|EE_Term|null
1213
+	 * @throws EE_Error
1214
+	 */
1215
+	public function first_event_category($query_params = array())
1216
+	{
1217
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1218
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1219
+		return EEM_Term::instance()->get_one($query_params);
1220
+	}
1221
+
1222
+
1223
+	/**
1224
+	 * Gets all terms for 'espresso_event_categories' we can find
1225
+	 *
1226
+	 * @param array $query_params
1227
+	 * @return EE_Base_Class[]|EE_Term[]
1228
+	 * @throws EE_Error
1229
+	 */
1230
+	public function get_all_event_categories($query_params = array())
1231
+	{
1232
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1233
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1234
+		return EEM_Term::instance()->get_all($query_params);
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 * Adds a question group to this event
1240
+	 *
1241
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1242
+	 * @param bool                  $for_primary if true, the question group will be added for the primary
1243
+	 *                                           registrant, if false will be added for others. default: false
1244
+	 * @return EE_Base_Class|EE_Question_Group
1245
+	 * @throws EE_Error
1246
+	 */
1247
+	public function add_question_group($question_group_id_or_obj, $for_primary = false)
1248
+	{
1249
+		$extra = $for_primary
1250
+			? array('EQG_primary' => 1)
1251
+			: array();
1252
+		return $this->_add_relation_to($question_group_id_or_obj, 'Question_Group', $extra);
1253
+	}
1254
+
1255
+
1256
+	/**
1257
+	 * Removes a question group from the event
1258
+	 *
1259
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1260
+	 * @param bool                  $for_primary if true, the question group will be removed from the primary
1261
+	 *                                           registrant, if false will be removed from others. default: false
1262
+	 * @return EE_Base_Class|EE_Question_Group
1263
+	 * @throws EE_Error
1264
+	 */
1265
+	public function remove_question_group($question_group_id_or_obj, $for_primary = false)
1266
+	{
1267
+		$where = $for_primary
1268
+			? array('EQG_primary' => 1)
1269
+			: array();
1270
+		return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group', $where);
1271
+	}
1272
+
1273
+
1274
+	/**
1275
+	 * Gets all the question groups, ordering them by QSG_order ascending
1276
+	 *
1277
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1278
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1279
+	 * @throws EE_Error
1280
+	 */
1281
+	public function question_groups($query_params = array())
1282
+	{
1283
+		$query_params = ! empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1284
+		return $this->get_many_related('Question_Group', $query_params);
1285
+	}
1286
+
1287
+
1288
+	/**
1289
+	 * Implementation for EEI_Has_Icon interface method.
1290
+	 *
1291
+	 * @see EEI_Visual_Representation for comments
1292
+	 * @return string
1293
+	 */
1294
+	public function get_icon()
1295
+	{
1296
+		return '<span class="dashicons dashicons-flag"></span>';
1297
+	}
1298
+
1299
+
1300
+	/**
1301
+	 * Implementation for EEI_Admin_Links interface method.
1302
+	 *
1303
+	 * @see EEI_Admin_Links for comments
1304
+	 * @return string
1305
+	 * @throws EE_Error
1306
+	 */
1307
+	public function get_admin_details_link()
1308
+	{
1309
+		return $this->get_admin_edit_link();
1310
+	}
1311
+
1312
+
1313
+	/**
1314
+	 * Implementation for EEI_Admin_Links interface method.
1315
+	 *
1316
+	 * @see EEI_Admin_Links for comments
1317
+	 * @return string
1318
+	 * @throws EE_Error
1319
+	 */
1320
+	public function get_admin_edit_link()
1321
+	{
1322
+		return EEH_URL::add_query_args_and_nonce(
1323
+			array(
1324
+				'page'   => 'espresso_events',
1325
+				'action' => 'edit',
1326
+				'post'   => $this->ID(),
1327
+			),
1328
+			admin_url('admin.php')
1329
+		);
1330
+	}
1331
+
1332
+
1333
+	/**
1334
+	 * Implementation for EEI_Admin_Links interface method.
1335
+	 *
1336
+	 * @see EEI_Admin_Links for comments
1337
+	 * @return string
1338
+	 */
1339
+	public function get_admin_settings_link()
1340
+	{
1341
+		return EEH_URL::add_query_args_and_nonce(
1342
+			array(
1343
+				'page'   => 'espresso_events',
1344
+				'action' => 'default_event_settings',
1345
+			),
1346
+			admin_url('admin.php')
1347
+		);
1348
+	}
1349
+
1350
+
1351
+	/**
1352
+	 * Implementation for EEI_Admin_Links interface method.
1353
+	 *
1354
+	 * @see EEI_Admin_Links for comments
1355
+	 * @return string
1356
+	 */
1357
+	public function get_admin_overview_link()
1358
+	{
1359
+		return EEH_URL::add_query_args_and_nonce(
1360
+			array(
1361
+				'page'   => 'espresso_events',
1362
+				'action' => 'default',
1363
+			),
1364
+			admin_url('admin.php')
1365
+		);
1366
+	}
1367 1367
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 1 patch
Indentation   +1272 added lines, -1272 removed lines patch added patch discarded remove patch
@@ -13,1276 +13,1276 @@
 block discarded – undo
13 13
 class EE_Datetime extends EE_Soft_Delete_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * constant used by get_active_status, indicates datetime has no more available spaces
18
-     */
19
-    const sold_out = 'DTS';
20
-
21
-    /**
22
-     * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
23
-     */
24
-    const active = 'DTA';
25
-
26
-    /**
27
-     * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
28
-     * expired
29
-     */
30
-    const upcoming = 'DTU';
31
-
32
-    /**
33
-     * Datetime is postponed
34
-     */
35
-    const postponed = 'DTP';
36
-
37
-    /**
38
-     * Datetime is cancelled
39
-     */
40
-    const cancelled = 'DTC';
41
-
42
-    /**
43
-     * constant used by get_active_status, indicates datetime has expired (event is over)
44
-     */
45
-    const expired = 'DTE';
46
-
47
-    /**
48
-     * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
49
-     */
50
-    const inactive = 'DTI';
51
-
52
-
53
-    /**
54
-     * @param array  $props_n_values    incoming values
55
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
56
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
57
-     *                                  and the second value is the time format
58
-     * @return EE_Datetime
59
-     * @throws ReflectionException
60
-     * @throws InvalidArgumentException
61
-     * @throws InvalidInterfaceException
62
-     * @throws InvalidDataTypeException
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
66
-    {
67
-        $has_object = parent::_check_for_object(
68
-            $props_n_values,
69
-            __CLASS__,
70
-            $timezone,
71
-            $date_formats
72
-        );
73
-        return $has_object
74
-            ? $has_object
75
-            : new self($props_n_values, false, $timezone, $date_formats);
76
-    }
77
-
78
-
79
-    /**
80
-     * @param array  $props_n_values  incoming values from the database
81
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
-     *                                the website will be used.
83
-     * @return EE_Datetime
84
-     * @throws ReflectionException
85
-     * @throws InvalidArgumentException
86
-     * @throws InvalidInterfaceException
87
-     * @throws InvalidDataTypeException
88
-     * @throws EE_Error
89
-     */
90
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
-    {
92
-        return new self($props_n_values, true, $timezone);
93
-    }
94
-
95
-
96
-    /**
97
-     * @param $name
98
-     * @throws ReflectionException
99
-     * @throws InvalidArgumentException
100
-     * @throws InvalidInterfaceException
101
-     * @throws InvalidDataTypeException
102
-     * @throws EE_Error
103
-     */
104
-    public function set_name($name)
105
-    {
106
-        $this->set('DTT_name', $name);
107
-    }
108
-
109
-
110
-    /**
111
-     * @param $description
112
-     * @throws ReflectionException
113
-     * @throws InvalidArgumentException
114
-     * @throws InvalidInterfaceException
115
-     * @throws InvalidDataTypeException
116
-     * @throws EE_Error
117
-     */
118
-    public function set_description($description)
119
-    {
120
-        $this->set('DTT_description', $description);
121
-    }
122
-
123
-
124
-    /**
125
-     * Set event start date
126
-     * set the start date for an event
127
-     *
128
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
129
-     * @throws ReflectionException
130
-     * @throws InvalidArgumentException
131
-     * @throws InvalidInterfaceException
132
-     * @throws InvalidDataTypeException
133
-     * @throws EE_Error
134
-     */
135
-    public function set_start_date($date)
136
-    {
137
-        $this->_set_date_for($date, 'DTT_EVT_start');
138
-    }
139
-
140
-
141
-    /**
142
-     * Set event start time
143
-     * set the start time for an event
144
-     *
145
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
146
-     * @throws ReflectionException
147
-     * @throws InvalidArgumentException
148
-     * @throws InvalidInterfaceException
149
-     * @throws InvalidDataTypeException
150
-     * @throws EE_Error
151
-     */
152
-    public function set_start_time($time)
153
-    {
154
-        $this->_set_time_for($time, 'DTT_EVT_start');
155
-    }
156
-
157
-
158
-    /**
159
-     * Set event end date
160
-     * set the end date for an event
161
-     *
162
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
163
-     * @throws ReflectionException
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidInterfaceException
166
-     * @throws InvalidDataTypeException
167
-     * @throws EE_Error
168
-     */
169
-    public function set_end_date($date)
170
-    {
171
-        $this->_set_date_for($date, 'DTT_EVT_end');
172
-    }
173
-
174
-
175
-    /**
176
-     * Set event end time
177
-     * set the end time for an event
178
-     *
179
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
180
-     * @throws ReflectionException
181
-     * @throws InvalidArgumentException
182
-     * @throws InvalidInterfaceException
183
-     * @throws InvalidDataTypeException
184
-     * @throws EE_Error
185
-     */
186
-    public function set_end_time($time)
187
-    {
188
-        $this->_set_time_for($time, 'DTT_EVT_end');
189
-    }
190
-
191
-
192
-    /**
193
-     * Set registration limit
194
-     * set the maximum number of attendees that can be registered for this datetime slot
195
-     *
196
-     * @param int $reg_limit
197
-     * @throws ReflectionException
198
-     * @throws InvalidArgumentException
199
-     * @throws InvalidInterfaceException
200
-     * @throws InvalidDataTypeException
201
-     * @throws EE_Error
202
-     */
203
-    public function set_reg_limit($reg_limit)
204
-    {
205
-        $this->set('DTT_reg_limit', $reg_limit);
206
-    }
207
-
208
-
209
-    /**
210
-     * get the number of tickets sold for this datetime slot
211
-     *
212
-     * @return mixed int on success, FALSE on fail
213
-     * @throws ReflectionException
214
-     * @throws InvalidArgumentException
215
-     * @throws InvalidInterfaceException
216
-     * @throws InvalidDataTypeException
217
-     * @throws EE_Error
218
-     */
219
-    public function sold()
220
-    {
221
-        return $this->get_raw('DTT_sold');
222
-    }
223
-
224
-
225
-    /**
226
-     * @param int $sold
227
-     * @throws ReflectionException
228
-     * @throws InvalidArgumentException
229
-     * @throws InvalidInterfaceException
230
-     * @throws InvalidDataTypeException
231
-     * @throws EE_Error
232
-     */
233
-    public function set_sold($sold)
234
-    {
235
-        // sold can not go below zero
236
-        $sold = max(0, $sold);
237
-        $this->set('DTT_sold', $sold);
238
-    }
239
-
240
-
241
-    /**
242
-     * increments sold by amount passed by $qty
243
-     *
244
-     * @param int $qty
245
-     * @throws ReflectionException
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidDataTypeException
249
-     * @throws EE_Error
250
-     */
251
-    public function increase_sold($qty = 1)
252
-    {
253
-        $sold = $this->sold() + $qty;
254
-        // remove ticket reservation
255
-        $this->decrease_reserved($qty);
256
-        $this->set_sold($sold);
257
-        do_action(
258
-            'AHEE__EE_Datetime__increase_sold',
259
-            $this,
260
-            $qty,
261
-            $sold
262
-        );
263
-    }
264
-
265
-
266
-    /**
267
-     * decrements (subtracts) sold amount passed by $qty
268
-     *
269
-     * @param int $qty
270
-     * @throws ReflectionException
271
-     * @throws InvalidArgumentException
272
-     * @throws InvalidInterfaceException
273
-     * @throws InvalidDataTypeException
274
-     * @throws EE_Error
275
-     */
276
-    public function decrease_sold($qty = 1)
277
-    {
278
-        $sold = $this->sold() - $qty;
279
-        $this->set_sold($sold);
280
-        do_action(
281
-            'AHEE__EE_Datetime__decrease_sold',
282
-            $this,
283
-            $qty,
284
-            $sold
285
-        );
286
-    }
287
-
288
-
289
-    /**
290
-     * Gets qty of reserved tickets for this datetime
291
-     *
292
-     * @return int
293
-     * @throws ReflectionException
294
-     * @throws InvalidArgumentException
295
-     * @throws InvalidInterfaceException
296
-     * @throws InvalidDataTypeException
297
-     * @throws EE_Error
298
-     */
299
-    public function reserved()
300
-    {
301
-        return $this->get_raw('DTT_reserved');
302
-    }
303
-
304
-
305
-    /**
306
-     * Sets qty of reserved tickets for this datetime
307
-     *
308
-     * @param int $reserved
309
-     * @throws ReflectionException
310
-     * @throws InvalidArgumentException
311
-     * @throws InvalidInterfaceException
312
-     * @throws InvalidDataTypeException
313
-     * @throws EE_Error
314
-     */
315
-    public function set_reserved($reserved)
316
-    {
317
-        // reserved can not go below zero
318
-        $reserved = max(0, (int) $reserved);
319
-        $this->set('DTT_reserved', $reserved);
320
-    }
321
-
322
-
323
-    /**
324
-     * increments reserved by amount passed by $qty
325
-     *
326
-     * @param int $qty
327
-     * @return void
328
-     * @throws ReflectionException
329
-     * @throws InvalidArgumentException
330
-     * @throws InvalidInterfaceException
331
-     * @throws InvalidDataTypeException
332
-     * @throws EE_Error
333
-     */
334
-    public function increase_reserved($qty = 1)
335
-    {
336
-        $reserved = $this->reserved() + absint($qty);
337
-        do_action(
338
-            'AHEE__EE_Datetime__increase_reserved',
339
-            $this,
340
-            $qty,
341
-            $reserved
342
-        );
343
-        $this->set_reserved($reserved);
344
-    }
345
-
346
-
347
-    /**
348
-     * decrements (subtracts) reserved by amount passed by $qty
349
-     *
350
-     * @param int $qty
351
-     * @return void
352
-     * @throws ReflectionException
353
-     * @throws InvalidArgumentException
354
-     * @throws InvalidInterfaceException
355
-     * @throws InvalidDataTypeException
356
-     * @throws EE_Error
357
-     */
358
-    public function decrease_reserved($qty = 1)
359
-    {
360
-        $reserved = $this->reserved() - absint($qty);
361
-        do_action(
362
-            'AHEE__EE_Datetime__decrease_reserved',
363
-            $this,
364
-            $qty,
365
-            $reserved
366
-        );
367
-        $this->set_reserved($reserved);
368
-    }
369
-
370
-
371
-    /**
372
-     * total sold and reserved tickets
373
-     *
374
-     * @return int
375
-     * @throws ReflectionException
376
-     * @throws InvalidArgumentException
377
-     * @throws InvalidInterfaceException
378
-     * @throws InvalidDataTypeException
379
-     * @throws EE_Error
380
-     */
381
-    public function sold_and_reserved()
382
-    {
383
-        return $this->sold() + $this->reserved();
384
-    }
385
-
386
-
387
-    /**
388
-     * returns the datetime name
389
-     *
390
-     * @return string
391
-     * @throws ReflectionException
392
-     * @throws InvalidArgumentException
393
-     * @throws InvalidInterfaceException
394
-     * @throws InvalidDataTypeException
395
-     * @throws EE_Error
396
-     */
397
-    public function name()
398
-    {
399
-        return $this->get('DTT_name');
400
-    }
401
-
402
-
403
-    /**
404
-     * returns the datetime description
405
-     *
406
-     * @return string
407
-     * @throws ReflectionException
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidInterfaceException
410
-     * @throws InvalidDataTypeException
411
-     * @throws EE_Error
412
-     */
413
-    public function description()
414
-    {
415
-        return $this->get('DTT_description');
416
-    }
417
-
418
-
419
-    /**
420
-     * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
421
-     *
422
-     * @return boolean  TRUE if is primary, FALSE if not.
423
-     * @throws ReflectionException
424
-     * @throws InvalidArgumentException
425
-     * @throws InvalidInterfaceException
426
-     * @throws InvalidDataTypeException
427
-     * @throws EE_Error
428
-     */
429
-    public function is_primary()
430
-    {
431
-        return $this->get('DTT_is_primary');
432
-    }
433
-
434
-
435
-    /**
436
-     * This helper simply returns the order for the datetime
437
-     *
438
-     * @return int  The order of the datetime for this event.
439
-     * @throws ReflectionException
440
-     * @throws InvalidArgumentException
441
-     * @throws InvalidInterfaceException
442
-     * @throws InvalidDataTypeException
443
-     * @throws EE_Error
444
-     */
445
-    public function order()
446
-    {
447
-        return $this->get('DTT_order');
448
-    }
449
-
450
-
451
-    /**
452
-     * This helper simply returns the parent id for the datetime
453
-     *
454
-     * @return int
455
-     * @throws ReflectionException
456
-     * @throws InvalidArgumentException
457
-     * @throws InvalidInterfaceException
458
-     * @throws InvalidDataTypeException
459
-     * @throws EE_Error
460
-     */
461
-    public function parent()
462
-    {
463
-        return $this->get('DTT_parent');
464
-    }
465
-
466
-
467
-    /**
468
-     * show date and/or time
469
-     *
470
-     * @param string $date_or_time    whether to display a date or time or both
471
-     * @param string $start_or_end    whether to display start or end datetimes
472
-     * @param string $dt_frmt
473
-     * @param string $tm_frmt
474
-     * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
475
-     *                                otherwise we use the standard formats)
476
-     * @return string|bool  string on success, FALSE on fail
477
-     * @throws ReflectionException
478
-     * @throws InvalidArgumentException
479
-     * @throws InvalidInterfaceException
480
-     * @throws InvalidDataTypeException
481
-     * @throws EE_Error
482
-     */
483
-    private function _show_datetime(
484
-        $date_or_time = null,
485
-        $start_or_end = 'start',
486
-        $dt_frmt = '',
487
-        $tm_frmt = '',
488
-        $echo = false
489
-    ) {
490
-        $field_name = "DTT_EVT_{$start_or_end}";
491
-        $dtt = $this->_get_datetime(
492
-            $field_name,
493
-            $dt_frmt,
494
-            $tm_frmt,
495
-            $date_or_time,
496
-            $echo
497
-        );
498
-        if (! $echo) {
499
-            return $dtt;
500
-        }
501
-        return '';
502
-    }
503
-
504
-
505
-    /**
506
-     * get event start date.  Provide either the date format, or NULL to re-use the
507
-     * last-used format, or '' to use the default date format
508
-     *
509
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
510
-     * @return mixed            string on success, FALSE on fail
511
-     * @throws ReflectionException
512
-     * @throws InvalidArgumentException
513
-     * @throws InvalidInterfaceException
514
-     * @throws InvalidDataTypeException
515
-     * @throws EE_Error
516
-     */
517
-    public function start_date($dt_frmt = '')
518
-    {
519
-        return $this->_show_datetime('D', 'start', $dt_frmt);
520
-    }
521
-
522
-
523
-    /**
524
-     * Echoes start_date()
525
-     *
526
-     * @param string $dt_frmt
527
-     * @throws ReflectionException
528
-     * @throws InvalidArgumentException
529
-     * @throws InvalidInterfaceException
530
-     * @throws InvalidDataTypeException
531
-     * @throws EE_Error
532
-     */
533
-    public function e_start_date($dt_frmt = '')
534
-    {
535
-        $this->_show_datetime('D', 'start', $dt_frmt, null, true);
536
-    }
537
-
538
-
539
-    /**
540
-     * get end date. Provide either the date format, or NULL to re-use the
541
-     * last-used format, or '' to use the default date format
542
-     *
543
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
544
-     * @return mixed            string on success, FALSE on fail
545
-     * @throws ReflectionException
546
-     * @throws InvalidArgumentException
547
-     * @throws InvalidInterfaceException
548
-     * @throws InvalidDataTypeException
549
-     * @throws EE_Error
550
-     */
551
-    public function end_date($dt_frmt = '')
552
-    {
553
-        return $this->_show_datetime('D', 'end', $dt_frmt);
554
-    }
555
-
556
-
557
-    /**
558
-     * Echoes the end date. See end_date()
559
-     *
560
-     * @param string $dt_frmt
561
-     * @throws ReflectionException
562
-     * @throws InvalidArgumentException
563
-     * @throws InvalidInterfaceException
564
-     * @throws InvalidDataTypeException
565
-     * @throws EE_Error
566
-     */
567
-    public function e_end_date($dt_frmt = '')
568
-    {
569
-        $this->_show_datetime('D', 'end', $dt_frmt, null, true);
570
-    }
571
-
572
-
573
-    /**
574
-     * get date_range - meaning the start AND end date
575
-     *
576
-     * @access public
577
-     * @param string $dt_frmt     string representation of date format defaults to WP settings
578
-     * @param string $conjunction conjunction junction what's your function ?
579
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
580
-     * @return mixed              string on success, FALSE on fail
581
-     * @throws ReflectionException
582
-     * @throws InvalidArgumentException
583
-     * @throws InvalidInterfaceException
584
-     * @throws InvalidDataTypeException
585
-     * @throws EE_Error
586
-     */
587
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
588
-    {
589
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
590
-        $start = str_replace(
591
-            ' ',
592
-            '&nbsp;',
593
-            $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
594
-        );
595
-        $end = str_replace(
596
-            ' ',
597
-            '&nbsp;',
598
-            $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
599
-        );
600
-        return $start !== $end ? $start . $conjunction . $end : $start;
601
-    }
602
-
603
-
604
-    /**
605
-     * @param string $dt_frmt
606
-     * @param string $conjunction
607
-     * @throws ReflectionException
608
-     * @throws InvalidArgumentException
609
-     * @throws InvalidInterfaceException
610
-     * @throws InvalidDataTypeException
611
-     * @throws EE_Error
612
-     */
613
-    public function e_date_range($dt_frmt = '', $conjunction = ' - ')
614
-    {
615
-        echo $this->date_range($dt_frmt, $conjunction);
616
-    }
617
-
618
-
619
-    /**
620
-     * get start time
621
-     *
622
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
623
-     * @return mixed        string on success, FALSE on fail
624
-     * @throws ReflectionException
625
-     * @throws InvalidArgumentException
626
-     * @throws InvalidInterfaceException
627
-     * @throws InvalidDataTypeException
628
-     * @throws EE_Error
629
-     */
630
-    public function start_time($tm_format = '')
631
-    {
632
-        return $this->_show_datetime('T', 'start', null, $tm_format);
633
-    }
634
-
635
-
636
-    /**
637
-     * @param string $tm_format
638
-     * @throws ReflectionException
639
-     * @throws InvalidArgumentException
640
-     * @throws InvalidInterfaceException
641
-     * @throws InvalidDataTypeException
642
-     * @throws EE_Error
643
-     */
644
-    public function e_start_time($tm_format = '')
645
-    {
646
-        $this->_show_datetime('T', 'start', null, $tm_format, true);
647
-    }
648
-
649
-
650
-    /**
651
-     * get end time
652
-     *
653
-     * @param string $tm_format string representation of time format defaults to 'g:i a'
654
-     * @return mixed                string on success, FALSE on fail
655
-     * @throws ReflectionException
656
-     * @throws InvalidArgumentException
657
-     * @throws InvalidInterfaceException
658
-     * @throws InvalidDataTypeException
659
-     * @throws EE_Error
660
-     */
661
-    public function end_time($tm_format = '')
662
-    {
663
-        return $this->_show_datetime('T', 'end', null, $tm_format);
664
-    }
665
-
666
-
667
-    /**
668
-     * @param string $tm_format
669
-     * @throws ReflectionException
670
-     * @throws InvalidArgumentException
671
-     * @throws InvalidInterfaceException
672
-     * @throws InvalidDataTypeException
673
-     * @throws EE_Error
674
-     */
675
-    public function e_end_time($tm_format = '')
676
-    {
677
-        $this->_show_datetime('T', 'end', null, $tm_format, true);
678
-    }
679
-
680
-
681
-    /**
682
-     * get time_range
683
-     *
684
-     * @access public
685
-     * @param string $tm_format   string representation of time format defaults to 'g:i a'
686
-     * @param string $conjunction conjunction junction what's your function ?
687
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
688
-     * @return mixed              string on success, FALSE on fail
689
-     * @throws ReflectionException
690
-     * @throws InvalidArgumentException
691
-     * @throws InvalidInterfaceException
692
-     * @throws InvalidDataTypeException
693
-     * @throws EE_Error
694
-     */
695
-    public function time_range($tm_format = '', $conjunction = ' - ')
696
-    {
697
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
698
-        $start = str_replace(
699
-            ' ',
700
-            '&nbsp;',
701
-            $this->get_i18n_datetime('DTT_EVT_start', $tm_format)
702
-        );
703
-        $end = str_replace(
704
-            ' ',
705
-            '&nbsp;',
706
-            $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
707
-        );
708
-        return $start !== $end ? $start . $conjunction . $end : $start;
709
-    }
710
-
711
-
712
-    /**
713
-     * @param string $tm_format
714
-     * @param string $conjunction
715
-     * @throws ReflectionException
716
-     * @throws InvalidArgumentException
717
-     * @throws InvalidInterfaceException
718
-     * @throws InvalidDataTypeException
719
-     * @throws EE_Error
720
-     */
721
-    public function e_time_range($tm_format = '', $conjunction = ' - ')
722
-    {
723
-        echo $this->time_range($tm_format, $conjunction);
724
-    }
725
-
726
-
727
-    /**
728
-     * This returns a range representation of the date and times.
729
-     * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
730
-     * Also, the return value is localized.
731
-     *
732
-     * @param string $dt_format
733
-     * @param string $tm_format
734
-     * @param string $conjunction used between two different dates or times.
735
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
736
-     * @param string $separator   used between the date and time formats.
737
-     *                            ex: Dec 1, 2016{$separator}2pm
738
-     * @return string
739
-     * @throws ReflectionException
740
-     * @throws InvalidArgumentException
741
-     * @throws InvalidInterfaceException
742
-     * @throws InvalidDataTypeException
743
-     * @throws EE_Error
744
-     */
745
-    public function date_and_time_range(
746
-        $dt_format = '',
747
-        $tm_format = '',
748
-        $conjunction = ' - ',
749
-        $separator = ' '
750
-    ) {
751
-        $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
752
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
753
-        $full_format = $dt_format . $separator . $tm_format;
754
-        // the range output depends on various conditions
755
-        switch (true) {
756
-            // start date timestamp and end date timestamp are the same.
757
-            case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
758
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
759
-                break;
760
-            // start and end date are the same but times are different
761
-            case ($this->start_date() === $this->end_date()):
762
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
763
-                          . $conjunction
764
-                          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
765
-                break;
766
-            // all other conditions
767
-            default:
768
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
769
-                          . $conjunction
770
-                          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
771
-                break;
772
-        }
773
-        return $output;
774
-    }
775
-
776
-
777
-    /**
778
-     * This echos the results of date and time range.
779
-     *
780
-     * @see date_and_time_range() for more details on purpose.
781
-     * @param string $dt_format
782
-     * @param string $tm_format
783
-     * @param string $conjunction
784
-     * @return void
785
-     * @throws ReflectionException
786
-     * @throws InvalidArgumentException
787
-     * @throws InvalidInterfaceException
788
-     * @throws InvalidDataTypeException
789
-     * @throws EE_Error
790
-     */
791
-    public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
792
-    {
793
-        echo $this->date_and_time_range($dt_format, $tm_format, $conjunction);
794
-    }
795
-
796
-
797
-    /**
798
-     * get start date and start time
799
-     *
800
-     * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
801
-     * @param    string $tm_format - string representation of time format defaults to 'g:i a'
802
-     * @return    mixed    string on success, FALSE on fail
803
-     * @throws ReflectionException
804
-     * @throws InvalidArgumentException
805
-     * @throws InvalidInterfaceException
806
-     * @throws InvalidDataTypeException
807
-     * @throws EE_Error
808
-     */
809
-    public function start_date_and_time($dt_format = '', $tm_format = '')
810
-    {
811
-        return $this->_show_datetime('', 'start', $dt_format, $tm_format);
812
-    }
813
-
814
-
815
-    /**
816
-     * @param string $dt_frmt
817
-     * @param string $tm_format
818
-     * @throws ReflectionException
819
-     * @throws InvalidArgumentException
820
-     * @throws InvalidInterfaceException
821
-     * @throws InvalidDataTypeException
822
-     * @throws EE_Error
823
-     */
824
-    public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
825
-    {
826
-        $this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
827
-    }
828
-
829
-
830
-    /**
831
-     * Shows the length of the event (start to end time).
832
-     * Can be shown in 'seconds','minutes','hours', or 'days'.
833
-     * By default, rounds up. (So if you use 'days', and then event
834
-     * only occurs for 1 hour, it will return 1 day).
835
-     *
836
-     * @param string $units 'seconds','minutes','hours','days'
837
-     * @param bool   $round_up
838
-     * @return float|int|mixed
839
-     * @throws ReflectionException
840
-     * @throws InvalidArgumentException
841
-     * @throws InvalidInterfaceException
842
-     * @throws InvalidDataTypeException
843
-     * @throws EE_Error
844
-     */
845
-    public function length($units = 'seconds', $round_up = false)
846
-    {
847
-        $start = $this->get_raw('DTT_EVT_start');
848
-        $end = $this->get_raw('DTT_EVT_end');
849
-        $length_in_units = $end - $start;
850
-        switch ($units) {
851
-            // NOTE: We purposefully don't use "break;" in order to chain the divisions
852
-            /** @noinspection PhpMissingBreakStatementInspection */
853
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
854
-            case 'days':
855
-                $length_in_units /= 24;
856
-            /** @noinspection PhpMissingBreakStatementInspection */
857
-            case 'hours':
858
-                // fall through is intentional
859
-                $length_in_units /= 60;
860
-            /** @noinspection PhpMissingBreakStatementInspection */
861
-            case 'minutes':
862
-                // fall through is intentional
863
-                $length_in_units /= 60;
864
-            case 'seconds':
865
-            default:
866
-                $length_in_units = ceil($length_in_units);
867
-        }
868
-        // phpcs:enable
869
-        if ($round_up) {
870
-            $length_in_units = max($length_in_units, 1);
871
-        }
872
-        return $length_in_units;
873
-    }
874
-
875
-
876
-    /**
877
-     *        get end date and time
878
-     *
879
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
880
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
881
-     * @return    mixed                string on success, FALSE on fail
882
-     * @throws ReflectionException
883
-     * @throws InvalidArgumentException
884
-     * @throws InvalidInterfaceException
885
-     * @throws InvalidDataTypeException
886
-     * @throws EE_Error
887
-     */
888
-    public function end_date_and_time($dt_frmt = '', $tm_format = '')
889
-    {
890
-        return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
891
-    }
892
-
893
-
894
-    /**
895
-     * @param string $dt_frmt
896
-     * @param string $tm_format
897
-     * @throws ReflectionException
898
-     * @throws InvalidArgumentException
899
-     * @throws InvalidInterfaceException
900
-     * @throws InvalidDataTypeException
901
-     * @throws EE_Error
902
-     */
903
-    public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
904
-    {
905
-        $this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
906
-    }
907
-
908
-
909
-    /**
910
-     *        get start timestamp
911
-     *
912
-     * @return        int
913
-     * @throws ReflectionException
914
-     * @throws InvalidArgumentException
915
-     * @throws InvalidInterfaceException
916
-     * @throws InvalidDataTypeException
917
-     * @throws EE_Error
918
-     */
919
-    public function start()
920
-    {
921
-        return $this->get_raw('DTT_EVT_start');
922
-    }
923
-
924
-
925
-    /**
926
-     *        get end timestamp
927
-     *
928
-     * @return        int
929
-     * @throws ReflectionException
930
-     * @throws InvalidArgumentException
931
-     * @throws InvalidInterfaceException
932
-     * @throws InvalidDataTypeException
933
-     * @throws EE_Error
934
-     */
935
-    public function end()
936
-    {
937
-        return $this->get_raw('DTT_EVT_end');
938
-    }
939
-
940
-
941
-    /**
942
-     *    get the registration limit for this datetime slot
943
-     *
944
-     * @return        mixed        int on success, FALSE on fail
945
-     * @throws ReflectionException
946
-     * @throws InvalidArgumentException
947
-     * @throws InvalidInterfaceException
948
-     * @throws InvalidDataTypeException
949
-     * @throws EE_Error
950
-     */
951
-    public function reg_limit()
952
-    {
953
-        return $this->get_raw('DTT_reg_limit');
954
-    }
955
-
956
-
957
-    /**
958
-     *    have the tickets sold for this datetime, met or exceed the registration limit ?
959
-     *
960
-     * @return        boolean
961
-     * @throws ReflectionException
962
-     * @throws InvalidArgumentException
963
-     * @throws InvalidInterfaceException
964
-     * @throws InvalidDataTypeException
965
-     * @throws EE_Error
966
-     */
967
-    public function sold_out()
968
-    {
969
-        return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
970
-    }
971
-
972
-
973
-    /**
974
-     * return the total number of spaces remaining at this venue.
975
-     * This only takes the venue's capacity into account, NOT the tickets available for sale
976
-     *
977
-     * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
978
-     *                               Because if all tickets attached to this datetime have no spaces left,
979
-     *                               then this datetime IS effectively sold out.
980
-     *                               However, there are cases where we just want to know the spaces
981
-     *                               remaining for this particular datetime, hence the flag.
982
-     * @return int
983
-     * @throws ReflectionException
984
-     * @throws InvalidArgumentException
985
-     * @throws InvalidInterfaceException
986
-     * @throws InvalidDataTypeException
987
-     * @throws EE_Error
988
-     */
989
-    public function spaces_remaining($consider_tickets = false)
990
-    {
991
-        // tickets remaining available for purchase
992
-        // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
993
-        $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
994
-        if (! $consider_tickets) {
995
-            return $dtt_remaining;
996
-        }
997
-        $tickets_remaining = $this->tickets_remaining();
998
-        return min($dtt_remaining, $tickets_remaining);
999
-    }
1000
-
1001
-
1002
-    /**
1003
-     * Counts the total tickets available
1004
-     * (from all the different types of tickets which are available for this datetime).
1005
-     *
1006
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1007
-     * @return int
1008
-     * @throws ReflectionException
1009
-     * @throws InvalidArgumentException
1010
-     * @throws InvalidInterfaceException
1011
-     * @throws InvalidDataTypeException
1012
-     * @throws EE_Error
1013
-     */
1014
-    public function tickets_remaining($query_params = array())
1015
-    {
1016
-        $sum = 0;
1017
-        $tickets = $this->tickets($query_params);
1018
-        if (! empty($tickets)) {
1019
-            foreach ($tickets as $ticket) {
1020
-                if ($ticket instanceof EE_Ticket) {
1021
-                    // get the actual amount of tickets that can be sold
1022
-                    $qty = $ticket->qty('saleable');
1023
-                    if ($qty === EE_INF) {
1024
-                        return EE_INF;
1025
-                    }
1026
-                    // no negative ticket quantities plz
1027
-                    if ($qty > 0) {
1028
-                        $sum += $qty;
1029
-                    }
1030
-                }
1031
-            }
1032
-        }
1033
-        return $sum;
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Gets the count of all the tickets available at this datetime (not ticket types)
1039
-     * before any were sold
1040
-     *
1041
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1042
-     * @return int
1043
-     * @throws ReflectionException
1044
-     * @throws InvalidArgumentException
1045
-     * @throws InvalidInterfaceException
1046
-     * @throws InvalidDataTypeException
1047
-     * @throws EE_Error
1048
-     */
1049
-    public function sum_tickets_initially_available($query_params = array())
1050
-    {
1051
-        return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1052
-    }
1053
-
1054
-
1055
-    /**
1056
-     * Returns the lesser-of-the two: spaces remaining at this datetime, or
1057
-     * the total tickets remaining (a sum of the tickets remaining for each ticket type
1058
-     * that is available for this datetime).
1059
-     *
1060
-     * @return int
1061
-     * @throws ReflectionException
1062
-     * @throws InvalidArgumentException
1063
-     * @throws InvalidInterfaceException
1064
-     * @throws InvalidDataTypeException
1065
-     * @throws EE_Error
1066
-     */
1067
-    public function total_tickets_available_at_this_datetime()
1068
-    {
1069
-        return $this->spaces_remaining(true);
1070
-    }
1071
-
1072
-
1073
-    /**
1074
-     * This simply compares the internal dtt for the given string with NOW
1075
-     * and determines if the date is upcoming or not.
1076
-     *
1077
-     * @access public
1078
-     * @return boolean
1079
-     * @throws ReflectionException
1080
-     * @throws InvalidArgumentException
1081
-     * @throws InvalidInterfaceException
1082
-     * @throws InvalidDataTypeException
1083
-     * @throws EE_Error
1084
-     */
1085
-    public function is_upcoming()
1086
-    {
1087
-        return ($this->get_raw('DTT_EVT_start') > time());
1088
-    }
1089
-
1090
-
1091
-    /**
1092
-     * This simply compares the internal datetime for the given string with NOW
1093
-     * and returns if the date is active (i.e. start and end time)
1094
-     *
1095
-     * @return boolean
1096
-     * @throws ReflectionException
1097
-     * @throws InvalidArgumentException
1098
-     * @throws InvalidInterfaceException
1099
-     * @throws InvalidDataTypeException
1100
-     * @throws EE_Error
1101
-     */
1102
-    public function is_active()
1103
-    {
1104
-        return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * This simply compares the internal dtt for the given string with NOW
1110
-     * and determines if the date is expired or not.
1111
-     *
1112
-     * @return boolean
1113
-     * @throws ReflectionException
1114
-     * @throws InvalidArgumentException
1115
-     * @throws InvalidInterfaceException
1116
-     * @throws InvalidDataTypeException
1117
-     * @throws EE_Error
1118
-     */
1119
-    public function is_expired()
1120
-    {
1121
-        return ($this->get_raw('DTT_EVT_end') < time());
1122
-    }
1123
-
1124
-
1125
-    /**
1126
-     * This returns the active status for whether an event is active, upcoming, or expired
1127
-     *
1128
-     * @return int return value will be one of the EE_Datetime status constants.
1129
-     * @throws ReflectionException
1130
-     * @throws InvalidArgumentException
1131
-     * @throws InvalidInterfaceException
1132
-     * @throws InvalidDataTypeException
1133
-     * @throws EE_Error
1134
-     */
1135
-    public function get_active_status()
1136
-    {
1137
-        $total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1138
-        if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1139
-            return EE_Datetime::sold_out;
1140
-        }
1141
-        if ($this->is_expired()) {
1142
-            return EE_Datetime::expired;
1143
-        }
1144
-        if ($this->is_upcoming()) {
1145
-            return EE_Datetime::upcoming;
1146
-        }
1147
-        if ($this->is_active()) {
1148
-            return EE_Datetime::active;
1149
-        }
1150
-        return null;
1151
-    }
1152
-
1153
-
1154
-    /**
1155
-     * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1156
-     *
1157
-     * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1158
-     * @return string
1159
-     * @throws ReflectionException
1160
-     * @throws InvalidArgumentException
1161
-     * @throws InvalidInterfaceException
1162
-     * @throws InvalidDataTypeException
1163
-     * @throws EE_Error
1164
-     */
1165
-    public function get_dtt_display_name($use_dtt_name = false)
1166
-    {
1167
-        if ($use_dtt_name) {
1168
-            $dtt_name = $this->name();
1169
-            if (! empty($dtt_name)) {
1170
-                return $dtt_name;
1171
-            }
1172
-        }
1173
-        // first condition is to see if the months are different
1174
-        if (date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1175
-        ) {
1176
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1177
-            // next condition is if its the same month but different day
1178
-        } else {
1179
-            if (date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1180
-                && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1181
-            ) {
1182
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1183
-            } else {
1184
-                $display_date = $this->start_date('F j\, Y')
1185
-                                . ' @ '
1186
-                                . $this->start_date('g:i a')
1187
-                                . ' - '
1188
-                                . $this->end_date('g:i a');
1189
-            }
1190
-        }
1191
-        return $display_date;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * Gets all the tickets for this datetime
1197
-     *
1198
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1199
-     * @return EE_Base_Class[]|EE_Ticket[]
1200
-     * @throws ReflectionException
1201
-     * @throws InvalidArgumentException
1202
-     * @throws InvalidInterfaceException
1203
-     * @throws InvalidDataTypeException
1204
-     * @throws EE_Error
1205
-     */
1206
-    public function tickets($query_params = array())
1207
-    {
1208
-        return $this->get_many_related('Ticket', $query_params);
1209
-    }
1210
-
1211
-
1212
-    /**
1213
-     * Gets all the ticket types currently available for purchase
1214
-     *
1215
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1216
-     * @return EE_Ticket[]
1217
-     * @throws ReflectionException
1218
-     * @throws InvalidArgumentException
1219
-     * @throws InvalidInterfaceException
1220
-     * @throws InvalidDataTypeException
1221
-     * @throws EE_Error
1222
-     */
1223
-    public function ticket_types_available_for_purchase($query_params = array())
1224
-    {
1225
-        // first check if datetime is valid
1226
-        if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1227
-            return array();
1228
-        }
1229
-        if (empty($query_params)) {
1230
-            $query_params = array(
1231
-                array(
1232
-                    'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1233
-                    'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1234
-                    'TKT_deleted'    => false,
1235
-                ),
1236
-            );
1237
-        }
1238
-        return $this->tickets($query_params);
1239
-    }
1240
-
1241
-
1242
-    /**
1243
-     * @return EE_Base_Class|EE_Event
1244
-     * @throws ReflectionException
1245
-     * @throws InvalidArgumentException
1246
-     * @throws InvalidInterfaceException
1247
-     * @throws InvalidDataTypeException
1248
-     * @throws EE_Error
1249
-     */
1250
-    public function event()
1251
-    {
1252
-        return $this->get_first_related('Event');
1253
-    }
1254
-
1255
-
1256
-    /**
1257
-     * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1258
-     * (via the tickets). into account
1259
-     *
1260
-     * @return int
1261
-     * @throws ReflectionException
1262
-     * @throws InvalidArgumentException
1263
-     * @throws InvalidInterfaceException
1264
-     * @throws InvalidDataTypeException
1265
-     * @throws EE_Error
1266
-     */
1267
-    public function update_sold()
1268
-    {
1269
-        $count_regs_for_this_datetime = EEM_Registration::instance()->count(
1270
-            array(
1271
-                array(
1272
-                    'STS_ID'                 => EEM_Registration::status_id_approved,
1273
-                    'REG_deleted'            => 0,
1274
-                    'Ticket.Datetime.DTT_ID' => $this->ID(),
1275
-                ),
1276
-            )
1277
-        );
1278
-        $sold = $this->sold();
1279
-        if ($count_regs_for_this_datetime > $sold) {
1280
-            $this->increase_sold($count_regs_for_this_datetime - $sold);
1281
-            $this->save();
1282
-        } elseif ($count_regs_for_this_datetime < $sold) {
1283
-            $this->decrease_sold($count_regs_for_this_datetime - $sold);
1284
-            $this->save();
1285
-        }
1286
-        return $count_regs_for_this_datetime;
1287
-    }
16
+	/**
17
+	 * constant used by get_active_status, indicates datetime has no more available spaces
18
+	 */
19
+	const sold_out = 'DTS';
20
+
21
+	/**
22
+	 * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
23
+	 */
24
+	const active = 'DTA';
25
+
26
+	/**
27
+	 * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
28
+	 * expired
29
+	 */
30
+	const upcoming = 'DTU';
31
+
32
+	/**
33
+	 * Datetime is postponed
34
+	 */
35
+	const postponed = 'DTP';
36
+
37
+	/**
38
+	 * Datetime is cancelled
39
+	 */
40
+	const cancelled = 'DTC';
41
+
42
+	/**
43
+	 * constant used by get_active_status, indicates datetime has expired (event is over)
44
+	 */
45
+	const expired = 'DTE';
46
+
47
+	/**
48
+	 * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
49
+	 */
50
+	const inactive = 'DTI';
51
+
52
+
53
+	/**
54
+	 * @param array  $props_n_values    incoming values
55
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
56
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
57
+	 *                                  and the second value is the time format
58
+	 * @return EE_Datetime
59
+	 * @throws ReflectionException
60
+	 * @throws InvalidArgumentException
61
+	 * @throws InvalidInterfaceException
62
+	 * @throws InvalidDataTypeException
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
66
+	{
67
+		$has_object = parent::_check_for_object(
68
+			$props_n_values,
69
+			__CLASS__,
70
+			$timezone,
71
+			$date_formats
72
+		);
73
+		return $has_object
74
+			? $has_object
75
+			: new self($props_n_values, false, $timezone, $date_formats);
76
+	}
77
+
78
+
79
+	/**
80
+	 * @param array  $props_n_values  incoming values from the database
81
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
+	 *                                the website will be used.
83
+	 * @return EE_Datetime
84
+	 * @throws ReflectionException
85
+	 * @throws InvalidArgumentException
86
+	 * @throws InvalidInterfaceException
87
+	 * @throws InvalidDataTypeException
88
+	 * @throws EE_Error
89
+	 */
90
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
+	{
92
+		return new self($props_n_values, true, $timezone);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param $name
98
+	 * @throws ReflectionException
99
+	 * @throws InvalidArgumentException
100
+	 * @throws InvalidInterfaceException
101
+	 * @throws InvalidDataTypeException
102
+	 * @throws EE_Error
103
+	 */
104
+	public function set_name($name)
105
+	{
106
+		$this->set('DTT_name', $name);
107
+	}
108
+
109
+
110
+	/**
111
+	 * @param $description
112
+	 * @throws ReflectionException
113
+	 * @throws InvalidArgumentException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws InvalidDataTypeException
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_description($description)
119
+	{
120
+		$this->set('DTT_description', $description);
121
+	}
122
+
123
+
124
+	/**
125
+	 * Set event start date
126
+	 * set the start date for an event
127
+	 *
128
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
129
+	 * @throws ReflectionException
130
+	 * @throws InvalidArgumentException
131
+	 * @throws InvalidInterfaceException
132
+	 * @throws InvalidDataTypeException
133
+	 * @throws EE_Error
134
+	 */
135
+	public function set_start_date($date)
136
+	{
137
+		$this->_set_date_for($date, 'DTT_EVT_start');
138
+	}
139
+
140
+
141
+	/**
142
+	 * Set event start time
143
+	 * set the start time for an event
144
+	 *
145
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
146
+	 * @throws ReflectionException
147
+	 * @throws InvalidArgumentException
148
+	 * @throws InvalidInterfaceException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws EE_Error
151
+	 */
152
+	public function set_start_time($time)
153
+	{
154
+		$this->_set_time_for($time, 'DTT_EVT_start');
155
+	}
156
+
157
+
158
+	/**
159
+	 * Set event end date
160
+	 * set the end date for an event
161
+	 *
162
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
163
+	 * @throws ReflectionException
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidInterfaceException
166
+	 * @throws InvalidDataTypeException
167
+	 * @throws EE_Error
168
+	 */
169
+	public function set_end_date($date)
170
+	{
171
+		$this->_set_date_for($date, 'DTT_EVT_end');
172
+	}
173
+
174
+
175
+	/**
176
+	 * Set event end time
177
+	 * set the end time for an event
178
+	 *
179
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
180
+	 * @throws ReflectionException
181
+	 * @throws InvalidArgumentException
182
+	 * @throws InvalidInterfaceException
183
+	 * @throws InvalidDataTypeException
184
+	 * @throws EE_Error
185
+	 */
186
+	public function set_end_time($time)
187
+	{
188
+		$this->_set_time_for($time, 'DTT_EVT_end');
189
+	}
190
+
191
+
192
+	/**
193
+	 * Set registration limit
194
+	 * set the maximum number of attendees that can be registered for this datetime slot
195
+	 *
196
+	 * @param int $reg_limit
197
+	 * @throws ReflectionException
198
+	 * @throws InvalidArgumentException
199
+	 * @throws InvalidInterfaceException
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws EE_Error
202
+	 */
203
+	public function set_reg_limit($reg_limit)
204
+	{
205
+		$this->set('DTT_reg_limit', $reg_limit);
206
+	}
207
+
208
+
209
+	/**
210
+	 * get the number of tickets sold for this datetime slot
211
+	 *
212
+	 * @return mixed int on success, FALSE on fail
213
+	 * @throws ReflectionException
214
+	 * @throws InvalidArgumentException
215
+	 * @throws InvalidInterfaceException
216
+	 * @throws InvalidDataTypeException
217
+	 * @throws EE_Error
218
+	 */
219
+	public function sold()
220
+	{
221
+		return $this->get_raw('DTT_sold');
222
+	}
223
+
224
+
225
+	/**
226
+	 * @param int $sold
227
+	 * @throws ReflectionException
228
+	 * @throws InvalidArgumentException
229
+	 * @throws InvalidInterfaceException
230
+	 * @throws InvalidDataTypeException
231
+	 * @throws EE_Error
232
+	 */
233
+	public function set_sold($sold)
234
+	{
235
+		// sold can not go below zero
236
+		$sold = max(0, $sold);
237
+		$this->set('DTT_sold', $sold);
238
+	}
239
+
240
+
241
+	/**
242
+	 * increments sold by amount passed by $qty
243
+	 *
244
+	 * @param int $qty
245
+	 * @throws ReflectionException
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws EE_Error
250
+	 */
251
+	public function increase_sold($qty = 1)
252
+	{
253
+		$sold = $this->sold() + $qty;
254
+		// remove ticket reservation
255
+		$this->decrease_reserved($qty);
256
+		$this->set_sold($sold);
257
+		do_action(
258
+			'AHEE__EE_Datetime__increase_sold',
259
+			$this,
260
+			$qty,
261
+			$sold
262
+		);
263
+	}
264
+
265
+
266
+	/**
267
+	 * decrements (subtracts) sold amount passed by $qty
268
+	 *
269
+	 * @param int $qty
270
+	 * @throws ReflectionException
271
+	 * @throws InvalidArgumentException
272
+	 * @throws InvalidInterfaceException
273
+	 * @throws InvalidDataTypeException
274
+	 * @throws EE_Error
275
+	 */
276
+	public function decrease_sold($qty = 1)
277
+	{
278
+		$sold = $this->sold() - $qty;
279
+		$this->set_sold($sold);
280
+		do_action(
281
+			'AHEE__EE_Datetime__decrease_sold',
282
+			$this,
283
+			$qty,
284
+			$sold
285
+		);
286
+	}
287
+
288
+
289
+	/**
290
+	 * Gets qty of reserved tickets for this datetime
291
+	 *
292
+	 * @return int
293
+	 * @throws ReflectionException
294
+	 * @throws InvalidArgumentException
295
+	 * @throws InvalidInterfaceException
296
+	 * @throws InvalidDataTypeException
297
+	 * @throws EE_Error
298
+	 */
299
+	public function reserved()
300
+	{
301
+		return $this->get_raw('DTT_reserved');
302
+	}
303
+
304
+
305
+	/**
306
+	 * Sets qty of reserved tickets for this datetime
307
+	 *
308
+	 * @param int $reserved
309
+	 * @throws ReflectionException
310
+	 * @throws InvalidArgumentException
311
+	 * @throws InvalidInterfaceException
312
+	 * @throws InvalidDataTypeException
313
+	 * @throws EE_Error
314
+	 */
315
+	public function set_reserved($reserved)
316
+	{
317
+		// reserved can not go below zero
318
+		$reserved = max(0, (int) $reserved);
319
+		$this->set('DTT_reserved', $reserved);
320
+	}
321
+
322
+
323
+	/**
324
+	 * increments reserved by amount passed by $qty
325
+	 *
326
+	 * @param int $qty
327
+	 * @return void
328
+	 * @throws ReflectionException
329
+	 * @throws InvalidArgumentException
330
+	 * @throws InvalidInterfaceException
331
+	 * @throws InvalidDataTypeException
332
+	 * @throws EE_Error
333
+	 */
334
+	public function increase_reserved($qty = 1)
335
+	{
336
+		$reserved = $this->reserved() + absint($qty);
337
+		do_action(
338
+			'AHEE__EE_Datetime__increase_reserved',
339
+			$this,
340
+			$qty,
341
+			$reserved
342
+		);
343
+		$this->set_reserved($reserved);
344
+	}
345
+
346
+
347
+	/**
348
+	 * decrements (subtracts) reserved by amount passed by $qty
349
+	 *
350
+	 * @param int $qty
351
+	 * @return void
352
+	 * @throws ReflectionException
353
+	 * @throws InvalidArgumentException
354
+	 * @throws InvalidInterfaceException
355
+	 * @throws InvalidDataTypeException
356
+	 * @throws EE_Error
357
+	 */
358
+	public function decrease_reserved($qty = 1)
359
+	{
360
+		$reserved = $this->reserved() - absint($qty);
361
+		do_action(
362
+			'AHEE__EE_Datetime__decrease_reserved',
363
+			$this,
364
+			$qty,
365
+			$reserved
366
+		);
367
+		$this->set_reserved($reserved);
368
+	}
369
+
370
+
371
+	/**
372
+	 * total sold and reserved tickets
373
+	 *
374
+	 * @return int
375
+	 * @throws ReflectionException
376
+	 * @throws InvalidArgumentException
377
+	 * @throws InvalidInterfaceException
378
+	 * @throws InvalidDataTypeException
379
+	 * @throws EE_Error
380
+	 */
381
+	public function sold_and_reserved()
382
+	{
383
+		return $this->sold() + $this->reserved();
384
+	}
385
+
386
+
387
+	/**
388
+	 * returns the datetime name
389
+	 *
390
+	 * @return string
391
+	 * @throws ReflectionException
392
+	 * @throws InvalidArgumentException
393
+	 * @throws InvalidInterfaceException
394
+	 * @throws InvalidDataTypeException
395
+	 * @throws EE_Error
396
+	 */
397
+	public function name()
398
+	{
399
+		return $this->get('DTT_name');
400
+	}
401
+
402
+
403
+	/**
404
+	 * returns the datetime description
405
+	 *
406
+	 * @return string
407
+	 * @throws ReflectionException
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidInterfaceException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws EE_Error
412
+	 */
413
+	public function description()
414
+	{
415
+		return $this->get('DTT_description');
416
+	}
417
+
418
+
419
+	/**
420
+	 * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
421
+	 *
422
+	 * @return boolean  TRUE if is primary, FALSE if not.
423
+	 * @throws ReflectionException
424
+	 * @throws InvalidArgumentException
425
+	 * @throws InvalidInterfaceException
426
+	 * @throws InvalidDataTypeException
427
+	 * @throws EE_Error
428
+	 */
429
+	public function is_primary()
430
+	{
431
+		return $this->get('DTT_is_primary');
432
+	}
433
+
434
+
435
+	/**
436
+	 * This helper simply returns the order for the datetime
437
+	 *
438
+	 * @return int  The order of the datetime for this event.
439
+	 * @throws ReflectionException
440
+	 * @throws InvalidArgumentException
441
+	 * @throws InvalidInterfaceException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws EE_Error
444
+	 */
445
+	public function order()
446
+	{
447
+		return $this->get('DTT_order');
448
+	}
449
+
450
+
451
+	/**
452
+	 * This helper simply returns the parent id for the datetime
453
+	 *
454
+	 * @return int
455
+	 * @throws ReflectionException
456
+	 * @throws InvalidArgumentException
457
+	 * @throws InvalidInterfaceException
458
+	 * @throws InvalidDataTypeException
459
+	 * @throws EE_Error
460
+	 */
461
+	public function parent()
462
+	{
463
+		return $this->get('DTT_parent');
464
+	}
465
+
466
+
467
+	/**
468
+	 * show date and/or time
469
+	 *
470
+	 * @param string $date_or_time    whether to display a date or time or both
471
+	 * @param string $start_or_end    whether to display start or end datetimes
472
+	 * @param string $dt_frmt
473
+	 * @param string $tm_frmt
474
+	 * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
475
+	 *                                otherwise we use the standard formats)
476
+	 * @return string|bool  string on success, FALSE on fail
477
+	 * @throws ReflectionException
478
+	 * @throws InvalidArgumentException
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws InvalidDataTypeException
481
+	 * @throws EE_Error
482
+	 */
483
+	private function _show_datetime(
484
+		$date_or_time = null,
485
+		$start_or_end = 'start',
486
+		$dt_frmt = '',
487
+		$tm_frmt = '',
488
+		$echo = false
489
+	) {
490
+		$field_name = "DTT_EVT_{$start_or_end}";
491
+		$dtt = $this->_get_datetime(
492
+			$field_name,
493
+			$dt_frmt,
494
+			$tm_frmt,
495
+			$date_or_time,
496
+			$echo
497
+		);
498
+		if (! $echo) {
499
+			return $dtt;
500
+		}
501
+		return '';
502
+	}
503
+
504
+
505
+	/**
506
+	 * get event start date.  Provide either the date format, or NULL to re-use the
507
+	 * last-used format, or '' to use the default date format
508
+	 *
509
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
510
+	 * @return mixed            string on success, FALSE on fail
511
+	 * @throws ReflectionException
512
+	 * @throws InvalidArgumentException
513
+	 * @throws InvalidInterfaceException
514
+	 * @throws InvalidDataTypeException
515
+	 * @throws EE_Error
516
+	 */
517
+	public function start_date($dt_frmt = '')
518
+	{
519
+		return $this->_show_datetime('D', 'start', $dt_frmt);
520
+	}
521
+
522
+
523
+	/**
524
+	 * Echoes start_date()
525
+	 *
526
+	 * @param string $dt_frmt
527
+	 * @throws ReflectionException
528
+	 * @throws InvalidArgumentException
529
+	 * @throws InvalidInterfaceException
530
+	 * @throws InvalidDataTypeException
531
+	 * @throws EE_Error
532
+	 */
533
+	public function e_start_date($dt_frmt = '')
534
+	{
535
+		$this->_show_datetime('D', 'start', $dt_frmt, null, true);
536
+	}
537
+
538
+
539
+	/**
540
+	 * get end date. Provide either the date format, or NULL to re-use the
541
+	 * last-used format, or '' to use the default date format
542
+	 *
543
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
544
+	 * @return mixed            string on success, FALSE on fail
545
+	 * @throws ReflectionException
546
+	 * @throws InvalidArgumentException
547
+	 * @throws InvalidInterfaceException
548
+	 * @throws InvalidDataTypeException
549
+	 * @throws EE_Error
550
+	 */
551
+	public function end_date($dt_frmt = '')
552
+	{
553
+		return $this->_show_datetime('D', 'end', $dt_frmt);
554
+	}
555
+
556
+
557
+	/**
558
+	 * Echoes the end date. See end_date()
559
+	 *
560
+	 * @param string $dt_frmt
561
+	 * @throws ReflectionException
562
+	 * @throws InvalidArgumentException
563
+	 * @throws InvalidInterfaceException
564
+	 * @throws InvalidDataTypeException
565
+	 * @throws EE_Error
566
+	 */
567
+	public function e_end_date($dt_frmt = '')
568
+	{
569
+		$this->_show_datetime('D', 'end', $dt_frmt, null, true);
570
+	}
571
+
572
+
573
+	/**
574
+	 * get date_range - meaning the start AND end date
575
+	 *
576
+	 * @access public
577
+	 * @param string $dt_frmt     string representation of date format defaults to WP settings
578
+	 * @param string $conjunction conjunction junction what's your function ?
579
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
580
+	 * @return mixed              string on success, FALSE on fail
581
+	 * @throws ReflectionException
582
+	 * @throws InvalidArgumentException
583
+	 * @throws InvalidInterfaceException
584
+	 * @throws InvalidDataTypeException
585
+	 * @throws EE_Error
586
+	 */
587
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
588
+	{
589
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
590
+		$start = str_replace(
591
+			' ',
592
+			'&nbsp;',
593
+			$this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
594
+		);
595
+		$end = str_replace(
596
+			' ',
597
+			'&nbsp;',
598
+			$this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
599
+		);
600
+		return $start !== $end ? $start . $conjunction . $end : $start;
601
+	}
602
+
603
+
604
+	/**
605
+	 * @param string $dt_frmt
606
+	 * @param string $conjunction
607
+	 * @throws ReflectionException
608
+	 * @throws InvalidArgumentException
609
+	 * @throws InvalidInterfaceException
610
+	 * @throws InvalidDataTypeException
611
+	 * @throws EE_Error
612
+	 */
613
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ')
614
+	{
615
+		echo $this->date_range($dt_frmt, $conjunction);
616
+	}
617
+
618
+
619
+	/**
620
+	 * get start time
621
+	 *
622
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
623
+	 * @return mixed        string on success, FALSE on fail
624
+	 * @throws ReflectionException
625
+	 * @throws InvalidArgumentException
626
+	 * @throws InvalidInterfaceException
627
+	 * @throws InvalidDataTypeException
628
+	 * @throws EE_Error
629
+	 */
630
+	public function start_time($tm_format = '')
631
+	{
632
+		return $this->_show_datetime('T', 'start', null, $tm_format);
633
+	}
634
+
635
+
636
+	/**
637
+	 * @param string $tm_format
638
+	 * @throws ReflectionException
639
+	 * @throws InvalidArgumentException
640
+	 * @throws InvalidInterfaceException
641
+	 * @throws InvalidDataTypeException
642
+	 * @throws EE_Error
643
+	 */
644
+	public function e_start_time($tm_format = '')
645
+	{
646
+		$this->_show_datetime('T', 'start', null, $tm_format, true);
647
+	}
648
+
649
+
650
+	/**
651
+	 * get end time
652
+	 *
653
+	 * @param string $tm_format string representation of time format defaults to 'g:i a'
654
+	 * @return mixed                string on success, FALSE on fail
655
+	 * @throws ReflectionException
656
+	 * @throws InvalidArgumentException
657
+	 * @throws InvalidInterfaceException
658
+	 * @throws InvalidDataTypeException
659
+	 * @throws EE_Error
660
+	 */
661
+	public function end_time($tm_format = '')
662
+	{
663
+		return $this->_show_datetime('T', 'end', null, $tm_format);
664
+	}
665
+
666
+
667
+	/**
668
+	 * @param string $tm_format
669
+	 * @throws ReflectionException
670
+	 * @throws InvalidArgumentException
671
+	 * @throws InvalidInterfaceException
672
+	 * @throws InvalidDataTypeException
673
+	 * @throws EE_Error
674
+	 */
675
+	public function e_end_time($tm_format = '')
676
+	{
677
+		$this->_show_datetime('T', 'end', null, $tm_format, true);
678
+	}
679
+
680
+
681
+	/**
682
+	 * get time_range
683
+	 *
684
+	 * @access public
685
+	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
686
+	 * @param string $conjunction conjunction junction what's your function ?
687
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
688
+	 * @return mixed              string on success, FALSE on fail
689
+	 * @throws ReflectionException
690
+	 * @throws InvalidArgumentException
691
+	 * @throws InvalidInterfaceException
692
+	 * @throws InvalidDataTypeException
693
+	 * @throws EE_Error
694
+	 */
695
+	public function time_range($tm_format = '', $conjunction = ' - ')
696
+	{
697
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
698
+		$start = str_replace(
699
+			' ',
700
+			'&nbsp;',
701
+			$this->get_i18n_datetime('DTT_EVT_start', $tm_format)
702
+		);
703
+		$end = str_replace(
704
+			' ',
705
+			'&nbsp;',
706
+			$this->get_i18n_datetime('DTT_EVT_end', $tm_format)
707
+		);
708
+		return $start !== $end ? $start . $conjunction . $end : $start;
709
+	}
710
+
711
+
712
+	/**
713
+	 * @param string $tm_format
714
+	 * @param string $conjunction
715
+	 * @throws ReflectionException
716
+	 * @throws InvalidArgumentException
717
+	 * @throws InvalidInterfaceException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws EE_Error
720
+	 */
721
+	public function e_time_range($tm_format = '', $conjunction = ' - ')
722
+	{
723
+		echo $this->time_range($tm_format, $conjunction);
724
+	}
725
+
726
+
727
+	/**
728
+	 * This returns a range representation of the date and times.
729
+	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
730
+	 * Also, the return value is localized.
731
+	 *
732
+	 * @param string $dt_format
733
+	 * @param string $tm_format
734
+	 * @param string $conjunction used between two different dates or times.
735
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
736
+	 * @param string $separator   used between the date and time formats.
737
+	 *                            ex: Dec 1, 2016{$separator}2pm
738
+	 * @return string
739
+	 * @throws ReflectionException
740
+	 * @throws InvalidArgumentException
741
+	 * @throws InvalidInterfaceException
742
+	 * @throws InvalidDataTypeException
743
+	 * @throws EE_Error
744
+	 */
745
+	public function date_and_time_range(
746
+		$dt_format = '',
747
+		$tm_format = '',
748
+		$conjunction = ' - ',
749
+		$separator = ' '
750
+	) {
751
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
752
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
753
+		$full_format = $dt_format . $separator . $tm_format;
754
+		// the range output depends on various conditions
755
+		switch (true) {
756
+			// start date timestamp and end date timestamp are the same.
757
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
758
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
759
+				break;
760
+			// start and end date are the same but times are different
761
+			case ($this->start_date() === $this->end_date()):
762
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
763
+						  . $conjunction
764
+						  . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
765
+				break;
766
+			// all other conditions
767
+			default:
768
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
769
+						  . $conjunction
770
+						  . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
771
+				break;
772
+		}
773
+		return $output;
774
+	}
775
+
776
+
777
+	/**
778
+	 * This echos the results of date and time range.
779
+	 *
780
+	 * @see date_and_time_range() for more details on purpose.
781
+	 * @param string $dt_format
782
+	 * @param string $tm_format
783
+	 * @param string $conjunction
784
+	 * @return void
785
+	 * @throws ReflectionException
786
+	 * @throws InvalidArgumentException
787
+	 * @throws InvalidInterfaceException
788
+	 * @throws InvalidDataTypeException
789
+	 * @throws EE_Error
790
+	 */
791
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
792
+	{
793
+		echo $this->date_and_time_range($dt_format, $tm_format, $conjunction);
794
+	}
795
+
796
+
797
+	/**
798
+	 * get start date and start time
799
+	 *
800
+	 * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
801
+	 * @param    string $tm_format - string representation of time format defaults to 'g:i a'
802
+	 * @return    mixed    string on success, FALSE on fail
803
+	 * @throws ReflectionException
804
+	 * @throws InvalidArgumentException
805
+	 * @throws InvalidInterfaceException
806
+	 * @throws InvalidDataTypeException
807
+	 * @throws EE_Error
808
+	 */
809
+	public function start_date_and_time($dt_format = '', $tm_format = '')
810
+	{
811
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
812
+	}
813
+
814
+
815
+	/**
816
+	 * @param string $dt_frmt
817
+	 * @param string $tm_format
818
+	 * @throws ReflectionException
819
+	 * @throws InvalidArgumentException
820
+	 * @throws InvalidInterfaceException
821
+	 * @throws InvalidDataTypeException
822
+	 * @throws EE_Error
823
+	 */
824
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
825
+	{
826
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
827
+	}
828
+
829
+
830
+	/**
831
+	 * Shows the length of the event (start to end time).
832
+	 * Can be shown in 'seconds','minutes','hours', or 'days'.
833
+	 * By default, rounds up. (So if you use 'days', and then event
834
+	 * only occurs for 1 hour, it will return 1 day).
835
+	 *
836
+	 * @param string $units 'seconds','minutes','hours','days'
837
+	 * @param bool   $round_up
838
+	 * @return float|int|mixed
839
+	 * @throws ReflectionException
840
+	 * @throws InvalidArgumentException
841
+	 * @throws InvalidInterfaceException
842
+	 * @throws InvalidDataTypeException
843
+	 * @throws EE_Error
844
+	 */
845
+	public function length($units = 'seconds', $round_up = false)
846
+	{
847
+		$start = $this->get_raw('DTT_EVT_start');
848
+		$end = $this->get_raw('DTT_EVT_end');
849
+		$length_in_units = $end - $start;
850
+		switch ($units) {
851
+			// NOTE: We purposefully don't use "break;" in order to chain the divisions
852
+			/** @noinspection PhpMissingBreakStatementInspection */
853
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
854
+			case 'days':
855
+				$length_in_units /= 24;
856
+			/** @noinspection PhpMissingBreakStatementInspection */
857
+			case 'hours':
858
+				// fall through is intentional
859
+				$length_in_units /= 60;
860
+			/** @noinspection PhpMissingBreakStatementInspection */
861
+			case 'minutes':
862
+				// fall through is intentional
863
+				$length_in_units /= 60;
864
+			case 'seconds':
865
+			default:
866
+				$length_in_units = ceil($length_in_units);
867
+		}
868
+		// phpcs:enable
869
+		if ($round_up) {
870
+			$length_in_units = max($length_in_units, 1);
871
+		}
872
+		return $length_in_units;
873
+	}
874
+
875
+
876
+	/**
877
+	 *        get end date and time
878
+	 *
879
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
880
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
881
+	 * @return    mixed                string on success, FALSE on fail
882
+	 * @throws ReflectionException
883
+	 * @throws InvalidArgumentException
884
+	 * @throws InvalidInterfaceException
885
+	 * @throws InvalidDataTypeException
886
+	 * @throws EE_Error
887
+	 */
888
+	public function end_date_and_time($dt_frmt = '', $tm_format = '')
889
+	{
890
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
891
+	}
892
+
893
+
894
+	/**
895
+	 * @param string $dt_frmt
896
+	 * @param string $tm_format
897
+	 * @throws ReflectionException
898
+	 * @throws InvalidArgumentException
899
+	 * @throws InvalidInterfaceException
900
+	 * @throws InvalidDataTypeException
901
+	 * @throws EE_Error
902
+	 */
903
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
904
+	{
905
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
906
+	}
907
+
908
+
909
+	/**
910
+	 *        get start timestamp
911
+	 *
912
+	 * @return        int
913
+	 * @throws ReflectionException
914
+	 * @throws InvalidArgumentException
915
+	 * @throws InvalidInterfaceException
916
+	 * @throws InvalidDataTypeException
917
+	 * @throws EE_Error
918
+	 */
919
+	public function start()
920
+	{
921
+		return $this->get_raw('DTT_EVT_start');
922
+	}
923
+
924
+
925
+	/**
926
+	 *        get end timestamp
927
+	 *
928
+	 * @return        int
929
+	 * @throws ReflectionException
930
+	 * @throws InvalidArgumentException
931
+	 * @throws InvalidInterfaceException
932
+	 * @throws InvalidDataTypeException
933
+	 * @throws EE_Error
934
+	 */
935
+	public function end()
936
+	{
937
+		return $this->get_raw('DTT_EVT_end');
938
+	}
939
+
940
+
941
+	/**
942
+	 *    get the registration limit for this datetime slot
943
+	 *
944
+	 * @return        mixed        int on success, FALSE on fail
945
+	 * @throws ReflectionException
946
+	 * @throws InvalidArgumentException
947
+	 * @throws InvalidInterfaceException
948
+	 * @throws InvalidDataTypeException
949
+	 * @throws EE_Error
950
+	 */
951
+	public function reg_limit()
952
+	{
953
+		return $this->get_raw('DTT_reg_limit');
954
+	}
955
+
956
+
957
+	/**
958
+	 *    have the tickets sold for this datetime, met or exceed the registration limit ?
959
+	 *
960
+	 * @return        boolean
961
+	 * @throws ReflectionException
962
+	 * @throws InvalidArgumentException
963
+	 * @throws InvalidInterfaceException
964
+	 * @throws InvalidDataTypeException
965
+	 * @throws EE_Error
966
+	 */
967
+	public function sold_out()
968
+	{
969
+		return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
970
+	}
971
+
972
+
973
+	/**
974
+	 * return the total number of spaces remaining at this venue.
975
+	 * This only takes the venue's capacity into account, NOT the tickets available for sale
976
+	 *
977
+	 * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
978
+	 *                               Because if all tickets attached to this datetime have no spaces left,
979
+	 *                               then this datetime IS effectively sold out.
980
+	 *                               However, there are cases where we just want to know the spaces
981
+	 *                               remaining for this particular datetime, hence the flag.
982
+	 * @return int
983
+	 * @throws ReflectionException
984
+	 * @throws InvalidArgumentException
985
+	 * @throws InvalidInterfaceException
986
+	 * @throws InvalidDataTypeException
987
+	 * @throws EE_Error
988
+	 */
989
+	public function spaces_remaining($consider_tickets = false)
990
+	{
991
+		// tickets remaining available for purchase
992
+		// no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
993
+		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
994
+		if (! $consider_tickets) {
995
+			return $dtt_remaining;
996
+		}
997
+		$tickets_remaining = $this->tickets_remaining();
998
+		return min($dtt_remaining, $tickets_remaining);
999
+	}
1000
+
1001
+
1002
+	/**
1003
+	 * Counts the total tickets available
1004
+	 * (from all the different types of tickets which are available for this datetime).
1005
+	 *
1006
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1007
+	 * @return int
1008
+	 * @throws ReflectionException
1009
+	 * @throws InvalidArgumentException
1010
+	 * @throws InvalidInterfaceException
1011
+	 * @throws InvalidDataTypeException
1012
+	 * @throws EE_Error
1013
+	 */
1014
+	public function tickets_remaining($query_params = array())
1015
+	{
1016
+		$sum = 0;
1017
+		$tickets = $this->tickets($query_params);
1018
+		if (! empty($tickets)) {
1019
+			foreach ($tickets as $ticket) {
1020
+				if ($ticket instanceof EE_Ticket) {
1021
+					// get the actual amount of tickets that can be sold
1022
+					$qty = $ticket->qty('saleable');
1023
+					if ($qty === EE_INF) {
1024
+						return EE_INF;
1025
+					}
1026
+					// no negative ticket quantities plz
1027
+					if ($qty > 0) {
1028
+						$sum += $qty;
1029
+					}
1030
+				}
1031
+			}
1032
+		}
1033
+		return $sum;
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Gets the count of all the tickets available at this datetime (not ticket types)
1039
+	 * before any were sold
1040
+	 *
1041
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1042
+	 * @return int
1043
+	 * @throws ReflectionException
1044
+	 * @throws InvalidArgumentException
1045
+	 * @throws InvalidInterfaceException
1046
+	 * @throws InvalidDataTypeException
1047
+	 * @throws EE_Error
1048
+	 */
1049
+	public function sum_tickets_initially_available($query_params = array())
1050
+	{
1051
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1052
+	}
1053
+
1054
+
1055
+	/**
1056
+	 * Returns the lesser-of-the two: spaces remaining at this datetime, or
1057
+	 * the total tickets remaining (a sum of the tickets remaining for each ticket type
1058
+	 * that is available for this datetime).
1059
+	 *
1060
+	 * @return int
1061
+	 * @throws ReflectionException
1062
+	 * @throws InvalidArgumentException
1063
+	 * @throws InvalidInterfaceException
1064
+	 * @throws InvalidDataTypeException
1065
+	 * @throws EE_Error
1066
+	 */
1067
+	public function total_tickets_available_at_this_datetime()
1068
+	{
1069
+		return $this->spaces_remaining(true);
1070
+	}
1071
+
1072
+
1073
+	/**
1074
+	 * This simply compares the internal dtt for the given string with NOW
1075
+	 * and determines if the date is upcoming or not.
1076
+	 *
1077
+	 * @access public
1078
+	 * @return boolean
1079
+	 * @throws ReflectionException
1080
+	 * @throws InvalidArgumentException
1081
+	 * @throws InvalidInterfaceException
1082
+	 * @throws InvalidDataTypeException
1083
+	 * @throws EE_Error
1084
+	 */
1085
+	public function is_upcoming()
1086
+	{
1087
+		return ($this->get_raw('DTT_EVT_start') > time());
1088
+	}
1089
+
1090
+
1091
+	/**
1092
+	 * This simply compares the internal datetime for the given string with NOW
1093
+	 * and returns if the date is active (i.e. start and end time)
1094
+	 *
1095
+	 * @return boolean
1096
+	 * @throws ReflectionException
1097
+	 * @throws InvalidArgumentException
1098
+	 * @throws InvalidInterfaceException
1099
+	 * @throws InvalidDataTypeException
1100
+	 * @throws EE_Error
1101
+	 */
1102
+	public function is_active()
1103
+	{
1104
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * This simply compares the internal dtt for the given string with NOW
1110
+	 * and determines if the date is expired or not.
1111
+	 *
1112
+	 * @return boolean
1113
+	 * @throws ReflectionException
1114
+	 * @throws InvalidArgumentException
1115
+	 * @throws InvalidInterfaceException
1116
+	 * @throws InvalidDataTypeException
1117
+	 * @throws EE_Error
1118
+	 */
1119
+	public function is_expired()
1120
+	{
1121
+		return ($this->get_raw('DTT_EVT_end') < time());
1122
+	}
1123
+
1124
+
1125
+	/**
1126
+	 * This returns the active status for whether an event is active, upcoming, or expired
1127
+	 *
1128
+	 * @return int return value will be one of the EE_Datetime status constants.
1129
+	 * @throws ReflectionException
1130
+	 * @throws InvalidArgumentException
1131
+	 * @throws InvalidInterfaceException
1132
+	 * @throws InvalidDataTypeException
1133
+	 * @throws EE_Error
1134
+	 */
1135
+	public function get_active_status()
1136
+	{
1137
+		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1138
+		if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1139
+			return EE_Datetime::sold_out;
1140
+		}
1141
+		if ($this->is_expired()) {
1142
+			return EE_Datetime::expired;
1143
+		}
1144
+		if ($this->is_upcoming()) {
1145
+			return EE_Datetime::upcoming;
1146
+		}
1147
+		if ($this->is_active()) {
1148
+			return EE_Datetime::active;
1149
+		}
1150
+		return null;
1151
+	}
1152
+
1153
+
1154
+	/**
1155
+	 * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1156
+	 *
1157
+	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1158
+	 * @return string
1159
+	 * @throws ReflectionException
1160
+	 * @throws InvalidArgumentException
1161
+	 * @throws InvalidInterfaceException
1162
+	 * @throws InvalidDataTypeException
1163
+	 * @throws EE_Error
1164
+	 */
1165
+	public function get_dtt_display_name($use_dtt_name = false)
1166
+	{
1167
+		if ($use_dtt_name) {
1168
+			$dtt_name = $this->name();
1169
+			if (! empty($dtt_name)) {
1170
+				return $dtt_name;
1171
+			}
1172
+		}
1173
+		// first condition is to see if the months are different
1174
+		if (date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1175
+		) {
1176
+			$display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1177
+			// next condition is if its the same month but different day
1178
+		} else {
1179
+			if (date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1180
+				&& date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1181
+			) {
1182
+				$display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1183
+			} else {
1184
+				$display_date = $this->start_date('F j\, Y')
1185
+								. ' @ '
1186
+								. $this->start_date('g:i a')
1187
+								. ' - '
1188
+								. $this->end_date('g:i a');
1189
+			}
1190
+		}
1191
+		return $display_date;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * Gets all the tickets for this datetime
1197
+	 *
1198
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1199
+	 * @return EE_Base_Class[]|EE_Ticket[]
1200
+	 * @throws ReflectionException
1201
+	 * @throws InvalidArgumentException
1202
+	 * @throws InvalidInterfaceException
1203
+	 * @throws InvalidDataTypeException
1204
+	 * @throws EE_Error
1205
+	 */
1206
+	public function tickets($query_params = array())
1207
+	{
1208
+		return $this->get_many_related('Ticket', $query_params);
1209
+	}
1210
+
1211
+
1212
+	/**
1213
+	 * Gets all the ticket types currently available for purchase
1214
+	 *
1215
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1216
+	 * @return EE_Ticket[]
1217
+	 * @throws ReflectionException
1218
+	 * @throws InvalidArgumentException
1219
+	 * @throws InvalidInterfaceException
1220
+	 * @throws InvalidDataTypeException
1221
+	 * @throws EE_Error
1222
+	 */
1223
+	public function ticket_types_available_for_purchase($query_params = array())
1224
+	{
1225
+		// first check if datetime is valid
1226
+		if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1227
+			return array();
1228
+		}
1229
+		if (empty($query_params)) {
1230
+			$query_params = array(
1231
+				array(
1232
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1233
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1234
+					'TKT_deleted'    => false,
1235
+				),
1236
+			);
1237
+		}
1238
+		return $this->tickets($query_params);
1239
+	}
1240
+
1241
+
1242
+	/**
1243
+	 * @return EE_Base_Class|EE_Event
1244
+	 * @throws ReflectionException
1245
+	 * @throws InvalidArgumentException
1246
+	 * @throws InvalidInterfaceException
1247
+	 * @throws InvalidDataTypeException
1248
+	 * @throws EE_Error
1249
+	 */
1250
+	public function event()
1251
+	{
1252
+		return $this->get_first_related('Event');
1253
+	}
1254
+
1255
+
1256
+	/**
1257
+	 * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1258
+	 * (via the tickets). into account
1259
+	 *
1260
+	 * @return int
1261
+	 * @throws ReflectionException
1262
+	 * @throws InvalidArgumentException
1263
+	 * @throws InvalidInterfaceException
1264
+	 * @throws InvalidDataTypeException
1265
+	 * @throws EE_Error
1266
+	 */
1267
+	public function update_sold()
1268
+	{
1269
+		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
1270
+			array(
1271
+				array(
1272
+					'STS_ID'                 => EEM_Registration::status_id_approved,
1273
+					'REG_deleted'            => 0,
1274
+					'Ticket.Datetime.DTT_ID' => $this->ID(),
1275
+				),
1276
+			)
1277
+		);
1278
+		$sold = $this->sold();
1279
+		if ($count_regs_for_this_datetime > $sold) {
1280
+			$this->increase_sold($count_regs_for_this_datetime - $sold);
1281
+			$this->save();
1282
+		} elseif ($count_regs_for_this_datetime < $sold) {
1283
+			$this->decrease_sold($count_regs_for_this_datetime - $sold);
1284
+			$this->save();
1285
+		}
1286
+		return $count_regs_for_this_datetime;
1287
+	}
1288 1288
 }
Please login to merge, or discard this patch.