Completed
Branch BUG-10381-asset-loading (189bf4)
by
unknown
13:54
created
core/db_models/EEM_Datetime.model.php 1 patch
Indentation   +581 added lines, -581 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Class Datetime Model
@@ -11,586 +11,586 @@  discard block
 block discarded – undo
11 11
 class EEM_Datetime extends EEM_Soft_Delete_Base
12 12
 {
13 13
 
14
-    /**
15
-     * @var EEM_Datetime $_instance
16
-     */
17
-    protected static $_instance;
18
-
19
-
20
-
21
-    /**
22
-     *        private constructor to prevent direct creation
23
-     *
24
-     * @Constructor
25
-     * @access private
26
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
27
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
28
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
29
-     *                         timezone in the 'timezone_string' wp option)
30
-     * @throws \EE_Error
31
-     */
32
-    protected function __construct($timezone)
33
-    {
34
-        $this->singular_item = __('Datetime', 'event_espresso');
35
-        $this->plural_item = __('Datetimes', 'event_espresso');
36
-        $this->_tables = array(
37
-            'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
38
-        );
39
-        $this->_fields = array(
40
-            'Datetime' => array(
41
-                'DTT_ID'          => new EE_Primary_Key_Int_Field('DTT_ID', __('Datetime ID', 'event_espresso')),
42
-                'EVT_ID'          => new EE_Foreign_Key_Int_Field(
43
-                    'EVT_ID', __('Event ID', 'event_espresso'), false, 0, 'Event'
44
-                ),
45
-                'DTT_name'        => new EE_Plain_Text_Field(
46
-                    'DTT_name', __('Datetime Name', 'event_espresso'), false, ''
47
-                ),
48
-                'DTT_description' => new EE_Post_Content_Field(
49
-                    'DTT_description', __('Description for Datetime', 'event_espresso'), false, ''
50
-                ),
51
-                'DTT_EVT_start'   => new EE_Datetime_Field(
52
-                    'DTT_EVT_start', __('Start time/date of Event', 'event_espresso'), false, EE_Datetime_Field::now,
53
-                    $timezone
54
-                ),
55
-                'DTT_EVT_end'     => new EE_Datetime_Field(
56
-                    'DTT_EVT_end', __('End time/date of Event', 'event_espresso'), false, EE_Datetime_Field::now,
57
-                    $timezone
58
-                ),
59
-                'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
60
-                    'DTT_reg_limit', __('Registration Limit for this time', 'event_espresso'), true, EE_INF),
61
-                'DTT_sold'        => new EE_Integer_Field(
62
-                    'DTT_sold', __('How many sales for this Datetime that have occurred', 'event_espresso'), true, 0
63
-                ),
64
-                'DTT_reserved' => new EE_Integer_Field('DTT_reserved',
65
-                    __('Quantity of tickets reserved, but not yet fully purchased', 'event_espresso'), false, 0
66
-                ),
67
-                'DTT_is_primary'  => new EE_Boolean_Field(
68
-                    'DTT_is_primary', __('Flag indicating datetime is primary one for event', 'event_espresso'),
69
-                    false, false
70
-                ),
71
-                'DTT_order'       => new EE_Integer_Field(
72
-                    'DTT_order', __('The order in which the Datetime is displayed', 'event_espresso'), false, 0
73
-                ),
74
-                'DTT_parent'      => new EE_Integer_Field(
75
-                    'DTT_parent', __('Indicates what DTT_ID is the parent of this DTT_ID'), true, 0
76
-                ),
77
-                'DTT_deleted'     => new EE_Trashed_Flag_Field(
78
-                    'DTT_deleted', __('Flag indicating datetime is archived', 'event_espresso'), false, false
79
-                ),
80
-            ),
81
-        );
82
-        $this->_model_relations = array(
83
-            'Ticket'  => new EE_HABTM_Relation('Datetime_Ticket'),
84
-            'Event'   => new EE_Belongs_To_Relation(),
85
-            'Checkin' => new EE_Has_Many_Relation(),
86
-        );
87
-        $this->_model_chain_to_wp_user = 'Event';
88
-        //this model is generally available for reading
89
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Event_Related_Public('Event');
90
-        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Event_Related_Protected('Event');
91
-        $this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Event_Related_Protected('Event');
92
-        $this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Event_Related_Protected('Event',
93
-            EEM_Base::caps_edit);
94
-        parent::__construct($timezone);
95
-    }
96
-
97
-
98
-
99
-    /**
100
-     * create new blank datetime
101
-     *
102
-     * @access public
103
-     * @return EE_Datetime[] array on success, FALSE on fail
104
-     * @throws \EE_Error
105
-     */
106
-    public function create_new_blank_datetime()
107
-    {
108
-        //makes sure timezone is always set.
109
-        $timezone_string = $this->get_timezone();
110
-        $blank_datetime = EE_Datetime::new_instance(
111
-            array(
112
-                'DTT_EVT_start' => $this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS,
113
-                'DTT_EVT_end'   => $this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS,
114
-                'DTT_order'     => 1,
115
-                'DTT_reg_limit' => EE_INF,
116
-            ),
117
-            $timezone_string
118
-        );
119
-        $blank_datetime->set_start_time($this->convert_datetime_for_query('DTT_EVT_start', '8am', 'ga',
120
-            $timezone_string));
121
-        $blank_datetime->set_end_time($this->convert_datetime_for_query('DTT_EVT_end', '5pm', 'ga', $timezone_string));
122
-        return array($blank_datetime);
123
-    }
124
-
125
-
126
-
127
-    /**
128
-     * get event start date from db
129
-     *
130
-     * @access public
131
-     * @param  int $EVT_ID
132
-     * @return EE_Datetime[] array on success, FALSE on fail
133
-     * @throws \EE_Error
134
-     */
135
-    public function get_all_event_dates($EVT_ID = 0)
136
-    {
137
-        if ( ! $EVT_ID) { // on add_new_event event_id gets set to 0
138
-            return $this->create_new_blank_datetime();
139
-        }
140
-        $results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
141
-        if (empty($results)) {
142
-            return $this->create_new_blank_datetime();
143
-        }
144
-        return $results;
145
-    }
146
-
147
-
148
-
149
-    /**
150
-     * get all datetimes attached to an event ordered by the DTT_order field
151
-     *
152
-     * @public
153
-     * @param  int    $EVT_ID     event id
154
-     * @param boolean $include_expired
155
-     * @param boolean $include_deleted
156
-     * @param  int    $limit      If included then limit the count of results by
157
-     *                            the given number
158
-     * @return EE_Datetime[]
159
-     * @throws \EE_Error
160
-     */
161
-    public function get_datetimes_for_event_ordered_by_DTT_order(
162
-        $EVT_ID,
163
-        $include_expired = true,
164
-        $include_deleted = true,
165
-        $limit = null
166
-    ) {
167
-        //sanitize EVT_ID
168
-        $EVT_ID = absint($EVT_ID);
169
-        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
170
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
171
-        $where_params = array('Event.EVT_ID' => $EVT_ID);
172
-        $query_params = ! empty($limit)
173
-            ? array(
174
-                $where_params,
175
-                'limit'                    => $limit,
176
-                'order_by'                 => array('DTT_order' => 'ASC'),
177
-                'default_where_conditions' => 'none',
178
-            )
179
-            : array(
180
-                $where_params,
181
-                'order_by'                 => array('DTT_order' => 'ASC'),
182
-                'default_where_conditions' => 'none',
183
-            );
184
-        if ( ! $include_expired) {
185
-            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
186
-        }
187
-        if ($include_deleted) {
188
-            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
189
-        }
190
-        /** @var EE_Datetime[] $result */
191
-        $result = $this->get_all($query_params);
192
-        $this->assume_values_already_prepared_by_model_object($old_assumption);
193
-        return $result;
194
-    }
195
-
196
-
197
-
198
-    /**
199
-     * Gets the datetimes for the event (with the given limit), and orders them by "importance". By importance, we mean
200
-     * that the primary datetimes are most important (DEPRECATED FOR NOW), and then the earlier datetimes are the most
201
-     * important. Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
202
-     *
203
-     * @param int $EVT_ID
204
-     * @param int $limit
205
-     * @return EE_Datetime[]|EE_Base_Class[]
206
-     * @throws \EE_Error
207
-     */
208
-    public function get_datetimes_for_event_ordered_by_importance($EVT_ID = 0, $limit = null)
209
-    {
210
-        return $this->get_all(
211
-            array(
212
-                array('Event.EVT_ID' => $EVT_ID),
213
-                'limit'                    => $limit,
214
-                'order_by'                 => array('DTT_EVT_start' => 'ASC'),
215
-                'default_where_conditions' => 'none',
216
-            )
217
-        );
218
-    }
219
-
220
-
221
-
222
-    /**
223
-     * @param int     $EVT_ID
224
-     * @param boolean $include_expired
225
-     * @param boolean $include_deleted
226
-     * @return EE_Datetime
227
-     * @throws \EE_Error
228
-     */
229
-    public function get_oldest_datetime_for_event($EVT_ID, $include_expired = false, $include_deleted = false)
230
-    {
231
-        $results = $this->get_datetimes_for_event_ordered_by_start_time($EVT_ID, $include_expired, $include_deleted, 1);
232
-        if ($results) {
233
-            return array_shift($results);
234
-        } else {
235
-            return null;
236
-        }
237
-    }
238
-
239
-
240
-
241
-    /**
242
-     * Gets the 'primary' datetime for an event.
243
-     *
244
-     * @param int  $EVT_ID
245
-     * @param bool $try_to_exclude_expired
246
-     * @param bool $try_to_exclude_deleted
247
-     * @return \EE_Datetime
248
-     * @throws \EE_Error
249
-     */
250
-    public function get_primary_datetime_for_event(
251
-        $EVT_ID,
252
-        $try_to_exclude_expired = true,
253
-        $try_to_exclude_deleted = true
254
-    ) {
255
-        if ($try_to_exclude_expired) {
256
-            $non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
257
-            if ($non_expired) {
258
-                return $non_expired;
259
-            }
260
-        }
261
-        if ($try_to_exclude_deleted) {
262
-            $expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
263
-            if ($expired_even) {
264
-                return $expired_even;
265
-            }
266
-        }
267
-        return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
268
-    }
269
-
270
-
271
-
272
-    /**
273
-     * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
274
-     * only by start date
275
-     *
276
-     * @param int     $EVT_ID
277
-     * @param boolean $include_expired
278
-     * @param boolean $include_deleted
279
-     * @param int     $limit
280
-     * @return EE_Datetime[]
281
-     * @throws \EE_Error
282
-     */
283
-    public function get_datetimes_for_event_ordered_by_start_time(
284
-        $EVT_ID,
285
-        $include_expired = true,
286
-        $include_deleted = true,
287
-        $limit = null
288
-    ) {
289
-        //sanitize EVT_ID
290
-        $EVT_ID = absint($EVT_ID);
291
-        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
292
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
293
-        $query_params = array(array('Event.EVT_ID' => $EVT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
294
-        if ( ! $include_expired) {
295
-            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
296
-        }
297
-        if ($include_deleted) {
298
-            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
299
-        }
300
-        if ($limit) {
301
-            $query_params['limit'] = $limit;
302
-        }
303
-        /** @var EE_Datetime[] $result */
304
-        $result = $this->get_all($query_params);
305
-        $this->assume_values_already_prepared_by_model_object($old_assumption);
306
-        return $result;
307
-    }
308
-
309
-
310
-
311
-    /**
312
-     * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
313
-     * only by start date
314
-     *
315
-     * @param int     $TKT_ID
316
-     * @param boolean $include_expired
317
-     * @param boolean $include_deleted
318
-     * @param int     $limit
319
-     * @return EE_Datetime[]
320
-     * @throws \EE_Error
321
-     */
322
-    public function get_datetimes_for_ticket_ordered_by_start_time(
323
-        $TKT_ID,
324
-        $include_expired = true,
325
-        $include_deleted = true,
326
-        $limit = null
327
-    ) {
328
-        //sanitize TKT_ID
329
-        $TKT_ID = absint($TKT_ID);
330
-        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
331
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
332
-        $query_params = array(array('Ticket.TKT_ID' => $TKT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
333
-        if ( ! $include_expired) {
334
-            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
335
-        }
336
-        if ($include_deleted) {
337
-            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
338
-        }
339
-        if ($limit) {
340
-            $query_params['limit'] = $limit;
341
-        }
342
-        /** @var EE_Datetime[] $result */
343
-        $result = $this->get_all($query_params);
344
-        $this->assume_values_already_prepared_by_model_object($old_assumption);
345
-        return $result;
346
-    }
347
-
348
-
349
-
350
-    /**
351
-     * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
352
-     * datetimes.
353
-     *
354
-     * @param  int      $TKT_ID          ID of ticket to retrieve the datetimes for
355
-     * @param  boolean  $include_expired whether to include expired datetimes or not
356
-     * @param  boolean  $include_deleted whether to include trashed datetimes or not.
357
-     * @param  int|null $limit           if null, no limit, if int then limit results by
358
-     *                                   that number
359
-     * @return EE_Datetime[]
360
-     * @throws \EE_Error
361
-     */
362
-    public function get_datetimes_for_ticket_ordered_by_DTT_order(
363
-        $TKT_ID,
364
-        $include_expired = true,
365
-        $include_deleted = true,
366
-        $limit = null
367
-    ) {
368
-        //sanitize id.
369
-        $TKT_ID = absint($TKT_ID);
370
-        $old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
371
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
372
-        $where_params = array('Ticket.TKT_ID' => $TKT_ID);
373
-        $query_params = array($where_params, 'order_by' => array('DTT_order' => 'ASC'));
374
-        if ( ! $include_expired) {
375
-            $query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
376
-        }
377
-        if ($include_deleted) {
378
-            $query_params[0]['DTT_deleted'] = array('IN', array(true, false));
379
-        }
380
-        if ($limit) {
381
-            $query_params['limit'] = $limit;
382
-        }
383
-        /** @var EE_Datetime[] $result */
384
-        $result = $this->get_all($query_params);
385
-        $this->assume_values_already_prepared_by_model_object($old_assumption);
386
-        return $result;
387
-    }
388
-
389
-
390
-
391
-    /**
392
-     * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
393
-     * reason it doesn't exist, we consider the earliest event the most important)
394
-     *
395
-     * @param int $EVT_ID
396
-     * @return EE_Datetime
397
-     * @throws \EE_Error
398
-     */
399
-    public function get_most_important_datetime_for_event($EVT_ID)
400
-    {
401
-        $results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
402
-        if ($results) {
403
-            return array_shift($results);
404
-        } else {
405
-            return null;
406
-        }
407
-    }
408
-
409
-
410
-
411
-    /**
412
-     * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
413
-     * grouped by month and year.
414
-     *
415
-     * @param  array  $where_params      Array of query_params as described in the comments for EEM_Base::get_all()
416
-     * @param  string $evt_active_status A string representing the evt active status to filter the months by.
417
-     *                                   Can be:
418
-     *                                   - '' = no filter
419
-     *                                   - upcoming = Published events with at least one upcoming datetime.
420
-     *                                   - expired = Events with all datetimes expired.
421
-     *                                   - active = Events that are published and have at least one datetime that
422
-     *                                   starts before now and ends after now.
423
-     *                                   - inactive = Events that are either not published.
424
-     * @return EE_Base_Class[]
425
-     * @throws \EE_Error
426
-     */
427
-    public function get_dtt_months_and_years($where_params, $evt_active_status = '')
428
-    {
429
-        $current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
430
-        $current_time_for_DTT_EVT_end = $this->current_time_for_query('DTT_EVT_end');
431
-        switch ($evt_active_status) {
432
-            case 'upcoming' :
433
-                $where_params['Event.status'] = 'publish';
434
-                //if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
435
-                if (isset($where_params['DTT_EVT_start'])) {
436
-                    $where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
437
-                }
438
-                $where_params['DTT_EVT_start'] = array('>', $current_time_for_DTT_EVT_start);
439
-                break;
440
-            case 'expired' :
441
-                if (isset($where_params['Event.status'])) {
442
-                    unset($where_params['Event.status']);
443
-                }
444
-                //get events to exclude
445
-                $exclude_query[0] = array_merge($where_params,
446
-                    array('DTT_EVT_end' => array('>', $current_time_for_DTT_EVT_end)));
447
-                //first get all events that have datetimes where its not expired.
448
-                $event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Datetime.EVT_ID');
449
-                $event_ids = array_keys($event_ids);
450
-                if (isset($where_params['DTT_EVT_end'])) {
451
-                    $where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
452
-                }
453
-                $where_params['DTT_EVT_end'] = array('<', $current_time_for_DTT_EVT_end);
454
-                $where_params['Event.EVT_ID'] = array('NOT IN', $event_ids);
455
-                break;
456
-            case 'active' :
457
-                $where_params['Event.status'] = 'publish';
458
-                if (isset($where_params['DTT_EVT_start'])) {
459
-                    $where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
460
-                }
461
-                if (isset($where_params['Datetime.DTT_EVT_end'])) {
462
-                    $where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
463
-                }
464
-                $where_params['DTT_EVT_start'] = array('<', $current_time_for_DTT_EVT_start);
465
-                $where_params['DTT_EVT_end'] = array('>', $current_time_for_DTT_EVT_end);
466
-                break;
467
-            case 'inactive' :
468
-                if (isset($where_params['Event.status'])) {
469
-                    unset($where_params['Event.status']);
470
-                }
471
-                if (isset($where_params['OR'])) {
472
-                    $where_params['AND']['OR'] = $where_params['OR'];
473
-                }
474
-                if (isset($where_params['DTT_EVT_end'])) {
475
-                    $where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
476
-                    unset($where_params['DTT_EVT_end']);
477
-                }
478
-                if (isset($where_params['DTT_EVT_start'])) {
479
-                    $where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
480
-                    unset($where_params['DTT_EVT_start']);
481
-                }
482
-                $where_params['AND']['Event.status'] = array('!=', 'publish');
483
-                break;
484
-        }
485
-        $query_params[0] = $where_params;
486
-        $query_params['group_by'] = array('dtt_year', 'dtt_month');
487
-        $query_params['order_by'] = array('DTT_EVT_start' => 'DESC');
488
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'DTT_EVT_start');
489
-        $columns_to_select = array(
490
-            'dtt_year'      => array('YEAR(' . $query_interval . ')', '%s'),
491
-            'dtt_month'     => array('MONTHNAME(' . $query_interval . ')', '%s'),
492
-            'dtt_month_num' => array('MONTH(' . $query_interval . ')', '%s'),
493
-        );
494
-        return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
495
-    }
496
-
497
-
498
-
499
-    /**
500
-     * Updates the DTT_sold attribute on each datetime (based on the registrations
501
-     * for the tickets for each datetime)
502
-     *
503
-     * @param EE_Datetime[] $datetimes
504
-     */
505
-    public function update_sold($datetimes)
506
-    {
507
-        foreach ($datetimes as $datetime) {
508
-            $datetime->update_sold();
509
-        }
510
-    }
511
-
512
-
513
-
514
-    /**
515
-     *    Gets the total number of tickets available at a particular datetime
516
-     *    (does NOT take into account the datetime's spaces available)
517
-     *
518
-     * @param int   $DTT_ID
519
-     * @param array $query_params
520
-     * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
521
-     *             tickets attached to datetime then FALSE is returned.
522
-     */
523
-    public function sum_tickets_currently_available_at_datetime($DTT_ID, array $query_params = array())
524
-    {
525
-        $datetime = $this->get_one_by_ID($DTT_ID);
526
-        if ($datetime instanceof EE_Datetime) {
527
-            return $datetime->tickets_remaining($query_params);
528
-        }
529
-        return 0;
530
-    }
531
-
532
-
533
-
534
-    /**
535
-     * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
536
-     *
537
-     * @param  array $stati_to_include If included you can restrict the statuses we return counts for by including the
538
-     *                                 stati you want counts for as values in the array.  An empty array returns counts
539
-     *                                 for all valid stati.
540
-     * @param  array $query_params     If included can be used to refine the conditions for returning the count (i.e.
541
-     *                                 only for Datetimes connected to a specific event, or specific ticket.
542
-     * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
543
-     * @throws \EE_Error
544
-     *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming EE_Datetime::expired
545
-     */
546
-    public function get_datetime_counts_by_status(array $stati_to_include = array(), array $query_params = array())
547
-    {
548
-        //only accept where conditions for this query.
549
-        $_where = isset($query_params[0]) ? $query_params[0] : array();
550
-        $status_query_args = array(
551
-            EE_Datetime::active   => array_merge(
552
-                $_where,
553
-                array('DTT_EVT_start' => array('<', time()), 'DTT_EVT_end' => array('>', time()))
554
-            ),
555
-            EE_Datetime::upcoming => array_merge(
556
-                $_where,
557
-                array('DTT_EVT_start' => array('>', time()))
558
-            ),
559
-            EE_Datetime::expired  => array_merge(
560
-                $_where,
561
-                array('DTT_EVT_end' => array('<', time()))
562
-            ),
563
-        );
564
-        if ( ! empty($stati_to_include)) {
565
-            foreach (array_keys($status_query_args) as $status) {
566
-                if ( ! in_array($status, $stati_to_include, true)) {
567
-                    unset($status_query_args[$status]);
568
-                }
569
-            }
570
-        }
571
-        //loop through and query counts for each stati.
572
-        $status_query_results = array();
573
-        foreach ($status_query_args as $status => $status_where_conditions) {
574
-            $status_query_results[$status] = EEM_Datetime::count(array($status_where_conditions), 'DTT_ID', true);
575
-        }
576
-        return $status_query_results;
577
-    }
578
-
579
-
580
-
581
-    /**
582
-     * Returns the specific count for a given Datetime status matching any given query_params.
583
-     *
584
-     * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
585
-     * @param array  $query_params
586
-     * @return int
587
-     * @throws \EE_Error
588
-     */
589
-    public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = array())
590
-    {
591
-        $count = $this->get_datetime_counts_by_status(array($status), $query_params);
592
-        return ! empty($count[$status]) ? $count[$status] : 0;
593
-    }
14
+	/**
15
+	 * @var EEM_Datetime $_instance
16
+	 */
17
+	protected static $_instance;
18
+
19
+
20
+
21
+	/**
22
+	 *        private constructor to prevent direct creation
23
+	 *
24
+	 * @Constructor
25
+	 * @access private
26
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
27
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
28
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
29
+	 *                         timezone in the 'timezone_string' wp option)
30
+	 * @throws \EE_Error
31
+	 */
32
+	protected function __construct($timezone)
33
+	{
34
+		$this->singular_item = __('Datetime', 'event_espresso');
35
+		$this->plural_item = __('Datetimes', 'event_espresso');
36
+		$this->_tables = array(
37
+			'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
38
+		);
39
+		$this->_fields = array(
40
+			'Datetime' => array(
41
+				'DTT_ID'          => new EE_Primary_Key_Int_Field('DTT_ID', __('Datetime ID', 'event_espresso')),
42
+				'EVT_ID'          => new EE_Foreign_Key_Int_Field(
43
+					'EVT_ID', __('Event ID', 'event_espresso'), false, 0, 'Event'
44
+				),
45
+				'DTT_name'        => new EE_Plain_Text_Field(
46
+					'DTT_name', __('Datetime Name', 'event_espresso'), false, ''
47
+				),
48
+				'DTT_description' => new EE_Post_Content_Field(
49
+					'DTT_description', __('Description for Datetime', 'event_espresso'), false, ''
50
+				),
51
+				'DTT_EVT_start'   => new EE_Datetime_Field(
52
+					'DTT_EVT_start', __('Start time/date of Event', 'event_espresso'), false, EE_Datetime_Field::now,
53
+					$timezone
54
+				),
55
+				'DTT_EVT_end'     => new EE_Datetime_Field(
56
+					'DTT_EVT_end', __('End time/date of Event', 'event_espresso'), false, EE_Datetime_Field::now,
57
+					$timezone
58
+				),
59
+				'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
60
+					'DTT_reg_limit', __('Registration Limit for this time', 'event_espresso'), true, EE_INF),
61
+				'DTT_sold'        => new EE_Integer_Field(
62
+					'DTT_sold', __('How many sales for this Datetime that have occurred', 'event_espresso'), true, 0
63
+				),
64
+				'DTT_reserved' => new EE_Integer_Field('DTT_reserved',
65
+					__('Quantity of tickets reserved, but not yet fully purchased', 'event_espresso'), false, 0
66
+				),
67
+				'DTT_is_primary'  => new EE_Boolean_Field(
68
+					'DTT_is_primary', __('Flag indicating datetime is primary one for event', 'event_espresso'),
69
+					false, false
70
+				),
71
+				'DTT_order'       => new EE_Integer_Field(
72
+					'DTT_order', __('The order in which the Datetime is displayed', 'event_espresso'), false, 0
73
+				),
74
+				'DTT_parent'      => new EE_Integer_Field(
75
+					'DTT_parent', __('Indicates what DTT_ID is the parent of this DTT_ID'), true, 0
76
+				),
77
+				'DTT_deleted'     => new EE_Trashed_Flag_Field(
78
+					'DTT_deleted', __('Flag indicating datetime is archived', 'event_espresso'), false, false
79
+				),
80
+			),
81
+		);
82
+		$this->_model_relations = array(
83
+			'Ticket'  => new EE_HABTM_Relation('Datetime_Ticket'),
84
+			'Event'   => new EE_Belongs_To_Relation(),
85
+			'Checkin' => new EE_Has_Many_Relation(),
86
+		);
87
+		$this->_model_chain_to_wp_user = 'Event';
88
+		//this model is generally available for reading
89
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Event_Related_Public('Event');
90
+		$this->_cap_restriction_generators[EEM_Base::caps_read_admin] = new EE_Restriction_Generator_Event_Related_Protected('Event');
91
+		$this->_cap_restriction_generators[EEM_Base::caps_edit] = new EE_Restriction_Generator_Event_Related_Protected('Event');
92
+		$this->_cap_restriction_generators[EEM_Base::caps_delete] = new EE_Restriction_Generator_Event_Related_Protected('Event',
93
+			EEM_Base::caps_edit);
94
+		parent::__construct($timezone);
95
+	}
96
+
97
+
98
+
99
+	/**
100
+	 * create new blank datetime
101
+	 *
102
+	 * @access public
103
+	 * @return EE_Datetime[] array on success, FALSE on fail
104
+	 * @throws \EE_Error
105
+	 */
106
+	public function create_new_blank_datetime()
107
+	{
108
+		//makes sure timezone is always set.
109
+		$timezone_string = $this->get_timezone();
110
+		$blank_datetime = EE_Datetime::new_instance(
111
+			array(
112
+				'DTT_EVT_start' => $this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS,
113
+				'DTT_EVT_end'   => $this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS,
114
+				'DTT_order'     => 1,
115
+				'DTT_reg_limit' => EE_INF,
116
+			),
117
+			$timezone_string
118
+		);
119
+		$blank_datetime->set_start_time($this->convert_datetime_for_query('DTT_EVT_start', '8am', 'ga',
120
+			$timezone_string));
121
+		$blank_datetime->set_end_time($this->convert_datetime_for_query('DTT_EVT_end', '5pm', 'ga', $timezone_string));
122
+		return array($blank_datetime);
123
+	}
124
+
125
+
126
+
127
+	/**
128
+	 * get event start date from db
129
+	 *
130
+	 * @access public
131
+	 * @param  int $EVT_ID
132
+	 * @return EE_Datetime[] array on success, FALSE on fail
133
+	 * @throws \EE_Error
134
+	 */
135
+	public function get_all_event_dates($EVT_ID = 0)
136
+	{
137
+		if ( ! $EVT_ID) { // on add_new_event event_id gets set to 0
138
+			return $this->create_new_blank_datetime();
139
+		}
140
+		$results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
141
+		if (empty($results)) {
142
+			return $this->create_new_blank_datetime();
143
+		}
144
+		return $results;
145
+	}
146
+
147
+
148
+
149
+	/**
150
+	 * get all datetimes attached to an event ordered by the DTT_order field
151
+	 *
152
+	 * @public
153
+	 * @param  int    $EVT_ID     event id
154
+	 * @param boolean $include_expired
155
+	 * @param boolean $include_deleted
156
+	 * @param  int    $limit      If included then limit the count of results by
157
+	 *                            the given number
158
+	 * @return EE_Datetime[]
159
+	 * @throws \EE_Error
160
+	 */
161
+	public function get_datetimes_for_event_ordered_by_DTT_order(
162
+		$EVT_ID,
163
+		$include_expired = true,
164
+		$include_deleted = true,
165
+		$limit = null
166
+	) {
167
+		//sanitize EVT_ID
168
+		$EVT_ID = absint($EVT_ID);
169
+		$old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
170
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
171
+		$where_params = array('Event.EVT_ID' => $EVT_ID);
172
+		$query_params = ! empty($limit)
173
+			? array(
174
+				$where_params,
175
+				'limit'                    => $limit,
176
+				'order_by'                 => array('DTT_order' => 'ASC'),
177
+				'default_where_conditions' => 'none',
178
+			)
179
+			: array(
180
+				$where_params,
181
+				'order_by'                 => array('DTT_order' => 'ASC'),
182
+				'default_where_conditions' => 'none',
183
+			);
184
+		if ( ! $include_expired) {
185
+			$query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
186
+		}
187
+		if ($include_deleted) {
188
+			$query_params[0]['DTT_deleted'] = array('IN', array(true, false));
189
+		}
190
+		/** @var EE_Datetime[] $result */
191
+		$result = $this->get_all($query_params);
192
+		$this->assume_values_already_prepared_by_model_object($old_assumption);
193
+		return $result;
194
+	}
195
+
196
+
197
+
198
+	/**
199
+	 * Gets the datetimes for the event (with the given limit), and orders them by "importance". By importance, we mean
200
+	 * that the primary datetimes are most important (DEPRECATED FOR NOW), and then the earlier datetimes are the most
201
+	 * important. Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
202
+	 *
203
+	 * @param int $EVT_ID
204
+	 * @param int $limit
205
+	 * @return EE_Datetime[]|EE_Base_Class[]
206
+	 * @throws \EE_Error
207
+	 */
208
+	public function get_datetimes_for_event_ordered_by_importance($EVT_ID = 0, $limit = null)
209
+	{
210
+		return $this->get_all(
211
+			array(
212
+				array('Event.EVT_ID' => $EVT_ID),
213
+				'limit'                    => $limit,
214
+				'order_by'                 => array('DTT_EVT_start' => 'ASC'),
215
+				'default_where_conditions' => 'none',
216
+			)
217
+		);
218
+	}
219
+
220
+
221
+
222
+	/**
223
+	 * @param int     $EVT_ID
224
+	 * @param boolean $include_expired
225
+	 * @param boolean $include_deleted
226
+	 * @return EE_Datetime
227
+	 * @throws \EE_Error
228
+	 */
229
+	public function get_oldest_datetime_for_event($EVT_ID, $include_expired = false, $include_deleted = false)
230
+	{
231
+		$results = $this->get_datetimes_for_event_ordered_by_start_time($EVT_ID, $include_expired, $include_deleted, 1);
232
+		if ($results) {
233
+			return array_shift($results);
234
+		} else {
235
+			return null;
236
+		}
237
+	}
238
+
239
+
240
+
241
+	/**
242
+	 * Gets the 'primary' datetime for an event.
243
+	 *
244
+	 * @param int  $EVT_ID
245
+	 * @param bool $try_to_exclude_expired
246
+	 * @param bool $try_to_exclude_deleted
247
+	 * @return \EE_Datetime
248
+	 * @throws \EE_Error
249
+	 */
250
+	public function get_primary_datetime_for_event(
251
+		$EVT_ID,
252
+		$try_to_exclude_expired = true,
253
+		$try_to_exclude_deleted = true
254
+	) {
255
+		if ($try_to_exclude_expired) {
256
+			$non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
257
+			if ($non_expired) {
258
+				return $non_expired;
259
+			}
260
+		}
261
+		if ($try_to_exclude_deleted) {
262
+			$expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
263
+			if ($expired_even) {
264
+				return $expired_even;
265
+			}
266
+		}
267
+		return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
268
+	}
269
+
270
+
271
+
272
+	/**
273
+	 * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
274
+	 * only by start date
275
+	 *
276
+	 * @param int     $EVT_ID
277
+	 * @param boolean $include_expired
278
+	 * @param boolean $include_deleted
279
+	 * @param int     $limit
280
+	 * @return EE_Datetime[]
281
+	 * @throws \EE_Error
282
+	 */
283
+	public function get_datetimes_for_event_ordered_by_start_time(
284
+		$EVT_ID,
285
+		$include_expired = true,
286
+		$include_deleted = true,
287
+		$limit = null
288
+	) {
289
+		//sanitize EVT_ID
290
+		$EVT_ID = absint($EVT_ID);
291
+		$old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
292
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
293
+		$query_params = array(array('Event.EVT_ID' => $EVT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
294
+		if ( ! $include_expired) {
295
+			$query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
296
+		}
297
+		if ($include_deleted) {
298
+			$query_params[0]['DTT_deleted'] = array('IN', array(true, false));
299
+		}
300
+		if ($limit) {
301
+			$query_params['limit'] = $limit;
302
+		}
303
+		/** @var EE_Datetime[] $result */
304
+		$result = $this->get_all($query_params);
305
+		$this->assume_values_already_prepared_by_model_object($old_assumption);
306
+		return $result;
307
+	}
308
+
309
+
310
+
311
+	/**
312
+	 * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
313
+	 * only by start date
314
+	 *
315
+	 * @param int     $TKT_ID
316
+	 * @param boolean $include_expired
317
+	 * @param boolean $include_deleted
318
+	 * @param int     $limit
319
+	 * @return EE_Datetime[]
320
+	 * @throws \EE_Error
321
+	 */
322
+	public function get_datetimes_for_ticket_ordered_by_start_time(
323
+		$TKT_ID,
324
+		$include_expired = true,
325
+		$include_deleted = true,
326
+		$limit = null
327
+	) {
328
+		//sanitize TKT_ID
329
+		$TKT_ID = absint($TKT_ID);
330
+		$old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
331
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
332
+		$query_params = array(array('Ticket.TKT_ID' => $TKT_ID), 'order_by' => array('DTT_EVT_start' => 'asc'));
333
+		if ( ! $include_expired) {
334
+			$query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
335
+		}
336
+		if ($include_deleted) {
337
+			$query_params[0]['DTT_deleted'] = array('IN', array(true, false));
338
+		}
339
+		if ($limit) {
340
+			$query_params['limit'] = $limit;
341
+		}
342
+		/** @var EE_Datetime[] $result */
343
+		$result = $this->get_all($query_params);
344
+		$this->assume_values_already_prepared_by_model_object($old_assumption);
345
+		return $result;
346
+	}
347
+
348
+
349
+
350
+	/**
351
+	 * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
352
+	 * datetimes.
353
+	 *
354
+	 * @param  int      $TKT_ID          ID of ticket to retrieve the datetimes for
355
+	 * @param  boolean  $include_expired whether to include expired datetimes or not
356
+	 * @param  boolean  $include_deleted whether to include trashed datetimes or not.
357
+	 * @param  int|null $limit           if null, no limit, if int then limit results by
358
+	 *                                   that number
359
+	 * @return EE_Datetime[]
360
+	 * @throws \EE_Error
361
+	 */
362
+	public function get_datetimes_for_ticket_ordered_by_DTT_order(
363
+		$TKT_ID,
364
+		$include_expired = true,
365
+		$include_deleted = true,
366
+		$limit = null
367
+	) {
368
+		//sanitize id.
369
+		$TKT_ID = absint($TKT_ID);
370
+		$old_assumption = $this->get_assumption_concerning_values_already_prepared_by_model_object();
371
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
372
+		$where_params = array('Ticket.TKT_ID' => $TKT_ID);
373
+		$query_params = array($where_params, 'order_by' => array('DTT_order' => 'ASC'));
374
+		if ( ! $include_expired) {
375
+			$query_params[0]['DTT_EVT_end'] = array('>=', current_time('mysql', true));
376
+		}
377
+		if ($include_deleted) {
378
+			$query_params[0]['DTT_deleted'] = array('IN', array(true, false));
379
+		}
380
+		if ($limit) {
381
+			$query_params['limit'] = $limit;
382
+		}
383
+		/** @var EE_Datetime[] $result */
384
+		$result = $this->get_all($query_params);
385
+		$this->assume_values_already_prepared_by_model_object($old_assumption);
386
+		return $result;
387
+	}
388
+
389
+
390
+
391
+	/**
392
+	 * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
393
+	 * reason it doesn't exist, we consider the earliest event the most important)
394
+	 *
395
+	 * @param int $EVT_ID
396
+	 * @return EE_Datetime
397
+	 * @throws \EE_Error
398
+	 */
399
+	public function get_most_important_datetime_for_event($EVT_ID)
400
+	{
401
+		$results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
402
+		if ($results) {
403
+			return array_shift($results);
404
+		} else {
405
+			return null;
406
+		}
407
+	}
408
+
409
+
410
+
411
+	/**
412
+	 * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
413
+	 * grouped by month and year.
414
+	 *
415
+	 * @param  array  $where_params      Array of query_params as described in the comments for EEM_Base::get_all()
416
+	 * @param  string $evt_active_status A string representing the evt active status to filter the months by.
417
+	 *                                   Can be:
418
+	 *                                   - '' = no filter
419
+	 *                                   - upcoming = Published events with at least one upcoming datetime.
420
+	 *                                   - expired = Events with all datetimes expired.
421
+	 *                                   - active = Events that are published and have at least one datetime that
422
+	 *                                   starts before now and ends after now.
423
+	 *                                   - inactive = Events that are either not published.
424
+	 * @return EE_Base_Class[]
425
+	 * @throws \EE_Error
426
+	 */
427
+	public function get_dtt_months_and_years($where_params, $evt_active_status = '')
428
+	{
429
+		$current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
430
+		$current_time_for_DTT_EVT_end = $this->current_time_for_query('DTT_EVT_end');
431
+		switch ($evt_active_status) {
432
+			case 'upcoming' :
433
+				$where_params['Event.status'] = 'publish';
434
+				//if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
435
+				if (isset($where_params['DTT_EVT_start'])) {
436
+					$where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
437
+				}
438
+				$where_params['DTT_EVT_start'] = array('>', $current_time_for_DTT_EVT_start);
439
+				break;
440
+			case 'expired' :
441
+				if (isset($where_params['Event.status'])) {
442
+					unset($where_params['Event.status']);
443
+				}
444
+				//get events to exclude
445
+				$exclude_query[0] = array_merge($where_params,
446
+					array('DTT_EVT_end' => array('>', $current_time_for_DTT_EVT_end)));
447
+				//first get all events that have datetimes where its not expired.
448
+				$event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Datetime.EVT_ID');
449
+				$event_ids = array_keys($event_ids);
450
+				if (isset($where_params['DTT_EVT_end'])) {
451
+					$where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
452
+				}
453
+				$where_params['DTT_EVT_end'] = array('<', $current_time_for_DTT_EVT_end);
454
+				$where_params['Event.EVT_ID'] = array('NOT IN', $event_ids);
455
+				break;
456
+			case 'active' :
457
+				$where_params['Event.status'] = 'publish';
458
+				if (isset($where_params['DTT_EVT_start'])) {
459
+					$where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
460
+				}
461
+				if (isset($where_params['Datetime.DTT_EVT_end'])) {
462
+					$where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
463
+				}
464
+				$where_params['DTT_EVT_start'] = array('<', $current_time_for_DTT_EVT_start);
465
+				$where_params['DTT_EVT_end'] = array('>', $current_time_for_DTT_EVT_end);
466
+				break;
467
+			case 'inactive' :
468
+				if (isset($where_params['Event.status'])) {
469
+					unset($where_params['Event.status']);
470
+				}
471
+				if (isset($where_params['OR'])) {
472
+					$where_params['AND']['OR'] = $where_params['OR'];
473
+				}
474
+				if (isset($where_params['DTT_EVT_end'])) {
475
+					$where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
476
+					unset($where_params['DTT_EVT_end']);
477
+				}
478
+				if (isset($where_params['DTT_EVT_start'])) {
479
+					$where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
480
+					unset($where_params['DTT_EVT_start']);
481
+				}
482
+				$where_params['AND']['Event.status'] = array('!=', 'publish');
483
+				break;
484
+		}
485
+		$query_params[0] = $where_params;
486
+		$query_params['group_by'] = array('dtt_year', 'dtt_month');
487
+		$query_params['order_by'] = array('DTT_EVT_start' => 'DESC');
488
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'DTT_EVT_start');
489
+		$columns_to_select = array(
490
+			'dtt_year'      => array('YEAR(' . $query_interval . ')', '%s'),
491
+			'dtt_month'     => array('MONTHNAME(' . $query_interval . ')', '%s'),
492
+			'dtt_month_num' => array('MONTH(' . $query_interval . ')', '%s'),
493
+		);
494
+		return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
495
+	}
496
+
497
+
498
+
499
+	/**
500
+	 * Updates the DTT_sold attribute on each datetime (based on the registrations
501
+	 * for the tickets for each datetime)
502
+	 *
503
+	 * @param EE_Datetime[] $datetimes
504
+	 */
505
+	public function update_sold($datetimes)
506
+	{
507
+		foreach ($datetimes as $datetime) {
508
+			$datetime->update_sold();
509
+		}
510
+	}
511
+
512
+
513
+
514
+	/**
515
+	 *    Gets the total number of tickets available at a particular datetime
516
+	 *    (does NOT take into account the datetime's spaces available)
517
+	 *
518
+	 * @param int   $DTT_ID
519
+	 * @param array $query_params
520
+	 * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
521
+	 *             tickets attached to datetime then FALSE is returned.
522
+	 */
523
+	public function sum_tickets_currently_available_at_datetime($DTT_ID, array $query_params = array())
524
+	{
525
+		$datetime = $this->get_one_by_ID($DTT_ID);
526
+		if ($datetime instanceof EE_Datetime) {
527
+			return $datetime->tickets_remaining($query_params);
528
+		}
529
+		return 0;
530
+	}
531
+
532
+
533
+
534
+	/**
535
+	 * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
536
+	 *
537
+	 * @param  array $stati_to_include If included you can restrict the statuses we return counts for by including the
538
+	 *                                 stati you want counts for as values in the array.  An empty array returns counts
539
+	 *                                 for all valid stati.
540
+	 * @param  array $query_params     If included can be used to refine the conditions for returning the count (i.e.
541
+	 *                                 only for Datetimes connected to a specific event, or specific ticket.
542
+	 * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
543
+	 * @throws \EE_Error
544
+	 *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming EE_Datetime::expired
545
+	 */
546
+	public function get_datetime_counts_by_status(array $stati_to_include = array(), array $query_params = array())
547
+	{
548
+		//only accept where conditions for this query.
549
+		$_where = isset($query_params[0]) ? $query_params[0] : array();
550
+		$status_query_args = array(
551
+			EE_Datetime::active   => array_merge(
552
+				$_where,
553
+				array('DTT_EVT_start' => array('<', time()), 'DTT_EVT_end' => array('>', time()))
554
+			),
555
+			EE_Datetime::upcoming => array_merge(
556
+				$_where,
557
+				array('DTT_EVT_start' => array('>', time()))
558
+			),
559
+			EE_Datetime::expired  => array_merge(
560
+				$_where,
561
+				array('DTT_EVT_end' => array('<', time()))
562
+			),
563
+		);
564
+		if ( ! empty($stati_to_include)) {
565
+			foreach (array_keys($status_query_args) as $status) {
566
+				if ( ! in_array($status, $stati_to_include, true)) {
567
+					unset($status_query_args[$status]);
568
+				}
569
+			}
570
+		}
571
+		//loop through and query counts for each stati.
572
+		$status_query_results = array();
573
+		foreach ($status_query_args as $status => $status_where_conditions) {
574
+			$status_query_results[$status] = EEM_Datetime::count(array($status_where_conditions), 'DTT_ID', true);
575
+		}
576
+		return $status_query_results;
577
+	}
578
+
579
+
580
+
581
+	/**
582
+	 * Returns the specific count for a given Datetime status matching any given query_params.
583
+	 *
584
+	 * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
585
+	 * @param array  $query_params
586
+	 * @return int
587
+	 * @throws \EE_Error
588
+	 */
589
+	public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = array())
590
+	{
591
+		$count = $this->get_datetime_counts_by_status(array($status), $query_params);
592
+		return ! empty($count[$status]) ? $count[$status] : 0;
593
+	}
594 594
 
595 595
 
596 596
 
Please login to merge, or discard this patch.
admin_pages/messages/Messages_Admin_Page.core.php 2 patches
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
         $this->_admin_base_url  = EE_MSG_ADMIN_URL;
88 88
         $this->_admin_base_path = EE_MSG_ADMIN;
89 89
         
90
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
90
+        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state'] : array();
91 91
         
92 92
         $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93 93
         $this->_load_message_resource_manager();
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
             array('none_selected' => __('Show All Messengers', 'event_espresso')),
220 220
             $messenger_options
221 221
         );
222
-        $input             = new EE_Select_Input(
222
+        $input = new EE_Select_Input(
223 223
             $messenger_options,
224 224
             array(
225 225
                 'html_name'  => 'ee_messenger_filter_by',
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
             array('none_selected' => __('Show All Message Types', 'event_espresso')),
258 258
             $message_type_options
259 259
         );
260
-        $input                = new EE_Select_Input(
260
+        $input = new EE_Select_Input(
261 261
             $message_type_options,
262 262
             array(
263 263
                 'html_name'  => 'ee_message_type_filter_by',
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
             array('none_selected' => __('Show all Contexts', 'event_espresso')),
296 296
             $context_options
297 297
         );
298
-        $input           = new EE_Select_Input(
298
+        $input = new EE_Select_Input(
299 299
             $context_options,
300 300
             array(
301 301
                 'html_name'  => 'ee_context_filter_by',
@@ -676,47 +676,47 @@  discard block
 block discarded – undo
676 676
     
677 677
     public function messages_help_tab()
678 678
     {
679
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
679
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_help_tab.template.php');
680 680
     }
681 681
     
682 682
     
683 683
     public function messengers_help_tab()
684 684
     {
685
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
685
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messenger_help_tab.template.php');
686 686
     }
687 687
     
688 688
     
689 689
     public function message_types_help_tab()
690 690
     {
691
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
691
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_type_help_tab.template.php');
692 692
     }
693 693
     
694 694
     
695 695
     public function messages_overview_help_tab()
696 696
     {
697
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
697
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_overview_help_tab.template.php');
698 698
     }
699 699
     
700 700
     
701 701
     public function message_templates_help_tab()
702 702
     {
703
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
703
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_templates_help_tab.template.php');
704 704
     }
705 705
     
706 706
     
707 707
     public function edit_message_template_help_tab()
708 708
     {
709
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
-                'event_espresso') . '" />';
711
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
-                'event_espresso') . '" />';
713
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
-                'event_espresso') . '" />';
715
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
-                'event_espresso') . '" />';
717
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
-                'event_espresso') . '" />';
719
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
709
+        $args['img1'] = '<img src="'.EE_MSG_ASSETS_URL.'images/editor.png'.'" alt="'.esc_attr__('Editor Title',
710
+                'event_espresso').'" />';
711
+        $args['img2'] = '<img src="'.EE_MSG_ASSETS_URL.'images/switch-context.png'.'" alt="'.esc_attr__('Context Switcher and Preview',
712
+                'event_espresso').'" />';
713
+        $args['img3'] = '<img class="left" src="'.EE_MSG_ASSETS_URL.'images/form-fields.png'.'" alt="'.esc_attr__('Message Template Form Fields',
714
+                'event_espresso').'" />';
715
+        $args['img4'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/shortcodes-metabox.png'.'" alt="'.esc_attr__('Shortcodes Metabox',
716
+                'event_espresso').'" />';
717
+        $args['img5'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/publish-meta-box.png'.'" alt="'.esc_attr__('Publish Metabox',
718
+                'event_espresso').'" />';
719
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_templates_editor_help_tab.template.php',
720 720
             $args);
721 721
     }
722 722
     
@@ -725,37 +725,37 @@  discard block
 block discarded – undo
725 725
     {
726 726
         $this->_set_shortcodes();
727 727
         $args['shortcodes'] = $this->_shortcodes;
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
728
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_shortcodes_help_tab.template.php',
729 729
             $args);
730 730
     }
731 731
     
732 732
     
733 733
     public function preview_message_help_tab()
734 734
     {
735
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
735
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_preview_help_tab.template.php');
736 736
     }
737 737
     
738 738
     
739 739
     public function settings_help_tab()
740 740
     {
741
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
-                'event_espresso') . '" />';
743
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
-                'event_espresso') . '" />';
741
+        $args['img1'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-active.png'.'" alt="'.esc_attr__('Active Email Tab',
742
+                'event_espresso').'" />';
743
+        $args['img2'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-inactive.png'.'" alt="'.esc_attr__('Inactive Email Tab',
744
+                'event_espresso').'" />';
745 745
         $args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746 746
         $args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
747
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_settings_help_tab.template.php', $args);
748 748
     }
749 749
     
750 750
     
751 751
     public function load_scripts_styles()
752 752
     {
753
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
753
+        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL.'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754 754
         wp_enqueue_style('espresso_ee_msg');
755 755
         
756
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
756
+        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL.'ee-messages-settings.js',
757 757
             array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
758
+        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL.'ee_message_admin_list_table.js',
759 759
             array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760 760
     }
761 761
     
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
         
788 788
         $this->_set_shortcodes();
789 789
         
790
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
790
+        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
791 791
             __('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
792 792
                 'event_espresso'),
793 793
             $this->_message_template_group->messenger_obj()->label['singular'],
@@ -796,7 +796,7 @@  discard block
 block discarded – undo
796 796
         EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
797 797
             'event_espresso');
798 798
         
799
-        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
799
+        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL.'ee_message_editor.js', array('jquery'),
800 800
             EVENT_ESPRESSO_VERSION);
801 801
         
802 802
         wp_enqueue_script('ee_admin_js');
@@ -827,7 +827,7 @@  discard block
 block discarded – undo
827 827
     
828 828
     public function load_scripts_styles_settings()
829 829
     {
830
-        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
830
+        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL.'ee_message_settings.css', array(),
831 831
             EVENT_ESPRESSO_VERSION);
832 832
         wp_enqueue_style('ee-text-links');
833 833
         wp_enqueue_style('ee-message-settings');
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
             }
894 894
             $status_bulk_actions = $common_bulk_actions;
895 895
             //unset bulk actions not applying to status
896
-            if (! empty($status_bulk_actions)) {
896
+            if ( ! empty($status_bulk_actions)) {
897 897
                 switch ($status) {
898 898
                     case EEM_Message::status_idle:
899 899
                     case EEM_Message::status_resend:
@@ -918,7 +918,7 @@  discard block
 block discarded – undo
918 918
             }
919 919
 
920 920
             //skip adding messenger executing status to views because it will be included with the Failed view.
921
-            if ( $status === EEM_Message::status_messenger_executing ) {
921
+            if ($status === EEM_Message::status_messenger_executing) {
922 922
                 continue;
923 923
             }
924 924
             
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
         $this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945 945
         $this->_template_args['per_column']        = 6;
946 946
         $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
-        $this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
947
+        $this->_template_args['before_list_table'] = '<h3>'.EEM_Message::instance()->get_pretty_label_for_results().'</h3>';
948 948
         $this->display_admin_list_table_page_with_no_sidebar();
949 949
     }
950 950
     
@@ -968,37 +968,37 @@  discard block
 block discarded – undo
968 968
         /** @type array $status_items status legend setup */
969 969
         $status_items = array(
970 970
             'sent_status'       => array(
971
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
971
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_sent,
972 972
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973 973
             ),
974 974
             'idle_status'       => array(
975
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
975
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_idle,
976 976
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977 977
             ),
978 978
             'failed_status'     => array(
979
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
979
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_failed,
980 980
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981 981
             ),
982 982
             'messenger_executing_status' => array(
983
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
983
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_messenger_executing,
984 984
                 'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985 985
             ),
986 986
             'resend_status'     => array(
987
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
987
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_resend,
988 988
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989 989
             ),
990 990
             'incomplete_status' => array(
991
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
991
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_incomplete,
992 992
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993 993
             ),
994 994
             'retry_status'      => array(
995
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
995
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_retry,
996 996
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997 997
             )
998 998
         );
999 999
         if (EEM_Message::debug()) {
1000 1000
             $status_items['debug_only_status'] = array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1001
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_debug_only,
1002 1002
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003 1003
             );
1004 1004
         }
@@ -1010,10 +1010,10 @@  discard block
 block discarded – undo
1010 1010
     protected function _custom_mtps_preview()
1011 1011
     {
1012 1012
         $this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
-                'event_espresso') . '" />';
1015
-        $this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1016
-                'event_espresso') . '</strong>';
1013
+        $this->_template_args['preview_img']  = '<img src="'.EE_MSG_ASSETS_URL.'images/custom_mtps_preview.png" alt="'.esc_attr__('Preview Custom Message Templates screenshot',
1014
+                'event_espresso').'" />';
1015
+        $this->_template_args['preview_text'] = '<strong>'.__('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1016
+                'event_espresso').'</strong>';
1017 1017
         $this->display_admin_caf_preview_page('custom_message_types', false);
1018 1018
     }
1019 1019
     
@@ -1261,7 +1261,7 @@  discard block
 block discarded – undo
1261 1261
                             //let's verify if we need this extra field via the shortcodes parameter.
1262 1262
                             $continue = false;
1263 1263
                             if (isset($extra_array['shortcodes_required'])) {
1264
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1264
+                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1265 1265
                                     if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266 1266
                                         $continue = true;
1267 1267
                                     }
@@ -1271,9 +1271,9 @@  discard block
 block discarded – undo
1271 1271
                                 }
1272 1272
                             }
1273 1273
                             
1274
-                            $field_id                                = $reference_field . '-' . $extra_field . '-content';
1274
+                            $field_id                                = $reference_field.'-'.$extra_field.'-content';
1275 1275
                             $template_form_fields[$field_id]         = $extra_array;
1276
-                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1276
+                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields['.$reference_field.'][content]['.$extra_field.']';
1277 1277
                             $css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1278 1278
                             
1279 1279
                             $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
@@ -1283,7 +1283,7 @@  discard block
 block discarded – undo
1283 1283
                                                                                 is_array($validators[$extra_field])
1284 1284
                                                                                 && isset($validators[$extra_field]['msg'])
1285 1285
                                                                             )
1286
-                                ? 'validate-error ' . $css_class
1286
+                                ? 'validate-error '.$css_class
1287 1287
                                 : $css_class;
1288 1288
                             
1289 1289
                             $template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
@@ -1311,11 +1311,11 @@  discard block
 block discarded – undo
1311 1311
                                 
1312 1312
                             }/**/
1313 1313
                         }
1314
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
-                        $templatefield_templatename_id = $reference_field . '-name';
1314
+                        $templatefield_MTP_id          = $reference_field.'-MTP_ID';
1315
+                        $templatefield_templatename_id = $reference_field.'-name';
1316 1316
                         
1317 1317
                         $template_form_fields[$templatefield_MTP_id] = array(
1318
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1318
+                            'name'       => 'MTP_template_fields['.$reference_field.'][MTP_ID]',
1319 1319
                             'label'      => null,
1320 1320
                             'input'      => 'hidden',
1321 1321
                             'type'       => 'int',
@@ -1328,7 +1328,7 @@  discard block
 block discarded – undo
1328 1328
                         );
1329 1329
                         
1330 1330
                         $template_form_fields[$templatefield_templatename_id] = array(
1331
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1331
+                            'name'       => 'MTP_template_fields['.$reference_field.'][name]',
1332 1332
                             'label'      => null,
1333 1333
                             'input'      => 'hidden',
1334 1334
                             'type'       => 'string',
@@ -1342,9 +1342,9 @@  discard block
 block discarded – undo
1342 1342
                     }
1343 1343
                     continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344 1344
                 } else {
1345
-                    $field_id                                 = $template_field . '-content';
1345
+                    $field_id                                 = $template_field.'-content';
1346 1346
                     $template_form_fields[$field_id]          = $field_setup_array;
1347
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1347
+                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields['.$template_field.'][content]';
1348 1348
                     $message_template                         = isset($message_templates[$context][$template_field])
1349 1349
                         ? $message_templates[$context][$template_field]
1350 1350
                         : null;
@@ -1365,7 +1365,7 @@  discard block
 block discarded – undo
1365 1365
                     $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366 1366
                                                                     && in_array($template_field, $v_fields)
1367 1367
                                                                     && isset($validators[$template_field]['msg'])
1368
-                        ? 'validate-error ' . $css_class
1368
+                        ? 'validate-error '.$css_class
1369 1369
                         : $css_class;
1370 1370
                     
1371 1371
                     //shortcode selector
@@ -1376,12 +1376,12 @@  discard block
 block discarded – undo
1376 1376
                 
1377 1377
                 //k took care of content field(s) now let's take care of others.
1378 1378
                 
1379
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
-                $templatefield_field_templatename_id = $template_field . '-name';
1379
+                $templatefield_MTP_id                = $template_field.'-MTP_ID';
1380
+                $templatefield_field_templatename_id = $template_field.'-name';
1381 1381
                 
1382 1382
                 //foreach template field there are actually two form fields created
1383 1383
                 $template_form_fields[$templatefield_MTP_id] = array(
1384
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1384
+                    'name'       => 'MTP_template_fields['.$template_field.'][MTP_ID]',
1385 1385
                     'label'      => null,
1386 1386
                     'input'      => 'hidden',
1387 1387
                     'type'       => 'int',
@@ -1394,7 +1394,7 @@  discard block
 block discarded – undo
1394 1394
                 );
1395 1395
                 
1396 1396
                 $template_form_fields[$templatefield_field_templatename_id] = array(
1397
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1397
+                    'name'       => 'MTP_template_fields['.$template_field.'][name]',
1398 1398
                     'label'      => null,
1399 1399
                     'input'      => 'hidden',
1400 1400
                     'type'       => 'string',
@@ -1512,7 +1512,7 @@  discard block
 block discarded – undo
1512 1512
                 'format'     => '%d',
1513 1513
                 'db-col'     => 'MTP_deleted'
1514 1514
             );
1515
-            $sidebar_form_fields['ee-msg-author']  = array(
1515
+            $sidebar_form_fields['ee-msg-author'] = array(
1516 1516
                 'name'       => 'MTP_user_id',
1517 1517
                 'label'      => __('Author', 'event_espresso'),
1518 1518
                 'input'      => 'hidden',
@@ -1531,17 +1531,17 @@  discard block
 block discarded – undo
1531 1531
                 'value' => $action
1532 1532
             );
1533 1533
             
1534
-            $sidebar_form_fields['ee-msg-id']        = array(
1534
+            $sidebar_form_fields['ee-msg-id'] = array(
1535 1535
                 'name'  => 'id',
1536 1536
                 'input' => 'hidden',
1537 1537
                 'type'  => 'int',
1538 1538
                 'value' => $GRP_ID
1539 1539
             );
1540 1540
             $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
-                'name'  => $action . '_nonce',
1541
+                'name'  => $action.'_nonce',
1542 1542
                 'input' => 'hidden',
1543 1543
                 'type'  => 'string',
1544
-                'value' => wp_create_nonce($action . '_nonce')
1544
+                'value' => wp_create_nonce($action.'_nonce')
1545 1545
             );
1546 1546
             
1547 1547
             if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
@@ -1573,7 +1573,7 @@  discard block
 block discarded – undo
1573 1573
         );
1574 1574
         
1575 1575
         //add preview button
1576
-        $preview_url    = parent::add_query_args_and_nonce(
1576
+        $preview_url = parent::add_query_args_and_nonce(
1577 1577
             array(
1578 1578
                 'message_type' => $message_template_group->message_type(),
1579 1579
                 'messenger'    => $message_template_group->messenger(),
@@ -1583,8 +1583,8 @@  discard block
 block discarded – undo
1583 1583
             ),
1584 1584
             $this->_admin_base_url
1585 1585
         );
1586
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
-                'event_espresso') . '</a>';
1586
+        $preview_button = '<a href="'.$preview_url.'" class="button-secondary messages-preview-button">'.__('Preview',
1587
+                'event_espresso').'</a>';
1588 1588
         
1589 1589
         
1590 1590
         //setup context switcher
@@ -1612,8 +1612,8 @@  discard block
 block discarded – undo
1612 1612
         $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613 1613
         
1614 1614
         $this->_template_path = $this->_template_args['GRP_ID']
1615
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1615
+            ? EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_edit_meta_box.template.php'
1616
+            : EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_add_meta_box.template.php';
1617 1617
         
1618 1618
         //send along EE_Message_Template_Group object for further template use.
1619 1619
         $this->_template_args['MTP'] = $message_template_group;
@@ -1648,7 +1648,7 @@  discard block
 block discarded – undo
1648 1648
     
1649 1649
     public function _add_form_element_before()
1650 1650
     {
1651
-        return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1651
+        return '<form method="post" action="'.$this->_template_args["edit_message_template_form_url"].'" id="ee-msg-edit-frm">';
1652 1652
     }
1653 1653
     
1654 1654
     public function _add_form_element_after()
@@ -1843,14 +1843,14 @@  discard block
 block discarded – undo
1843 1843
         }
1844 1844
         
1845 1845
         //let's add a button to go back to the edit view
1846
-        $query_args             = array(
1846
+        $query_args = array(
1847 1847
             'id'      => $this->_req_data['GRP_ID'],
1848 1848
             'context' => $this->_req_data['context'],
1849 1849
             'action'  => 'edit_message_template'
1850 1850
         );
1851 1851
         $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
-        $preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
-                'event_espresso') . '</a>';
1852
+        $preview_button         = '<a href="'.$go_back_url.'" class="button-secondary messages-preview-go-back-button">'.__('Go Back to Edit',
1853
+                'event_espresso').'</a>';
1854 1854
         $message_types          = $this->get_installed_message_types();
1855 1855
         $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856 1856
         $active_messenger_label = $active_messenger instanceof EE_messenger
@@ -1864,7 +1864,7 @@  discard block
 block discarded – undo
1864 1864
         );
1865 1865
         //setup display of preview.
1866 1866
         $this->_admin_page_title                    = $preview_title;
1867
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1867
+        $this->_template_args['admin_page_content'] = $preview_button.'<br />'.stripslashes($preview);
1868 1868
         $this->_template_args['data']['force_json'] = true;
1869 1869
         
1870 1870
         return '';
@@ -1946,7 +1946,7 @@  discard block
 block discarded – undo
1946 1946
         }
1947 1947
         
1948 1948
         //setup variation select values for the currently selected template.
1949
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
1949
+        $variations = $this->_message_template_group->get_template_pack()->get_variations(
1950 1950
             $this->_message_template_group->messenger(),
1951 1951
             $this->_message_template_group->message_type()
1952 1952
         );
@@ -1960,12 +1960,12 @@  discard block
 block discarded – undo
1960 1960
         
1961 1961
         $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962 1962
         
1963
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1963
+        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
1964 1964
             'MTP_template_pack',
1965 1965
             $tp_select_values,
1966 1966
             $this->_message_template_group->get_template_pack_name()
1967 1967
         );
1968
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
1968
+        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
1969 1969
             'MTP_template_variation',
1970 1970
             $variations_select_values,
1971 1971
             $this->_message_template_group->get_template_pack_variation()
@@ -1975,7 +1975,7 @@  discard block
 block discarded – undo
1975 1975
         $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976 1976
         $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977 1977
         
1978
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1978
+        $template = EE_MSG_TEMPLATE_PATH.'template_pack_and_variations_metabox.template.php';
1979 1979
         
1980 1980
         EEH_Template::display_template($template, $template_args);
1981 1981
     }
@@ -2004,7 +2004,7 @@  discard block
 block discarded – undo
2004 2004
         if ( ! empty($fields)) {
2005 2005
             //yup there be fields
2006 2006
             foreach ($fields as $field => $config) {
2007
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2007
+                $field_id = $this->_message_template_group->messenger().'_'.$field;
2008 2008
                 $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009 2009
                 $default  = isset($config['default']) ? $config['default'] : '';
2010 2010
                 $default  = isset($config['value']) ? $config['value'] : $default;
@@ -2019,7 +2019,7 @@  discard block
 block discarded – undo
2019 2019
                     : $fix;
2020 2020
                 
2021 2021
                 $template_form_fields[$field_id] = array(
2022
-                    'name'       => 'test_settings_fld[' . $field . ']',
2022
+                    'name'       => 'test_settings_fld['.$field.']',
2023 2023
                     'label'      => $config['label'],
2024 2024
                     'input'      => $config['input'],
2025 2025
                     'type'       => $config['type'],
@@ -2049,7 +2049,7 @@  discard block
 block discarded – undo
2049 2049
         }
2050 2050
         
2051 2051
         //and button
2052
-        $test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2052
+        $test_settings_html .= '<p>'.__('Need to reset this message type and start over?', 'event_espresso').'</p>';
2053 2053
         $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054 2054
         $test_settings_html .= $this->get_action_link_or_button(
2055 2055
             'reset_to_default',
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
             'linked_input_id' => $linked_input_id
2081 2081
         );
2082 2082
         
2083
-        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2083
+        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'shortcode_selector_skeleton.template.php',
2084 2084
             $template_args, true);
2085 2085
     }
2086 2086
     
@@ -2098,7 +2098,7 @@  discard block
 block discarded – undo
2098 2098
         //$messenger = $this->_message_template_group->messenger_obj();
2099 2099
         //now let's set the content depending on the status of the shortcodes array
2100 2100
         if (empty($shortcodes)) {
2101
-            $content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2101
+            $content = '<p>'.__('There are no valid shortcodes available', 'event_espresso').'</p>';
2102 2102
             echo $content;
2103 2103
         } else {
2104 2104
             //$alt = 0;
@@ -2215,7 +2215,7 @@  discard block
 block discarded – undo
2215 2215
                     <?php
2216 2216
                 }
2217 2217
                 //setup nonce_url
2218
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2218
+                wp_nonce_field($args['action'].'_nonce', $args['action'].'_nonce', false);
2219 2219
                 ?>
2220 2220
                 <select name="context">
2221 2221
                     <?php
@@ -2313,7 +2313,7 @@  discard block
 block discarded – undo
2313 2313
             : '';
2314 2314
         $context      = ucwords(str_replace('_', ' ', $context_slug));
2315 2315
         
2316
-        $item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2316
+        $item_desc = $messenger_label && $message_type_label ? $messenger_label.' '.$message_type_label.' '.$context.' ' : '';
2317 2317
         $item_desc .= 'Message Template';
2318 2318
         $query_args  = array();
2319 2319
         $edit_array  = array();
@@ -2682,8 +2682,8 @@  discard block
 block discarded – undo
2682 2682
      */
2683 2683
     protected function _learn_more_about_message_templates_link()
2684 2684
     {
2685
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2686
-            'event_espresso') . '</a>';
2685
+        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'.__('learn more about how message templates works',
2686
+            'event_espresso').'</a>';
2687 2687
     }
2688 2688
     
2689 2689
     
@@ -2759,10 +2759,10 @@  discard block
 block discarded – undo
2759 2759
                 
2760 2760
                 $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2761 2761
                     'label'    => ucwords($message_type->label['singular']),
2762
-                    'class'    => 'message-type-' . $a_or_i,
2763
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2764
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2765
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2762
+                    'class'    => 'message-type-'.$a_or_i,
2763
+                    'slug_id'  => $message_type->name.'-messagetype-'.$messenger->name,
2764
+                    'mt_nonce' => wp_create_nonce($message_type->name.'_nonce'),
2765
+                    'href'     => 'espresso_'.$message_type->name.'_message_type_settings',
2766 2766
                     'title'    => $a_or_i == 'active'
2767 2767
                         ? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2768 2768
                         : __('Drag this message type to the messenger to activate', 'event_espresso'),
@@ -2798,9 +2798,9 @@  discard block
 block discarded – undo
2798 2798
             $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2799 2799
             
2800 2800
             foreach ($fields as $fldname => $fldprops) {
2801
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2801
+                $field_id                       = $messenger->name.'-'.$message_type->name.'-'.$fldname;
2802 2802
                 $template_form_field[$field_id] = array(
2803
-                    'name'       => 'message_type_settings[' . $fldname . ']',
2803
+                    'name'       => 'message_type_settings['.$fldname.']',
2804 2804
                     'label'      => $fldprops['label'],
2805 2805
                     'input'      => $fldprops['field_type'],
2806 2806
                     'type'       => $fldprops['value_type'],
@@ -2841,7 +2841,7 @@  discard block
 block discarded – undo
2841 2841
         $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2842 2842
         
2843 2843
         
2844
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2844
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_mt_settings_content.template.php';
2845 2845
         $content  = EEH_Template::display_template($template, $settings_template_args, true);
2846 2846
         
2847 2847
         return $content;
@@ -2871,11 +2871,11 @@  discard block
 block discarded – undo
2871 2871
                 $active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2872 2872
                     ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2873 2873
                     : '';
2874
-                $m_boxes[$messenger . '_a_box']         = sprintf(
2874
+                $m_boxes[$messenger.'_a_box']         = sprintf(
2875 2875
                     __('%s Settings', 'event_espresso'),
2876 2876
                     $tab_array['label']
2877 2877
                 );
2878
-                $m_template_args[$messenger . '_a_box'] = array(
2878
+                $m_template_args[$messenger.'_a_box'] = array(
2879 2879
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2880 2880
                     'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2881 2881
                         ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
@@ -2889,8 +2889,8 @@  discard block
 block discarded – undo
2889 2889
                 // message type meta boxes
2890 2890
                 // (which is really just the inactive container for each messenger
2891 2891
                 // showing inactive message types for that messenger)
2892
-                $mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2893
-                $mt_template_args[$messenger . '_i_box'] = array(
2892
+                $mt_boxes[$messenger.'_i_box']         = __('Inactive Message Types', 'event_espresso');
2893
+                $mt_template_args[$messenger.'_i_box'] = array(
2894 2894
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2895 2895
                     'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2896 2896
                         ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
@@ -2906,14 +2906,14 @@  discard block
 block discarded – undo
2906 2906
         
2907 2907
         
2908 2908
         //register messenger metaboxes
2909
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2909
+        $m_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_mt_meta_box.template.php';
2910 2910
         foreach ($m_boxes as $box => $label) {
2911 2911
             $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2912 2912
             $msgr          = str_replace('_a_box', '', $box);
2913 2913
             add_meta_box(
2914
-                'espresso_' . $msgr . '_settings',
2914
+                'espresso_'.$msgr.'_settings',
2915 2915
                 $label,
2916
-                function ($post, $metabox) {
2916
+                function($post, $metabox) {
2917 2917
                     echo EEH_Template::display_template($metabox["args"]["template_path"],
2918 2918
                         $metabox["args"]["template_args"], true);
2919 2919
                 },
@@ -2925,17 +2925,17 @@  discard block
 block discarded – undo
2925 2925
         }
2926 2926
         
2927 2927
         //register message type metaboxes
2928
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2928
+        $mt_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_meta_box.template.php';
2929 2929
         foreach ($mt_boxes as $box => $label) {
2930 2930
             $callback_args = array(
2931 2931
                 'template_path' => $mt_template_path,
2932 2932
                 'template_args' => $mt_template_args[$box]
2933 2933
             );
2934
-            $mt            = str_replace('_i_box', '', $box);
2934
+            $mt = str_replace('_i_box', '', $box);
2935 2935
             add_meta_box(
2936
-                'espresso_' . $mt . '_inactive_mts',
2936
+                'espresso_'.$mt.'_inactive_mts',
2937 2937
                 $label,
2938
-                function ($post, $metabox) {
2938
+                function($post, $metabox) {
2939 2939
                     echo EEH_Template::display_template($metabox["args"]["template_path"],
2940 2940
                         $metabox["args"]["template_args"], true);
2941 2941
                 },
@@ -3037,7 +3037,7 @@  discard block
 block discarded – undo
3037 3037
             if ($form->is_valid()) {
3038 3038
                 $valid_data = $form->valid_data();
3039 3039
                 foreach ($valid_data as $property => $value) {
3040
-                    $setter = 'set_' . $property;
3040
+                    $setter = 'set_'.$property;
3041 3041
                     if (method_exists($network_config, $setter)) {
3042 3042
                         $network_config->{$setter}($value);
3043 3043
                     } else if (
@@ -3066,8 +3066,8 @@  discard block
 block discarded – undo
3066 3066
      */
3067 3067
     protected function _get_mt_tabs($tab_array)
3068 3068
     {
3069
-        $tab_array = (array)$tab_array;
3070
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3069
+        $tab_array = (array) $tab_array;
3070
+        $template  = EE_MSG_TEMPLATE_PATH.'ee_msg_details_mt_settings_tab_item.template.php';
3071 3071
         $tabs      = '';
3072 3072
         
3073 3073
         foreach ($tab_array as $tab) {
@@ -3100,9 +3100,9 @@  discard block
 block discarded – undo
3100 3100
             $existing_settings = $messenger->get_existing_admin_settings();
3101 3101
             
3102 3102
             foreach ($fields as $fldname => $fldprops) {
3103
-                $field_id                       = $messenger->name . '-' . $fldname;
3103
+                $field_id                       = $messenger->name.'-'.$fldname;
3104 3104
                 $template_form_field[$field_id] = array(
3105
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3105
+                    'name'       => 'messenger_settings['.$field_id.']',
3106 3106
                     'label'      => $fldprops['label'],
3107 3107
                     'input'      => $fldprops['field_type'],
3108 3108
                     'type'       => $fldprops['value_type'],
@@ -3137,7 +3137,7 @@  discard block
 block discarded – undo
3137 3137
         //make sure any active message types that are existing are included in the hidden fields
3138 3138
         if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3139 3139
             foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3140
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3140
+                $settings_template_args['hidden_fields']['messenger_settings[message_types]['.$mt.']'] = array(
3141 3141
                     'type'  => 'hidden',
3142 3142
                     'value' => $mt
3143 3143
                 );
@@ -3147,7 +3147,7 @@  discard block
 block discarded – undo
3147 3147
             $settings_template_args['hidden_fields'],
3148 3148
             'array'
3149 3149
         );
3150
-        $active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3150
+        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3151 3151
         
3152 3152
         $settings_template_args['messenger']           = $messenger->name;
3153 3153
         $settings_template_args['description']         = $messenger->description;
@@ -3164,9 +3164,9 @@  discard block
 block discarded – undo
3164 3164
         
3165 3165
         
3166 3166
         $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3167
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3167
+        $settings_template_args['nonce']         = wp_create_nonce('activate_'.$messenger->name.'_toggle_nonce');
3168 3168
         $settings_template_args['on_off_status'] = $active ? true : false;
3169
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3169
+        $template                                = EE_MSG_TEMPLATE_PATH.'ee_msg_m_settings_content.template.php';
3170 3170
         $content                                 = EEH_Template::display_template($template, $settings_template_args,
3171 3171
             true);
3172 3172
         
@@ -3194,7 +3194,7 @@  discard block
 block discarded – undo
3194 3194
         
3195 3195
         //do a nonce check here since we're not arriving via a normal route
3196 3196
         $nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3197
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3197
+        $nonce_ref = 'activate_'.$this->_req_data['messenger'].'_toggle_nonce';
3198 3198
         
3199 3199
         $this->_verify_nonce($nonce, $nonce_ref);
3200 3200
         
@@ -3296,7 +3296,7 @@  discard block
 block discarded – undo
3296 3296
         
3297 3297
         //do a nonce check here since we're not arriving via a normal route
3298 3298
         $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3299
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3299
+        $nonce_ref = $this->_req_data['message_type'].'_nonce';
3300 3300
         
3301 3301
         $this->_verify_nonce($nonce, $nonce_ref);
3302 3302
         
Please login to merge, or discard this patch.
Indentation   +3620 added lines, -3620 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('NO direct script access allowed');
2
+	exit('NO direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -17,2213 +17,2213 @@  discard block
 block discarded – undo
17 17
 class Messages_Admin_Page extends EE_Admin_Page
18 18
 {
19 19
     
20
-    /**
21
-     * @type EE_Message_Resource_Manager $_message_resource_manager
22
-     */
23
-    protected $_message_resource_manager;
24
-    
25
-    /**
26
-     * @type string $_active_message_type_name
27
-     */
28
-    protected $_active_message_type_name = '';
29
-    
30
-    /**
31
-     * @type EE_messenger $_active_messenger
32
-     */
33
-    protected $_active_messenger;
34
-    protected $_activate_state;
35
-    protected $_activate_meta_box_type;
36
-    protected $_current_message_meta_box;
37
-    protected $_current_message_meta_box_object;
38
-    protected $_context_switcher;
39
-    protected $_shortcodes = array();
40
-    protected $_active_messengers = array();
41
-    protected $_active_message_types = array();
42
-    
43
-    /**
44
-     * @var EE_Message_Template_Group $_message_template_group
45
-     */
46
-    protected $_message_template_group;
47
-    protected $_m_mt_settings = array();
48
-    
49
-    
50
-    /**
51
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
52
-     * IF there is no group then it gets automatically set to the Default template pack.
53
-     *
54
-     * @since 4.5.0
55
-     *
56
-     * @var EE_Messages_Template_Pack
57
-     */
58
-    protected $_template_pack;
59
-    
60
-    
61
-    /**
62
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
63
-     * group is.  If there is no group then it automatically gets set to default.
64
-     *
65
-     * @since 4.5.0
66
-     *
67
-     * @var string
68
-     */
69
-    protected $_variation;
70
-    
71
-    
72
-    /**
73
-     * @param bool $routing
74
-     */
75
-    public function __construct($routing = true)
76
-    {
77
-        //make sure messages autoloader is running
78
-        EED_Messages::set_autoloaders();
79
-        parent::__construct($routing);
80
-    }
81
-    
82
-    
83
-    protected function _init_page_props()
84
-    {
85
-        $this->page_slug        = EE_MSG_PG_SLUG;
86
-        $this->page_label       = __('Messages Settings', 'event_espresso');
87
-        $this->_admin_base_url  = EE_MSG_ADMIN_URL;
88
-        $this->_admin_base_path = EE_MSG_ADMIN;
89
-        
90
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
91
-        
92
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93
-        $this->_load_message_resource_manager();
94
-    }
95
-    
96
-    
97
-    /**
98
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
99
-     *
100
-     *
101
-     * @throws EE_Error
102
-     */
103
-    protected function _load_message_resource_manager()
104
-    {
105
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
106
-    }
107
-    
108
-    
109
-    /**
110
-     * @deprecated 4.9.9.rc.014
111
-     * @return array
112
-     */
113
-    public function get_messengers_for_list_table()
114
-    {
115
-        EE_Error::doing_it_wrong(
116
-            __METHOD__,
117
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
20
+	/**
21
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
22
+	 */
23
+	protected $_message_resource_manager;
24
+    
25
+	/**
26
+	 * @type string $_active_message_type_name
27
+	 */
28
+	protected $_active_message_type_name = '';
29
+    
30
+	/**
31
+	 * @type EE_messenger $_active_messenger
32
+	 */
33
+	protected $_active_messenger;
34
+	protected $_activate_state;
35
+	protected $_activate_meta_box_type;
36
+	protected $_current_message_meta_box;
37
+	protected $_current_message_meta_box_object;
38
+	protected $_context_switcher;
39
+	protected $_shortcodes = array();
40
+	protected $_active_messengers = array();
41
+	protected $_active_message_types = array();
42
+    
43
+	/**
44
+	 * @var EE_Message_Template_Group $_message_template_group
45
+	 */
46
+	protected $_message_template_group;
47
+	protected $_m_mt_settings = array();
48
+    
49
+    
50
+	/**
51
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
52
+	 * IF there is no group then it gets automatically set to the Default template pack.
53
+	 *
54
+	 * @since 4.5.0
55
+	 *
56
+	 * @var EE_Messages_Template_Pack
57
+	 */
58
+	protected $_template_pack;
59
+    
60
+    
61
+	/**
62
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
63
+	 * group is.  If there is no group then it automatically gets set to default.
64
+	 *
65
+	 * @since 4.5.0
66
+	 *
67
+	 * @var string
68
+	 */
69
+	protected $_variation;
70
+    
71
+    
72
+	/**
73
+	 * @param bool $routing
74
+	 */
75
+	public function __construct($routing = true)
76
+	{
77
+		//make sure messages autoloader is running
78
+		EED_Messages::set_autoloaders();
79
+		parent::__construct($routing);
80
+	}
81
+    
82
+    
83
+	protected function _init_page_props()
84
+	{
85
+		$this->page_slug        = EE_MSG_PG_SLUG;
86
+		$this->page_label       = __('Messages Settings', 'event_espresso');
87
+		$this->_admin_base_url  = EE_MSG_ADMIN_URL;
88
+		$this->_admin_base_path = EE_MSG_ADMIN;
89
+        
90
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
91
+        
92
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93
+		$this->_load_message_resource_manager();
94
+	}
95
+    
96
+    
97
+	/**
98
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
99
+	 *
100
+	 *
101
+	 * @throws EE_Error
102
+	 */
103
+	protected function _load_message_resource_manager()
104
+	{
105
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
106
+	}
107
+    
108
+    
109
+	/**
110
+	 * @deprecated 4.9.9.rc.014
111
+	 * @return array
112
+	 */
113
+	public function get_messengers_for_list_table()
114
+	{
115
+		EE_Error::doing_it_wrong(
116
+			__METHOD__,
117
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
118 118
 			values for use in creating a messenger filter dropdown which is now generated differently via
119 119
 			 Messages_Admin_Page::get_messengers_select_input', 'event_espresso'),
120
-            '4.9.9.rc.014'
121
-        );
122
-        
123
-        $m_values          = array();
124
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
125
-        //setup messengers for selects
126
-        $i = 1;
127
-        foreach ($active_messengers as $active_messenger) {
128
-            if ($active_messenger instanceof EE_Message) {
129
-                $m_values[$i]['id']   = $active_messenger->messenger();
130
-                $m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
131
-                $i++;
132
-            }
133
-        }
134
-        
135
-        return $m_values;
136
-    }
137
-    
138
-    
139
-    /**
140
-     * @deprecated 4.9.9.rc.014
141
-     * @return array
142
-     */
143
-    public function get_message_types_for_list_table()
144
-    {
145
-        EE_Error::doing_it_wrong(
146
-            __METHOD__,
147
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
120
+			'4.9.9.rc.014'
121
+		);
122
+        
123
+		$m_values          = array();
124
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
125
+		//setup messengers for selects
126
+		$i = 1;
127
+		foreach ($active_messengers as $active_messenger) {
128
+			if ($active_messenger instanceof EE_Message) {
129
+				$m_values[$i]['id']   = $active_messenger->messenger();
130
+				$m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
131
+				$i++;
132
+			}
133
+		}
134
+        
135
+		return $m_values;
136
+	}
137
+    
138
+    
139
+	/**
140
+	 * @deprecated 4.9.9.rc.014
141
+	 * @return array
142
+	 */
143
+	public function get_message_types_for_list_table()
144
+	{
145
+		EE_Error::doing_it_wrong(
146
+			__METHOD__,
147
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
148 148
 			values for use in creating a message type filter dropdown which is now generated differently via
149 149
 			 Messages_Admin_Page::get_message_types_select_input', 'event_espresso'),
150
-            '4.9.9.rc.014'
151
-        );
152
-        
153
-        $mt_values       = array();
154
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
155
-        $i               = 1;
156
-        foreach ($active_messages as $active_message) {
157
-            if ($active_message instanceof EE_Message) {
158
-                $mt_values[$i]['id']   = $active_message->message_type();
159
-                $mt_values[$i]['text'] = ucwords($active_message->message_type_label());
160
-                $i++;
161
-            }
162
-        }
163
-        
164
-        return $mt_values;
165
-    }
166
-    
167
-    
168
-    /**
169
-     * @deprecated 4.9.9.rc.014
170
-     * @return array
171
-     */
172
-    public function get_contexts_for_message_types_for_list_table()
173
-    {
174
-        EE_Error::doing_it_wrong(
175
-            __METHOD__,
176
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
150
+			'4.9.9.rc.014'
151
+		);
152
+        
153
+		$mt_values       = array();
154
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
155
+		$i               = 1;
156
+		foreach ($active_messages as $active_message) {
157
+			if ($active_message instanceof EE_Message) {
158
+				$mt_values[$i]['id']   = $active_message->message_type();
159
+				$mt_values[$i]['text'] = ucwords($active_message->message_type_label());
160
+				$i++;
161
+			}
162
+		}
163
+        
164
+		return $mt_values;
165
+	}
166
+    
167
+    
168
+	/**
169
+	 * @deprecated 4.9.9.rc.014
170
+	 * @return array
171
+	 */
172
+	public function get_contexts_for_message_types_for_list_table()
173
+	{
174
+		EE_Error::doing_it_wrong(
175
+			__METHOD__,
176
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
177 177
 			values for use in creating a message type context filter dropdown which is now generated differently via
178 178
 			 Messages_Admin_Page::get_contexts_for_message_types_select_input', 'event_espresso'),
179
-            '4.9.9.rc.014'
180
-        );
181
-        
182
-        $contexts                = array();
183
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
184
-        foreach ($active_message_contexts as $active_message) {
185
-            if ($active_message instanceof EE_Message) {
186
-                $message_type = $active_message->message_type_object();
187
-                if ($message_type instanceof EE_message_type) {
188
-                    $message_type_contexts = $message_type->get_contexts();
189
-                    foreach ($message_type_contexts as $context => $context_details) {
190
-                        $contexts[$context] = $context_details['label'];
191
-                    }
192
-                }
193
-            }
194
-        }
195
-        
196
-        return $contexts;
197
-    }
198
-    
199
-    
200
-    /**
201
-     * Generate select input with provided messenger options array.
202
-     *
203
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
204
-     *                                 labels.
205
-     *
206
-     * @return string
207
-     */
208
-    public function get_messengers_select_input($messenger_options)
209
-    {
210
-        //if empty or just one value then just return an empty string
211
-        if (empty($messenger_options)
212
-            || ! is_array($messenger_options)
213
-            || count($messenger_options) === 1
214
-        ) {
215
-            return '';
216
-        }
217
-        //merge in default
218
-        $messenger_options = array_merge(
219
-            array('none_selected' => __('Show All Messengers', 'event_espresso')),
220
-            $messenger_options
221
-        );
222
-        $input             = new EE_Select_Input(
223
-            $messenger_options,
224
-            array(
225
-                'html_name'  => 'ee_messenger_filter_by',
226
-                'html_id'    => 'ee_messenger_filter_by',
227
-                'html_class' => 'wide',
228
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
229
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
230
-                    : 'none_selected'
231
-            )
232
-        );
233
-        
234
-        return $input->get_html_for_input();
235
-    }
236
-    
237
-    
238
-    /**
239
-     * Generate select input with provided message type options array.
240
-     *
241
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
242
-     *                                    message type labels
243
-     *
244
-     * @return string
245
-     */
246
-    public function get_message_types_select_input($message_type_options)
247
-    {
248
-        //if empty or count of options is 1 then just return an empty string
249
-        if (empty($message_type_options)
250
-            || ! is_array($message_type_options)
251
-            || count($message_type_options) === 1
252
-        ) {
253
-            return '';
254
-        }
255
-        //merge in default
256
-        $message_type_options = array_merge(
257
-            array('none_selected' => __('Show All Message Types', 'event_espresso')),
258
-            $message_type_options
259
-        );
260
-        $input                = new EE_Select_Input(
261
-            $message_type_options,
262
-            array(
263
-                'html_name'  => 'ee_message_type_filter_by',
264
-                'html_id'    => 'ee_message_type_filter_by',
265
-                'html_class' => 'wide',
266
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
267
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
268
-                    : 'none_selected',
269
-            )
270
-        );
271
-        
272
-        return $input->get_html_for_input();
273
-    }
274
-    
275
-    
276
-    /**
277
-     * Generate select input with provide message type contexts array.
278
-     *
279
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
280
-     *                               context label.
281
-     *
282
-     * @return string
283
-     */
284
-    public function get_contexts_for_message_types_select_input($context_options)
285
-    {
286
-        //if empty or count of options is one then just return empty string
287
-        if (empty($context_options)
288
-            || ! is_array($context_options)
289
-            || count($context_options) === 1
290
-        ) {
291
-            return '';
292
-        }
293
-        //merge in default
294
-        $context_options = array_merge(
295
-            array('none_selected' => __('Show all Contexts', 'event_espresso')),
296
-            $context_options
297
-        );
298
-        $input           = new EE_Select_Input(
299
-            $context_options,
300
-            array(
301
-                'html_name'  => 'ee_context_filter_by',
302
-                'html_id'    => 'ee_context_filter_by',
303
-                'html_class' => 'wide',
304
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
305
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
306
-                    : 'none_selected',
307
-            )
308
-        );
309
-        
310
-        return $input->get_html_for_input();
311
-    }
312
-    
313
-    
314
-    protected function _ajax_hooks()
315
-    {
316
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
317
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
318
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
319
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
320
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
321
-    }
322
-    
323
-    
324
-    protected function _define_page_props()
325
-    {
326
-        $this->_admin_page_title = $this->page_label;
327
-        $this->_labels           = array(
328
-            'buttons'    => array(
329
-                'add'    => __('Add New Message Template', 'event_espresso'),
330
-                'edit'   => __('Edit Message Template', 'event_espresso'),
331
-                'delete' => __('Delete Message Template', 'event_espresso')
332
-            ),
333
-            'publishbox' => __('Update Actions', 'event_espresso')
334
-        );
335
-    }
336
-    
337
-    
338
-    /**
339
-     *        an array for storing key => value pairs of request actions and their corresponding methods
340
-     * @access protected
341
-     * @return void
342
-     */
343
-    protected function _set_page_routes()
344
-    {
345
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
346
-            ? $this->_req_data['GRP_ID']
347
-            : 0;
348
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
349
-            ? $this->_req_data['id']
350
-            : $grp_id;
351
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
352
-            ? $this->_req_data['MSG_ID']
353
-            : 0;
354
-        
355
-        $this->_page_routes = array(
356
-            'default'                          => array(
357
-                'func'       => '_message_queue_list_table',
358
-                'capability' => 'ee_read_global_messages'
359
-            ),
360
-            'global_mtps'                      => array(
361
-                'func'       => '_ee_default_messages_overview_list_table',
362
-                'capability' => 'ee_read_global_messages'
363
-            ),
364
-            'custom_mtps'                      => array(
365
-                'func'       => '_custom_mtps_preview',
366
-                'capability' => 'ee_read_messages'
367
-            ),
368
-            'add_new_message_template'         => array(
369
-                'func'       => '_add_message_template',
370
-                'capability' => 'ee_edit_messages',
371
-                'noheader'   => true
372
-            ),
373
-            'edit_message_template'            => array(
374
-                'func'       => '_edit_message_template',
375
-                'capability' => 'ee_edit_message',
376
-                'obj_id'     => $grp_id
377
-            ),
378
-            'preview_message'                  => array(
379
-                'func'               => '_preview_message',
380
-                'capability'         => 'ee_read_message',
381
-                'obj_id'             => $grp_id,
382
-                'noheader'           => true,
383
-                'headers_sent_route' => 'display_preview_message'
384
-            ),
385
-            'display_preview_message'          => array(
386
-                'func'       => '_display_preview_message',
387
-                'capability' => 'ee_read_message',
388
-                'obj_id'     => $grp_id
389
-            ),
390
-            'insert_message_template'          => array(
391
-                'func'       => '_insert_or_update_message_template',
392
-                'capability' => 'ee_edit_messages',
393
-                'args'       => array('new_template' => true),
394
-                'noheader'   => true
395
-            ),
396
-            'update_message_template'          => array(
397
-                'func'       => '_insert_or_update_message_template',
398
-                'capability' => 'ee_edit_message',
399
-                'obj_id'     => $grp_id,
400
-                'args'       => array('new_template' => false),
401
-                'noheader'   => true
402
-            ),
403
-            'trash_message_template'           => array(
404
-                'func'       => '_trash_or_restore_message_template',
405
-                'capability' => 'ee_delete_message',
406
-                'obj_id'     => $grp_id,
407
-                'args'       => array('trash' => true, 'all' => true),
408
-                'noheader'   => true
409
-            ),
410
-            'trash_message_template_context'   => array(
411
-                'func'       => '_trash_or_restore_message_template',
412
-                'capability' => 'ee_delete_message',
413
-                'obj_id'     => $grp_id,
414
-                'args'       => array('trash' => true),
415
-                'noheader'   => true
416
-            ),
417
-            'restore_message_template'         => array(
418
-                'func'       => '_trash_or_restore_message_template',
419
-                'capability' => 'ee_delete_message',
420
-                'obj_id'     => $grp_id,
421
-                'args'       => array('trash' => false, 'all' => true),
422
-                'noheader'   => true
423
-            ),
424
-            'restore_message_template_context' => array(
425
-                'func'       => '_trash_or_restore_message_template',
426
-                'capability' => 'ee_delete_message',
427
-                'obj_id'     => $grp_id,
428
-                'args'       => array('trash' => false),
429
-                'noheader'   => true
430
-            ),
431
-            'delete_message_template'          => array(
432
-                'func'       => '_delete_message_template',
433
-                'capability' => 'ee_delete_message',
434
-                'obj_id'     => $grp_id,
435
-                'noheader'   => true
436
-            ),
437
-            'reset_to_default'                 => array(
438
-                'func'       => '_reset_to_default_template',
439
-                'capability' => 'ee_edit_message',
440
-                'obj_id'     => $grp_id,
441
-                'noheader'   => true
442
-            ),
443
-            'settings'                         => array(
444
-                'func'       => '_settings',
445
-                'capability' => 'manage_options'
446
-            ),
447
-            'update_global_settings'           => array(
448
-                'func'       => '_update_global_settings',
449
-                'capability' => 'manage_options',
450
-                'noheader'   => true
451
-            ),
452
-            'generate_now'                     => array(
453
-                'func'       => '_generate_now',
454
-                'capability' => 'ee_send_message',
455
-                'noheader'   => true
456
-            ),
457
-            'generate_and_send_now'            => array(
458
-                'func'       => '_generate_and_send_now',
459
-                'capability' => 'ee_send_message',
460
-                'noheader'   => true
461
-            ),
462
-            'queue_for_resending'              => array(
463
-                'func'       => '_queue_for_resending',
464
-                'capability' => 'ee_send_message',
465
-                'noheader'   => true
466
-            ),
467
-            'send_now'                         => array(
468
-                'func'       => '_send_now',
469
-                'capability' => 'ee_send_message',
470
-                'noheader'   => true
471
-            ),
472
-            'delete_ee_message'                => array(
473
-                'func'       => '_delete_ee_messages',
474
-                'capability' => 'ee_delete_message',
475
-                'noheader'   => true
476
-            ),
477
-            'delete_ee_messages'               => array(
478
-                'func'       => '_delete_ee_messages',
479
-                'capability' => 'ee_delete_messages',
480
-                'noheader'   => true,
481
-                'obj_id'     => $msg_id
482
-            )
483
-        );
484
-    }
485
-    
486
-    
487
-    protected function _set_page_config()
488
-    {
489
-        $this->_page_config = array(
490
-            'default'                  => array(
491
-                'nav'           => array(
492
-                    'label' => __('Message Activity', 'event_espresso'),
493
-                    'order' => 10
494
-                ),
495
-                'list_table'    => 'EE_Message_List_Table',
496
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
497
-                'require_nonce' => false
498
-            ),
499
-            'global_mtps'              => array(
500
-                'nav'           => array(
501
-                    'label' => __('Default Message Templates', 'event_espresso'),
502
-                    'order' => 20
503
-                ),
504
-                'list_table'    => 'Messages_Template_List_Table',
505
-                'help_tabs'     => array(
506
-                    'messages_overview_help_tab'                                => array(
507
-                        'title'    => __('Messages Overview', 'event_espresso'),
508
-                        'filename' => 'messages_overview'
509
-                    ),
510
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
511
-                        'title'    => __('Messages Table Column Headings', 'event_espresso'),
512
-                        'filename' => 'messages_overview_table_column_headings'
513
-                    ),
514
-                    'messages_overview_messages_filters_help_tab'               => array(
515
-                        'title'    => __('Message Filters', 'event_espresso'),
516
-                        'filename' => 'messages_overview_filters'
517
-                    ),
518
-                    'messages_overview_messages_views_help_tab'                 => array(
519
-                        'title'    => __('Message Views', 'event_espresso'),
520
-                        'filename' => 'messages_overview_views'
521
-                    ),
522
-                    'message_overview_message_types_help_tab'                   => array(
523
-                        'title'    => __('Message Types', 'event_espresso'),
524
-                        'filename' => 'messages_overview_types'
525
-                    ),
526
-                    'messages_overview_messengers_help_tab'                     => array(
527
-                        'title'    => __('Messengers', 'event_espresso'),
528
-                        'filename' => 'messages_overview_messengers',
529
-                    ),
530
-                    'messages_overview_other_help_tab'                          => array(
531
-                        'title'    => __('Messages Other', 'event_espresso'),
532
-                        'filename' => 'messages_overview_other',
533
-                    ),
534
-                ),
535
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
536
-                'require_nonce' => false
537
-            ),
538
-            'custom_mtps'              => array(
539
-                'nav'           => array(
540
-                    'label' => __('Custom Message Templates', 'event_espresso'),
541
-                    'order' => 30
542
-                ),
543
-                'help_tabs'     => array(),
544
-                'help_tour'     => array(),
545
-                'require_nonce' => false
546
-            ),
547
-            'add_new_message_template' => array(
548
-                'nav'           => array(
549
-                    'label'      => __('Add New Message Templates', 'event_espresso'),
550
-                    'order'      => 5,
551
-                    'persistent' => false
552
-                ),
553
-                'require_nonce' => false
554
-            ),
555
-            'edit_message_template'    => array(
556
-                'labels'        => array(
557
-                    'buttons'    => array(
558
-                        'reset' => __('Reset Templates'),
559
-                    ),
560
-                    'publishbox' => __('Update Actions', 'event_espresso')
561
-                ),
562
-                'nav'           => array(
563
-                    'label'      => __('Edit Message Templates', 'event_espresso'),
564
-                    'order'      => 5,
565
-                    'persistent' => false,
566
-                    'url'        => ''
567
-                ),
568
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
569
-                'has_metaboxes' => true,
570
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
571
-                'help_tabs'     => array(
572
-                    'edit_message_template'       => array(
573
-                        'title'    => __('Message Template Editor', 'event_espresso'),
574
-                        'callback' => 'edit_message_template_help_tab'
575
-                    ),
576
-                    'message_templates_help_tab'  => array(
577
-                        'title'    => __('Message Templates', 'event_espresso'),
578
-                        'filename' => 'messages_templates'
579
-                    ),
580
-                    'message_template_shortcodes' => array(
581
-                        'title'    => __('Message Shortcodes', 'event_espresso'),
582
-                        'callback' => 'message_template_shortcodes_help_tab'
583
-                    ),
584
-                    'message_preview_help_tab'    => array(
585
-                        'title'    => __('Message Preview', 'event_espresso'),
586
-                        'filename' => 'messages_preview'
587
-                    ),
588
-                ),
589
-                'require_nonce' => false
590
-            ),
591
-            'display_preview_message'  => array(
592
-                'nav'           => array(
593
-                    'label'      => __('Message Preview', 'event_espresso'),
594
-                    'order'      => 5,
595
-                    'url'        => '',
596
-                    'persistent' => false
597
-                ),
598
-                'help_tabs'     => array(
599
-                    'preview_message' => array(
600
-                        'title'    => __('About Previews', 'event_espresso'),
601
-                        'callback' => 'preview_message_help_tab'
602
-                    )
603
-                ),
604
-                'require_nonce' => false
605
-            ),
606
-            'settings'                 => array(
607
-                'nav'           => array(
608
-                    'label' => __('Settings', 'event_espresso'),
609
-                    'order' => 40
610
-                ),
611
-                'metaboxes'     => array('_messages_settings_metaboxes'),
612
-                'help_tabs'     => array(
613
-                    'messages_settings_help_tab'               => array(
614
-                        'title'    => __('Messages Settings', 'event_espresso'),
615
-                        'filename' => 'messages_settings'
616
-                    ),
617
-                    'messages_settings_message_types_help_tab' => array(
618
-                        'title'    => __('Activating / Deactivating Message Types', 'event_espresso'),
619
-                        'filename' => 'messages_settings_message_types'
620
-                    ),
621
-                    'messages_settings_messengers_help_tab'    => array(
622
-                        'title'    => __('Activating / Deactivating Messengers', 'event_espresso'),
623
-                        'filename' => 'messages_settings_messengers'
624
-                    ),
625
-                ),
626
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
627
-                'require_nonce' => false
628
-            )
629
-        );
630
-    }
631
-    
632
-    
633
-    protected function _add_screen_options()
634
-    {
635
-        //todo
636
-    }
637
-    
638
-    
639
-    protected function _add_screen_options_global_mtps()
640
-    {
641
-        /**
642
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
643
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
644
-         */
645
-        $page_title              = $this->_admin_page_title;
646
-        $this->_admin_page_title = __('Global Message Templates', 'event_espresso');
647
-        $this->_per_page_screen_option();
648
-        $this->_admin_page_title = $page_title;
649
-    }
650
-    
651
-    
652
-    protected function _add_screen_options_default()
653
-    {
654
-        $this->_admin_page_title = __('Message Activity', 'event_espresso');
655
-        $this->_per_page_screen_option();
656
-    }
657
-    
658
-    
659
-    //none of the below group are currently used for Messages
660
-    protected function _add_feature_pointers()
661
-    {
662
-    }
663
-    
664
-    public function admin_init()
665
-    {
666
-    }
667
-    
668
-    public function admin_notices()
669
-    {
670
-    }
671
-    
672
-    public function admin_footer_scripts()
673
-    {
674
-    }
675
-    
676
-    
677
-    public function messages_help_tab()
678
-    {
679
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
680
-    }
681
-    
682
-    
683
-    public function messengers_help_tab()
684
-    {
685
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
686
-    }
687
-    
688
-    
689
-    public function message_types_help_tab()
690
-    {
691
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
692
-    }
693
-    
694
-    
695
-    public function messages_overview_help_tab()
696
-    {
697
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
698
-    }
699
-    
700
-    
701
-    public function message_templates_help_tab()
702
-    {
703
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
704
-    }
705
-    
706
-    
707
-    public function edit_message_template_help_tab()
708
-    {
709
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
-                'event_espresso') . '" />';
711
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
-                'event_espresso') . '" />';
713
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
-                'event_espresso') . '" />';
715
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
-                'event_espresso') . '" />';
717
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
-                'event_espresso') . '" />';
719
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
720
-            $args);
721
-    }
722
-    
723
-    
724
-    public function message_template_shortcodes_help_tab()
725
-    {
726
-        $this->_set_shortcodes();
727
-        $args['shortcodes'] = $this->_shortcodes;
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
729
-            $args);
730
-    }
179
+			'4.9.9.rc.014'
180
+		);
181
+        
182
+		$contexts                = array();
183
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
184
+		foreach ($active_message_contexts as $active_message) {
185
+			if ($active_message instanceof EE_Message) {
186
+				$message_type = $active_message->message_type_object();
187
+				if ($message_type instanceof EE_message_type) {
188
+					$message_type_contexts = $message_type->get_contexts();
189
+					foreach ($message_type_contexts as $context => $context_details) {
190
+						$contexts[$context] = $context_details['label'];
191
+					}
192
+				}
193
+			}
194
+		}
195
+        
196
+		return $contexts;
197
+	}
198
+    
199
+    
200
+	/**
201
+	 * Generate select input with provided messenger options array.
202
+	 *
203
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
204
+	 *                                 labels.
205
+	 *
206
+	 * @return string
207
+	 */
208
+	public function get_messengers_select_input($messenger_options)
209
+	{
210
+		//if empty or just one value then just return an empty string
211
+		if (empty($messenger_options)
212
+			|| ! is_array($messenger_options)
213
+			|| count($messenger_options) === 1
214
+		) {
215
+			return '';
216
+		}
217
+		//merge in default
218
+		$messenger_options = array_merge(
219
+			array('none_selected' => __('Show All Messengers', 'event_espresso')),
220
+			$messenger_options
221
+		);
222
+		$input             = new EE_Select_Input(
223
+			$messenger_options,
224
+			array(
225
+				'html_name'  => 'ee_messenger_filter_by',
226
+				'html_id'    => 'ee_messenger_filter_by',
227
+				'html_class' => 'wide',
228
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
229
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
230
+					: 'none_selected'
231
+			)
232
+		);
233
+        
234
+		return $input->get_html_for_input();
235
+	}
236
+    
237
+    
238
+	/**
239
+	 * Generate select input with provided message type options array.
240
+	 *
241
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
242
+	 *                                    message type labels
243
+	 *
244
+	 * @return string
245
+	 */
246
+	public function get_message_types_select_input($message_type_options)
247
+	{
248
+		//if empty or count of options is 1 then just return an empty string
249
+		if (empty($message_type_options)
250
+			|| ! is_array($message_type_options)
251
+			|| count($message_type_options) === 1
252
+		) {
253
+			return '';
254
+		}
255
+		//merge in default
256
+		$message_type_options = array_merge(
257
+			array('none_selected' => __('Show All Message Types', 'event_espresso')),
258
+			$message_type_options
259
+		);
260
+		$input                = new EE_Select_Input(
261
+			$message_type_options,
262
+			array(
263
+				'html_name'  => 'ee_message_type_filter_by',
264
+				'html_id'    => 'ee_message_type_filter_by',
265
+				'html_class' => 'wide',
266
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
267
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
268
+					: 'none_selected',
269
+			)
270
+		);
271
+        
272
+		return $input->get_html_for_input();
273
+	}
274
+    
275
+    
276
+	/**
277
+	 * Generate select input with provide message type contexts array.
278
+	 *
279
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
280
+	 *                               context label.
281
+	 *
282
+	 * @return string
283
+	 */
284
+	public function get_contexts_for_message_types_select_input($context_options)
285
+	{
286
+		//if empty or count of options is one then just return empty string
287
+		if (empty($context_options)
288
+			|| ! is_array($context_options)
289
+			|| count($context_options) === 1
290
+		) {
291
+			return '';
292
+		}
293
+		//merge in default
294
+		$context_options = array_merge(
295
+			array('none_selected' => __('Show all Contexts', 'event_espresso')),
296
+			$context_options
297
+		);
298
+		$input           = new EE_Select_Input(
299
+			$context_options,
300
+			array(
301
+				'html_name'  => 'ee_context_filter_by',
302
+				'html_id'    => 'ee_context_filter_by',
303
+				'html_class' => 'wide',
304
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
305
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
306
+					: 'none_selected',
307
+			)
308
+		);
309
+        
310
+		return $input->get_html_for_input();
311
+	}
312
+    
313
+    
314
+	protected function _ajax_hooks()
315
+	{
316
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
317
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
318
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
319
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
320
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
321
+	}
322
+    
323
+    
324
+	protected function _define_page_props()
325
+	{
326
+		$this->_admin_page_title = $this->page_label;
327
+		$this->_labels           = array(
328
+			'buttons'    => array(
329
+				'add'    => __('Add New Message Template', 'event_espresso'),
330
+				'edit'   => __('Edit Message Template', 'event_espresso'),
331
+				'delete' => __('Delete Message Template', 'event_espresso')
332
+			),
333
+			'publishbox' => __('Update Actions', 'event_espresso')
334
+		);
335
+	}
336
+    
337
+    
338
+	/**
339
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
340
+	 * @access protected
341
+	 * @return void
342
+	 */
343
+	protected function _set_page_routes()
344
+	{
345
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
346
+			? $this->_req_data['GRP_ID']
347
+			: 0;
348
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
349
+			? $this->_req_data['id']
350
+			: $grp_id;
351
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
352
+			? $this->_req_data['MSG_ID']
353
+			: 0;
354
+        
355
+		$this->_page_routes = array(
356
+			'default'                          => array(
357
+				'func'       => '_message_queue_list_table',
358
+				'capability' => 'ee_read_global_messages'
359
+			),
360
+			'global_mtps'                      => array(
361
+				'func'       => '_ee_default_messages_overview_list_table',
362
+				'capability' => 'ee_read_global_messages'
363
+			),
364
+			'custom_mtps'                      => array(
365
+				'func'       => '_custom_mtps_preview',
366
+				'capability' => 'ee_read_messages'
367
+			),
368
+			'add_new_message_template'         => array(
369
+				'func'       => '_add_message_template',
370
+				'capability' => 'ee_edit_messages',
371
+				'noheader'   => true
372
+			),
373
+			'edit_message_template'            => array(
374
+				'func'       => '_edit_message_template',
375
+				'capability' => 'ee_edit_message',
376
+				'obj_id'     => $grp_id
377
+			),
378
+			'preview_message'                  => array(
379
+				'func'               => '_preview_message',
380
+				'capability'         => 'ee_read_message',
381
+				'obj_id'             => $grp_id,
382
+				'noheader'           => true,
383
+				'headers_sent_route' => 'display_preview_message'
384
+			),
385
+			'display_preview_message'          => array(
386
+				'func'       => '_display_preview_message',
387
+				'capability' => 'ee_read_message',
388
+				'obj_id'     => $grp_id
389
+			),
390
+			'insert_message_template'          => array(
391
+				'func'       => '_insert_or_update_message_template',
392
+				'capability' => 'ee_edit_messages',
393
+				'args'       => array('new_template' => true),
394
+				'noheader'   => true
395
+			),
396
+			'update_message_template'          => array(
397
+				'func'       => '_insert_or_update_message_template',
398
+				'capability' => 'ee_edit_message',
399
+				'obj_id'     => $grp_id,
400
+				'args'       => array('new_template' => false),
401
+				'noheader'   => true
402
+			),
403
+			'trash_message_template'           => array(
404
+				'func'       => '_trash_or_restore_message_template',
405
+				'capability' => 'ee_delete_message',
406
+				'obj_id'     => $grp_id,
407
+				'args'       => array('trash' => true, 'all' => true),
408
+				'noheader'   => true
409
+			),
410
+			'trash_message_template_context'   => array(
411
+				'func'       => '_trash_or_restore_message_template',
412
+				'capability' => 'ee_delete_message',
413
+				'obj_id'     => $grp_id,
414
+				'args'       => array('trash' => true),
415
+				'noheader'   => true
416
+			),
417
+			'restore_message_template'         => array(
418
+				'func'       => '_trash_or_restore_message_template',
419
+				'capability' => 'ee_delete_message',
420
+				'obj_id'     => $grp_id,
421
+				'args'       => array('trash' => false, 'all' => true),
422
+				'noheader'   => true
423
+			),
424
+			'restore_message_template_context' => array(
425
+				'func'       => '_trash_or_restore_message_template',
426
+				'capability' => 'ee_delete_message',
427
+				'obj_id'     => $grp_id,
428
+				'args'       => array('trash' => false),
429
+				'noheader'   => true
430
+			),
431
+			'delete_message_template'          => array(
432
+				'func'       => '_delete_message_template',
433
+				'capability' => 'ee_delete_message',
434
+				'obj_id'     => $grp_id,
435
+				'noheader'   => true
436
+			),
437
+			'reset_to_default'                 => array(
438
+				'func'       => '_reset_to_default_template',
439
+				'capability' => 'ee_edit_message',
440
+				'obj_id'     => $grp_id,
441
+				'noheader'   => true
442
+			),
443
+			'settings'                         => array(
444
+				'func'       => '_settings',
445
+				'capability' => 'manage_options'
446
+			),
447
+			'update_global_settings'           => array(
448
+				'func'       => '_update_global_settings',
449
+				'capability' => 'manage_options',
450
+				'noheader'   => true
451
+			),
452
+			'generate_now'                     => array(
453
+				'func'       => '_generate_now',
454
+				'capability' => 'ee_send_message',
455
+				'noheader'   => true
456
+			),
457
+			'generate_and_send_now'            => array(
458
+				'func'       => '_generate_and_send_now',
459
+				'capability' => 'ee_send_message',
460
+				'noheader'   => true
461
+			),
462
+			'queue_for_resending'              => array(
463
+				'func'       => '_queue_for_resending',
464
+				'capability' => 'ee_send_message',
465
+				'noheader'   => true
466
+			),
467
+			'send_now'                         => array(
468
+				'func'       => '_send_now',
469
+				'capability' => 'ee_send_message',
470
+				'noheader'   => true
471
+			),
472
+			'delete_ee_message'                => array(
473
+				'func'       => '_delete_ee_messages',
474
+				'capability' => 'ee_delete_message',
475
+				'noheader'   => true
476
+			),
477
+			'delete_ee_messages'               => array(
478
+				'func'       => '_delete_ee_messages',
479
+				'capability' => 'ee_delete_messages',
480
+				'noheader'   => true,
481
+				'obj_id'     => $msg_id
482
+			)
483
+		);
484
+	}
485
+    
486
+    
487
+	protected function _set_page_config()
488
+	{
489
+		$this->_page_config = array(
490
+			'default'                  => array(
491
+				'nav'           => array(
492
+					'label' => __('Message Activity', 'event_espresso'),
493
+					'order' => 10
494
+				),
495
+				'list_table'    => 'EE_Message_List_Table',
496
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
497
+				'require_nonce' => false
498
+			),
499
+			'global_mtps'              => array(
500
+				'nav'           => array(
501
+					'label' => __('Default Message Templates', 'event_espresso'),
502
+					'order' => 20
503
+				),
504
+				'list_table'    => 'Messages_Template_List_Table',
505
+				'help_tabs'     => array(
506
+					'messages_overview_help_tab'                                => array(
507
+						'title'    => __('Messages Overview', 'event_espresso'),
508
+						'filename' => 'messages_overview'
509
+					),
510
+					'messages_overview_messages_table_column_headings_help_tab' => array(
511
+						'title'    => __('Messages Table Column Headings', 'event_espresso'),
512
+						'filename' => 'messages_overview_table_column_headings'
513
+					),
514
+					'messages_overview_messages_filters_help_tab'               => array(
515
+						'title'    => __('Message Filters', 'event_espresso'),
516
+						'filename' => 'messages_overview_filters'
517
+					),
518
+					'messages_overview_messages_views_help_tab'                 => array(
519
+						'title'    => __('Message Views', 'event_espresso'),
520
+						'filename' => 'messages_overview_views'
521
+					),
522
+					'message_overview_message_types_help_tab'                   => array(
523
+						'title'    => __('Message Types', 'event_espresso'),
524
+						'filename' => 'messages_overview_types'
525
+					),
526
+					'messages_overview_messengers_help_tab'                     => array(
527
+						'title'    => __('Messengers', 'event_espresso'),
528
+						'filename' => 'messages_overview_messengers',
529
+					),
530
+					'messages_overview_other_help_tab'                          => array(
531
+						'title'    => __('Messages Other', 'event_espresso'),
532
+						'filename' => 'messages_overview_other',
533
+					),
534
+				),
535
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
536
+				'require_nonce' => false
537
+			),
538
+			'custom_mtps'              => array(
539
+				'nav'           => array(
540
+					'label' => __('Custom Message Templates', 'event_espresso'),
541
+					'order' => 30
542
+				),
543
+				'help_tabs'     => array(),
544
+				'help_tour'     => array(),
545
+				'require_nonce' => false
546
+			),
547
+			'add_new_message_template' => array(
548
+				'nav'           => array(
549
+					'label'      => __('Add New Message Templates', 'event_espresso'),
550
+					'order'      => 5,
551
+					'persistent' => false
552
+				),
553
+				'require_nonce' => false
554
+			),
555
+			'edit_message_template'    => array(
556
+				'labels'        => array(
557
+					'buttons'    => array(
558
+						'reset' => __('Reset Templates'),
559
+					),
560
+					'publishbox' => __('Update Actions', 'event_espresso')
561
+				),
562
+				'nav'           => array(
563
+					'label'      => __('Edit Message Templates', 'event_espresso'),
564
+					'order'      => 5,
565
+					'persistent' => false,
566
+					'url'        => ''
567
+				),
568
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
569
+				'has_metaboxes' => true,
570
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
571
+				'help_tabs'     => array(
572
+					'edit_message_template'       => array(
573
+						'title'    => __('Message Template Editor', 'event_espresso'),
574
+						'callback' => 'edit_message_template_help_tab'
575
+					),
576
+					'message_templates_help_tab'  => array(
577
+						'title'    => __('Message Templates', 'event_espresso'),
578
+						'filename' => 'messages_templates'
579
+					),
580
+					'message_template_shortcodes' => array(
581
+						'title'    => __('Message Shortcodes', 'event_espresso'),
582
+						'callback' => 'message_template_shortcodes_help_tab'
583
+					),
584
+					'message_preview_help_tab'    => array(
585
+						'title'    => __('Message Preview', 'event_espresso'),
586
+						'filename' => 'messages_preview'
587
+					),
588
+				),
589
+				'require_nonce' => false
590
+			),
591
+			'display_preview_message'  => array(
592
+				'nav'           => array(
593
+					'label'      => __('Message Preview', 'event_espresso'),
594
+					'order'      => 5,
595
+					'url'        => '',
596
+					'persistent' => false
597
+				),
598
+				'help_tabs'     => array(
599
+					'preview_message' => array(
600
+						'title'    => __('About Previews', 'event_espresso'),
601
+						'callback' => 'preview_message_help_tab'
602
+					)
603
+				),
604
+				'require_nonce' => false
605
+			),
606
+			'settings'                 => array(
607
+				'nav'           => array(
608
+					'label' => __('Settings', 'event_espresso'),
609
+					'order' => 40
610
+				),
611
+				'metaboxes'     => array('_messages_settings_metaboxes'),
612
+				'help_tabs'     => array(
613
+					'messages_settings_help_tab'               => array(
614
+						'title'    => __('Messages Settings', 'event_espresso'),
615
+						'filename' => 'messages_settings'
616
+					),
617
+					'messages_settings_message_types_help_tab' => array(
618
+						'title'    => __('Activating / Deactivating Message Types', 'event_espresso'),
619
+						'filename' => 'messages_settings_message_types'
620
+					),
621
+					'messages_settings_messengers_help_tab'    => array(
622
+						'title'    => __('Activating / Deactivating Messengers', 'event_espresso'),
623
+						'filename' => 'messages_settings_messengers'
624
+					),
625
+				),
626
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
627
+				'require_nonce' => false
628
+			)
629
+		);
630
+	}
631
+    
632
+    
633
+	protected function _add_screen_options()
634
+	{
635
+		//todo
636
+	}
637
+    
638
+    
639
+	protected function _add_screen_options_global_mtps()
640
+	{
641
+		/**
642
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
643
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
644
+		 */
645
+		$page_title              = $this->_admin_page_title;
646
+		$this->_admin_page_title = __('Global Message Templates', 'event_espresso');
647
+		$this->_per_page_screen_option();
648
+		$this->_admin_page_title = $page_title;
649
+	}
650
+    
651
+    
652
+	protected function _add_screen_options_default()
653
+	{
654
+		$this->_admin_page_title = __('Message Activity', 'event_espresso');
655
+		$this->_per_page_screen_option();
656
+	}
657
+    
658
+    
659
+	//none of the below group are currently used for Messages
660
+	protected function _add_feature_pointers()
661
+	{
662
+	}
663
+    
664
+	public function admin_init()
665
+	{
666
+	}
667
+    
668
+	public function admin_notices()
669
+	{
670
+	}
671
+    
672
+	public function admin_footer_scripts()
673
+	{
674
+	}
675
+    
676
+    
677
+	public function messages_help_tab()
678
+	{
679
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
680
+	}
681
+    
682
+    
683
+	public function messengers_help_tab()
684
+	{
685
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
686
+	}
687
+    
688
+    
689
+	public function message_types_help_tab()
690
+	{
691
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
692
+	}
693
+    
694
+    
695
+	public function messages_overview_help_tab()
696
+	{
697
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
698
+	}
699
+    
700
+    
701
+	public function message_templates_help_tab()
702
+	{
703
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
704
+	}
705
+    
706
+    
707
+	public function edit_message_template_help_tab()
708
+	{
709
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
+				'event_espresso') . '" />';
711
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
+				'event_espresso') . '" />';
713
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
+				'event_espresso') . '" />';
715
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
+				'event_espresso') . '" />';
717
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
+				'event_espresso') . '" />';
719
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
720
+			$args);
721
+	}
722
+    
723
+    
724
+	public function message_template_shortcodes_help_tab()
725
+	{
726
+		$this->_set_shortcodes();
727
+		$args['shortcodes'] = $this->_shortcodes;
728
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
729
+			$args);
730
+	}
731 731
     
732 732
     
733
-    public function preview_message_help_tab()
734
-    {
735
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
736
-    }
733
+	public function preview_message_help_tab()
734
+	{
735
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
736
+	}
737 737
     
738
-    
739
-    public function settings_help_tab()
740
-    {
741
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
-                'event_espresso') . '" />';
743
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
-                'event_espresso') . '" />';
745
-        $args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746
-        $args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
748
-    }
738
+    
739
+	public function settings_help_tab()
740
+	{
741
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
+				'event_espresso') . '" />';
743
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
+				'event_espresso') . '" />';
745
+		$args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746
+		$args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
748
+	}
749 749
     
750 750
     
751
-    public function load_scripts_styles()
752
-    {
753
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754
-        wp_enqueue_style('espresso_ee_msg');
751
+	public function load_scripts_styles()
752
+	{
753
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754
+		wp_enqueue_style('espresso_ee_msg');
755 755
         
756
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
757
-            array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
759
-            array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760
-    }
756
+		wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
757
+			array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
+		wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
759
+			array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760
+	}
761 761
     
762 762
     
763
-    public function load_scripts_styles_default()
764
-    {
765
-        wp_enqueue_script('ee-msg-list-table-js');
766
-    }
763
+	public function load_scripts_styles_default()
764
+	{
765
+		wp_enqueue_script('ee-msg-list-table-js');
766
+	}
767 767
     
768 768
     
769
-    public function wp_editor_css($mce_css)
770
-    {
771
-        //if we're on the edit_message_template route
772
-        if ($this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
773
-            $message_type_name = $this->_active_message_type_name;
769
+	public function wp_editor_css($mce_css)
770
+	{
771
+		//if we're on the edit_message_template route
772
+		if ($this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
773
+			$message_type_name = $this->_active_message_type_name;
774 774
             
775
-            //we're going to REPLACE the existing mce css
776
-            //we need to get the css file location from the active messenger
777
-            $mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
778
-                'wpeditor', $this->_variation);
779
-        }
775
+			//we're going to REPLACE the existing mce css
776
+			//we need to get the css file location from the active messenger
777
+			$mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
778
+				'wpeditor', $this->_variation);
779
+		}
780 780
         
781
-        return $mce_css;
782
-    }
783
-    
784
-    
785
-    public function load_scripts_styles_edit_message_template()
786
-    {
787
-        
788
-        $this->_set_shortcodes();
781
+		return $mce_css;
782
+	}
783
+    
784
+    
785
+	public function load_scripts_styles_edit_message_template()
786
+	{
787
+        
788
+		$this->_set_shortcodes();
789 789
         
790
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
791
-            __('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
792
-                'event_espresso'),
793
-            $this->_message_template_group->messenger_obj()->label['singular'],
794
-            $this->_message_template_group->message_type_obj()->label['singular']
795
-        );
796
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
797
-            'event_espresso');
798
-        
799
-        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
800
-            EVENT_ESPRESSO_VERSION);
801
-        
802
-        wp_enqueue_script('ee_admin_js');
803
-        wp_enqueue_script('ee_msgs_edit_js');
804
-        
805
-        //add in special css for tiny_mce
806
-        add_filter('mce_css', array($this, 'wp_editor_css'));
807
-    }
808
-    
809
-    
810
-    public function load_scripts_styles_display_preview_message()
811
-    {
812
-        
813
-        $this->_set_message_template_group();
814
-        
815
-        if (isset($this->_req_data['messenger'])) {
816
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
817
-        }
818
-        
819
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
820
-        
821
-        
822
-        wp_enqueue_style('espresso_preview_css',
823
-            $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'preview',
824
-                $this->_variation));
825
-    }
826
-    
827
-    
828
-    public function load_scripts_styles_settings()
829
-    {
830
-        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
831
-            EVENT_ESPRESSO_VERSION);
832
-        wp_enqueue_style('ee-text-links');
833
-        wp_enqueue_style('ee-message-settings');
834
-        
835
-        wp_enqueue_script('ee-messages-settings');
836
-    }
837
-    
838
-    
839
-    /**
840
-     * set views array for List Table
841
-     */
842
-    public function _set_list_table_views_global_mtps()
843
-    {
844
-        $this->_views = array(
845
-            'in_use' => array(
846
-                'slug'        => 'in_use',
847
-                'label'       => __('In Use', 'event_espresso'),
848
-                'count'       => 0,
849
-                'bulk_action' => array(
850
-                    'trash_message_template' => __('Move to Trash', 'event_espresso')
851
-                )
852
-            )
853
-        );
854
-    }
855
-    
856
-    
857
-    /**
858
-     * set views array for message queue list table
859
-     */
860
-    public function _set_list_table_views_default()
861
-    {
862
-        EE_Registry::instance()->load_helper('Template');
863
-        
864
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can('ee_send_message',
865
-            'message_list_table_bulk_actions')
866
-            ? array(
867
-                'generate_now'          => __('Generate Now', 'event_espresso'),
868
-                'generate_and_send_now' => __('Generate and Send Now', 'event_espresso'),
869
-                'queue_for_resending'   => __('Queue for Resending', 'event_espresso'),
870
-                'send_now'              => __('Send Now', 'event_espresso')
871
-            )
872
-            : array();
873
-        
874
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can('ee_delete_messages',
875
-            'message_list_table_bulk_actions')
876
-            ? array('delete_ee_messages' => __('Delete Messages', 'event_espresso'))
877
-            : array();
878
-        
879
-        
880
-        $this->_views = array(
881
-            'all' => array(
882
-                'slug'        => 'all',
883
-                'label'       => __('All', 'event_espresso'),
884
-                'count'       => 0,
885
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
886
-            )
887
-        );
888
-        
889
-        
890
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
891
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
892
-                continue;
893
-            }
894
-            $status_bulk_actions = $common_bulk_actions;
895
-            //unset bulk actions not applying to status
896
-            if (! empty($status_bulk_actions)) {
897
-                switch ($status) {
898
-                    case EEM_Message::status_idle:
899
-                    case EEM_Message::status_resend:
900
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
901
-                        break;
790
+		EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
791
+			__('Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
792
+				'event_espresso'),
793
+			$this->_message_template_group->messenger_obj()->label['singular'],
794
+			$this->_message_template_group->message_type_obj()->label['singular']
795
+		);
796
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
797
+			'event_espresso');
798
+        
799
+		wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
800
+			EVENT_ESPRESSO_VERSION);
801
+        
802
+		wp_enqueue_script('ee_admin_js');
803
+		wp_enqueue_script('ee_msgs_edit_js');
804
+        
805
+		//add in special css for tiny_mce
806
+		add_filter('mce_css', array($this, 'wp_editor_css'));
807
+	}
808
+    
809
+    
810
+	public function load_scripts_styles_display_preview_message()
811
+	{
812
+        
813
+		$this->_set_message_template_group();
814
+        
815
+		if (isset($this->_req_data['messenger'])) {
816
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
817
+		}
818
+        
819
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
820
+        
821
+        
822
+		wp_enqueue_style('espresso_preview_css',
823
+			$this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'preview',
824
+				$this->_variation));
825
+	}
826
+    
827
+    
828
+	public function load_scripts_styles_settings()
829
+	{
830
+		wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
831
+			EVENT_ESPRESSO_VERSION);
832
+		wp_enqueue_style('ee-text-links');
833
+		wp_enqueue_style('ee-message-settings');
834
+        
835
+		wp_enqueue_script('ee-messages-settings');
836
+	}
837
+    
838
+    
839
+	/**
840
+	 * set views array for List Table
841
+	 */
842
+	public function _set_list_table_views_global_mtps()
843
+	{
844
+		$this->_views = array(
845
+			'in_use' => array(
846
+				'slug'        => 'in_use',
847
+				'label'       => __('In Use', 'event_espresso'),
848
+				'count'       => 0,
849
+				'bulk_action' => array(
850
+					'trash_message_template' => __('Move to Trash', 'event_espresso')
851
+				)
852
+			)
853
+		);
854
+	}
855
+    
856
+    
857
+	/**
858
+	 * set views array for message queue list table
859
+	 */
860
+	public function _set_list_table_views_default()
861
+	{
862
+		EE_Registry::instance()->load_helper('Template');
863
+        
864
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can('ee_send_message',
865
+			'message_list_table_bulk_actions')
866
+			? array(
867
+				'generate_now'          => __('Generate Now', 'event_espresso'),
868
+				'generate_and_send_now' => __('Generate and Send Now', 'event_espresso'),
869
+				'queue_for_resending'   => __('Queue for Resending', 'event_espresso'),
870
+				'send_now'              => __('Send Now', 'event_espresso')
871
+			)
872
+			: array();
873
+        
874
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can('ee_delete_messages',
875
+			'message_list_table_bulk_actions')
876
+			? array('delete_ee_messages' => __('Delete Messages', 'event_espresso'))
877
+			: array();
878
+        
879
+        
880
+		$this->_views = array(
881
+			'all' => array(
882
+				'slug'        => 'all',
883
+				'label'       => __('All', 'event_espresso'),
884
+				'count'       => 0,
885
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
886
+			)
887
+		);
888
+        
889
+        
890
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
891
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
892
+				continue;
893
+			}
894
+			$status_bulk_actions = $common_bulk_actions;
895
+			//unset bulk actions not applying to status
896
+			if (! empty($status_bulk_actions)) {
897
+				switch ($status) {
898
+					case EEM_Message::status_idle:
899
+					case EEM_Message::status_resend:
900
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
901
+						break;
902 902
                     
903
-                    case EEM_Message::status_failed:
904
-                    case EEM_Message::status_debug_only:
905
-                    case EEM_Message::status_messenger_executing:
906
-                        $status_bulk_actions = array();
907
-                        break;
903
+					case EEM_Message::status_failed:
904
+					case EEM_Message::status_debug_only:
905
+					case EEM_Message::status_messenger_executing:
906
+						$status_bulk_actions = array();
907
+						break;
908 908
                     
909
-                    case EEM_Message::status_incomplete:
910
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
911
-                        break;
909
+					case EEM_Message::status_incomplete:
910
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
911
+						break;
912 912
                     
913
-                    case EEM_Message::status_retry:
914
-                    case EEM_Message::status_sent:
915
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
916
-                        break;
917
-                }
918
-            }
913
+					case EEM_Message::status_retry:
914
+					case EEM_Message::status_sent:
915
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
916
+						break;
917
+				}
918
+			}
919 919
 
920
-            //skip adding messenger executing status to views because it will be included with the Failed view.
921
-            if ( $status === EEM_Message::status_messenger_executing ) {
922
-                continue;
923
-            }
920
+			//skip adding messenger executing status to views because it will be included with the Failed view.
921
+			if ( $status === EEM_Message::status_messenger_executing ) {
922
+				continue;
923
+			}
924 924
             
925
-            $this->_views[strtolower($status)] = array(
926
-                'slug'        => strtolower($status),
927
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
928
-                'count'       => 0,
929
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
930
-            );
931
-        }
932
-    }
933
-    
934
-    
935
-    protected function _ee_default_messages_overview_list_table()
936
-    {
937
-        $this->_admin_page_title = __('Default Message Templates', 'event_espresso');
938
-        $this->display_admin_list_table_page_with_no_sidebar();
939
-    }
940
-    
941
-    
942
-    protected function _message_queue_list_table()
943
-    {
944
-        $this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945
-        $this->_template_args['per_column']        = 6;
946
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
-        $this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
948
-        $this->display_admin_list_table_page_with_no_sidebar();
949
-    }
950
-    
951
-    
952
-    protected function _message_legend_items()
953
-    {
954
-        
955
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
956
-        $action_items       = array();
957
-        
958
-        foreach ($action_css_classes as $action_item => $action_details) {
959
-            if ($action_item === 'see_notifications_for') {
960
-                continue;
961
-            }
962
-            $action_items[$action_item] = array(
963
-                'class' => $action_details['css_class'],
964
-                'desc'  => $action_details['label']
965
-            );
966
-        }
967
-        
968
-        /** @type array $status_items status legend setup */
969
-        $status_items = array(
970
-            'sent_status'       => array(
971
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
972
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973
-            ),
974
-            'idle_status'       => array(
975
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
976
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977
-            ),
978
-            'failed_status'     => array(
979
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
980
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981
-            ),
982
-            'messenger_executing_status' => array(
983
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
984
-                'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985
-            ),
986
-            'resend_status'     => array(
987
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
988
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989
-            ),
990
-            'incomplete_status' => array(
991
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
992
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993
-            ),
994
-            'retry_status'      => array(
995
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
996
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997
-            )
998
-        );
999
-        if (EEM_Message::debug()) {
1000
-            $status_items['debug_only_status'] = array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1002
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003
-            );
1004
-        }
1005
-        
1006
-        return array_merge($action_items, $status_items);
1007
-    }
1008
-    
1009
-    
1010
-    protected function _custom_mtps_preview()
1011
-    {
1012
-        $this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
-                'event_espresso') . '" />';
1015
-        $this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1016
-                'event_espresso') . '</strong>';
1017
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1018
-    }
1019
-    
1020
-    
1021
-    /**
1022
-     * get_message_templates
1023
-     * This gets all the message templates for listing on the overview list.
1024
-     *
1025
-     * @access public
1026
-     *
1027
-     * @param int    $perpage the amount of templates groups to show per page
1028
-     * @param string $type    the current _view we're getting templates for
1029
-     * @param bool   $count   return count?
1030
-     * @param bool   $all     disregard any paging info (get all data);
1031
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1032
-     *
1033
-     * @return array
1034
-     */
1035
-    public function get_message_templates($perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true)
1036
-    {
1037
-        
1038
-        $MTP = EEM_Message_Template_Group::instance();
1039
-        
1040
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1041
-        $orderby                    = $this->_req_data['orderby'];
1042
-        
1043
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1044
-        
1045
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1046
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $perpage;
1047
-        
1048
-        $offset = ($current_page - 1) * $per_page;
1049
-        $limit  = $all ? null : array($offset, $per_page);
1050
-        
1051
-        
1052
-        //options will match what is in the _views array property
1053
-        switch ($type) {
925
+			$this->_views[strtolower($status)] = array(
926
+				'slug'        => strtolower($status),
927
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
928
+				'count'       => 0,
929
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
930
+			);
931
+		}
932
+	}
933
+    
934
+    
935
+	protected function _ee_default_messages_overview_list_table()
936
+	{
937
+		$this->_admin_page_title = __('Default Message Templates', 'event_espresso');
938
+		$this->display_admin_list_table_page_with_no_sidebar();
939
+	}
940
+    
941
+    
942
+	protected function _message_queue_list_table()
943
+	{
944
+		$this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945
+		$this->_template_args['per_column']        = 6;
946
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
+		$this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
948
+		$this->display_admin_list_table_page_with_no_sidebar();
949
+	}
950
+    
951
+    
952
+	protected function _message_legend_items()
953
+	{
954
+        
955
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
956
+		$action_items       = array();
957
+        
958
+		foreach ($action_css_classes as $action_item => $action_details) {
959
+			if ($action_item === 'see_notifications_for') {
960
+				continue;
961
+			}
962
+			$action_items[$action_item] = array(
963
+				'class' => $action_details['css_class'],
964
+				'desc'  => $action_details['label']
965
+			);
966
+		}
967
+        
968
+		/** @type array $status_items status legend setup */
969
+		$status_items = array(
970
+			'sent_status'       => array(
971
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
972
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973
+			),
974
+			'idle_status'       => array(
975
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
976
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977
+			),
978
+			'failed_status'     => array(
979
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
980
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981
+			),
982
+			'messenger_executing_status' => array(
983
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
984
+				'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985
+			),
986
+			'resend_status'     => array(
987
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
988
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989
+			),
990
+			'incomplete_status' => array(
991
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
992
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993
+			),
994
+			'retry_status'      => array(
995
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
996
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997
+			)
998
+		);
999
+		if (EEM_Message::debug()) {
1000
+			$status_items['debug_only_status'] = array(
1001
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1002
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003
+			);
1004
+		}
1005
+        
1006
+		return array_merge($action_items, $status_items);
1007
+	}
1008
+    
1009
+    
1010
+	protected function _custom_mtps_preview()
1011
+	{
1012
+		$this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
+		$this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
+				'event_espresso') . '" />';
1015
+		$this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1016
+				'event_espresso') . '</strong>';
1017
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1018
+	}
1019
+    
1020
+    
1021
+	/**
1022
+	 * get_message_templates
1023
+	 * This gets all the message templates for listing on the overview list.
1024
+	 *
1025
+	 * @access public
1026
+	 *
1027
+	 * @param int    $perpage the amount of templates groups to show per page
1028
+	 * @param string $type    the current _view we're getting templates for
1029
+	 * @param bool   $count   return count?
1030
+	 * @param bool   $all     disregard any paging info (get all data);
1031
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1032
+	 *
1033
+	 * @return array
1034
+	 */
1035
+	public function get_message_templates($perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true)
1036
+	{
1037
+        
1038
+		$MTP = EEM_Message_Template_Group::instance();
1039
+        
1040
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1041
+		$orderby                    = $this->_req_data['orderby'];
1042
+        
1043
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1044
+        
1045
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1046
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $perpage;
1047
+        
1048
+		$offset = ($current_page - 1) * $per_page;
1049
+		$limit  = $all ? null : array($offset, $per_page);
1050
+        
1051
+        
1052
+		//options will match what is in the _views array property
1053
+		switch ($type) {
1054 1054
             
1055
-            case 'in_use':
1056
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1057
-                break;
1055
+			case 'in_use':
1056
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1057
+				break;
1058 1058
             
1059
-            default:
1060
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1059
+			default:
1060
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1061 1061
             
1062
-        }
1063
-        
1064
-        return $templates;
1065
-    }
1066
-    
1067
-    
1068
-    /**
1069
-     * filters etc might need a list of installed message_types
1070
-     * @return array an array of message type objects
1071
-     */
1072
-    public function get_installed_message_types()
1073
-    {
1074
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1075
-        $installed               = array();
1076
-        
1077
-        foreach ($installed_message_types as $message_type) {
1078
-            $installed[$message_type->name] = $message_type;
1079
-        }
1080
-        
1081
-        return $installed;
1082
-    }
1083
-    
1084
-    
1085
-    /**
1086
-     * _add_message_template
1087
-     *
1088
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1089
-     *
1090
-     * @param string $message_type
1091
-     * @param string $messenger
1092
-     * @param string $GRP_ID
1093
-     *
1094
-     * @throws EE_error
1095
-     */
1096
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1097
-    {
1098
-        //set values override any request data
1099
-        $message_type = ! empty($message_type) ? $message_type : '';
1100
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type']) ? $this->_req_data['message_type'] : $message_type;
1101
-        
1102
-        $messenger = ! empty($messenger) ? $messenger : '';
1103
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger']) ? $this->_req_data['messenger'] : $messenger;
1104
-        
1105
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1106
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1107
-        
1108
-        //we need messenger and message type.  They should be coming from the event editor. If not here then return error
1109
-        if (empty($message_type) || empty($messenger)) {
1110
-            throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1111
-                'event_espresso'));
1112
-        }
1113
-        
1114
-        //we need the GRP_ID for the template being used as the base for the new template
1115
-        if (empty($GRP_ID)) {
1116
-            throw new EE_Error(__('In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1117
-                'event_espresso'));
1118
-        }
1119
-        
1120
-        //let's just make sure the template gets generated!
1121
-        
1122
-        //we need to reassign some variables for what the insert is expecting
1123
-        $this->_req_data['MTP_messenger']    = $messenger;
1124
-        $this->_req_data['MTP_message_type'] = $message_type;
1125
-        $this->_req_data['GRP_ID']           = $GRP_ID;
1126
-        $this->_insert_or_update_message_template(true);
1127
-    }
1128
-    
1129
-    
1130
-    /**
1131
-     * public wrapper for the _add_message_template method
1132
-     *
1133
-     * @param string $message_type     message type slug
1134
-     * @param string $messenger        messenger slug
1135
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1136
-     *                                 off of.
1137
-     */
1138
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1139
-    {
1140
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1141
-    }
1142
-    
1143
-    
1144
-    /**
1145
-     * _edit_message_template
1146
-     *
1147
-     * @access protected
1148
-     * @return void
1149
-     */
1150
-    protected function _edit_message_template()
1151
-    {
1152
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1153
-        $template_fields = '';
1154
-        $sidebar_fields  = '';
1155
-        //we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1156
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1157
-        
1158
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1159
-            ? absint($this->_req_data['id'])
1160
-            : false;
1161
-        
1162
-        $this->_set_shortcodes(); //this also sets the _message_template property.
1163
-        $message_template_group = $this->_message_template_group;
1164
-        $c_label                = $message_template_group->context_label();
1165
-        $c_config               = $message_template_group->contexts_config();
1166
-        
1167
-        reset($c_config);
1168
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1169
-            ? strtolower($this->_req_data['context'])
1170
-            : key($c_config);
1171
-        
1172
-        
1173
-        if (empty($GRP_ID)) {
1174
-            $action = 'insert_message_template';
1175
-            //$button_both = false;
1176
-            //$button_text = array( __( 'Save','event_espresso') );
1177
-            //$button_actions = array('something_different');
1178
-            //$referrer = false;
1179
-            $edit_message_template_form_url = add_query_arg(
1180
-                array('action' => $action, 'noheader' => true),
1181
-                EE_MSG_ADMIN_URL
1182
-            );
1183
-        } else {
1184
-            $action = 'update_message_template';
1185
-            //$button_both = true;
1186
-            //$button_text = array();
1187
-            //$button_actions = array();
1188
-            //$referrer = $this->_admin_base_url;
1189
-            $edit_message_template_form_url = add_query_arg(
1190
-                array('action' => $action, 'noheader' => true),
1191
-                EE_MSG_ADMIN_URL
1192
-            );
1193
-        }
1194
-        
1195
-        //set active messenger for this view
1196
-        $this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1197
-            $message_template_group->messenger()
1198
-        );
1199
-        $this->_active_message_type_name = $message_template_group->message_type();
1200
-        
1201
-        
1202
-        //Do we have any validation errors?
1203
-        $validators = $this->_get_transient();
1204
-        $v_fields   = ! empty($validators) ? array_keys($validators) : array();
1205
-        
1206
-        
1207
-        //we need to assemble the title from Various details
1208
-        $context_label = sprintf(
1209
-            __('(%s %s)', 'event_espresso'),
1210
-            $c_config[$context]['label'],
1211
-            ucwords($c_label['label'])
1212
-        );
1213
-        
1214
-        $title = sprintf(
1215
-            __(' %s %s Template %s', 'event_espresso'),
1216
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1217
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1218
-            $context_label
1219
-        );
1220
-        
1221
-        $this->_template_args['GRP_ID']           = $GRP_ID;
1222
-        $this->_template_args['message_template'] = $message_template_group;
1223
-        $this->_template_args['is_extra_fields']  = false;
1224
-        
1225
-        
1226
-        //let's get EEH_MSG_Template so we can get template form fields
1227
-        $template_field_structure = EEH_MSG_Template::get_fields(
1228
-            $message_template_group->messenger(),
1229
-            $message_template_group->message_type()
1230
-        );
1231
-        
1232
-        if ( ! $template_field_structure) {
1233
-            $template_field_structure = false;
1234
-            $template_fields          = __('There was an error in assembling the fields for this display (you should see an error message)',
1235
-                'event_espresso');
1236
-        }
1237
-        
1238
-        
1239
-        $message_templates = $message_template_group->context_templates();
1240
-        
1241
-        
1242
-        //if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1243
-        if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1244
-            foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1245
-                unset($template_field_structure[$context][$reference_field]);
1246
-            }
1247
-        }
1248
-        
1249
-        //let's loop through the template_field_structure and actually assemble the input fields!
1250
-        if ( ! empty($template_field_structure)) {
1251
-            foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1252
-                //if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1253
-                if ($template_field == 'extra') {
1254
-                    $this->_template_args['is_extra_fields'] = true;
1255
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1256
-                        $message_template = $message_templates[$context][$reference_field];
1257
-                        $content          = $message_template instanceof EE_Message_Template
1258
-                            ? $message_template->get('MTP_content')
1259
-                            : '';
1260
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1261
-                            //let's verify if we need this extra field via the shortcodes parameter.
1262
-                            $continue = false;
1263
-                            if (isset($extra_array['shortcodes_required'])) {
1264
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1265
-                                    if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266
-                                        $continue = true;
1267
-                                    }
1268
-                                }
1269
-                                if ($continue) {
1270
-                                    continue;
1271
-                                }
1272
-                            }
1062
+		}
1063
+        
1064
+		return $templates;
1065
+	}
1066
+    
1067
+    
1068
+	/**
1069
+	 * filters etc might need a list of installed message_types
1070
+	 * @return array an array of message type objects
1071
+	 */
1072
+	public function get_installed_message_types()
1073
+	{
1074
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1075
+		$installed               = array();
1076
+        
1077
+		foreach ($installed_message_types as $message_type) {
1078
+			$installed[$message_type->name] = $message_type;
1079
+		}
1080
+        
1081
+		return $installed;
1082
+	}
1083
+    
1084
+    
1085
+	/**
1086
+	 * _add_message_template
1087
+	 *
1088
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1089
+	 *
1090
+	 * @param string $message_type
1091
+	 * @param string $messenger
1092
+	 * @param string $GRP_ID
1093
+	 *
1094
+	 * @throws EE_error
1095
+	 */
1096
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1097
+	{
1098
+		//set values override any request data
1099
+		$message_type = ! empty($message_type) ? $message_type : '';
1100
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type']) ? $this->_req_data['message_type'] : $message_type;
1101
+        
1102
+		$messenger = ! empty($messenger) ? $messenger : '';
1103
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger']) ? $this->_req_data['messenger'] : $messenger;
1104
+        
1105
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1106
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1107
+        
1108
+		//we need messenger and message type.  They should be coming from the event editor. If not here then return error
1109
+		if (empty($message_type) || empty($messenger)) {
1110
+			throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1111
+				'event_espresso'));
1112
+		}
1113
+        
1114
+		//we need the GRP_ID for the template being used as the base for the new template
1115
+		if (empty($GRP_ID)) {
1116
+			throw new EE_Error(__('In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1117
+				'event_espresso'));
1118
+		}
1119
+        
1120
+		//let's just make sure the template gets generated!
1121
+        
1122
+		//we need to reassign some variables for what the insert is expecting
1123
+		$this->_req_data['MTP_messenger']    = $messenger;
1124
+		$this->_req_data['MTP_message_type'] = $message_type;
1125
+		$this->_req_data['GRP_ID']           = $GRP_ID;
1126
+		$this->_insert_or_update_message_template(true);
1127
+	}
1128
+    
1129
+    
1130
+	/**
1131
+	 * public wrapper for the _add_message_template method
1132
+	 *
1133
+	 * @param string $message_type     message type slug
1134
+	 * @param string $messenger        messenger slug
1135
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1136
+	 *                                 off of.
1137
+	 */
1138
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1139
+	{
1140
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1141
+	}
1142
+    
1143
+    
1144
+	/**
1145
+	 * _edit_message_template
1146
+	 *
1147
+	 * @access protected
1148
+	 * @return void
1149
+	 */
1150
+	protected function _edit_message_template()
1151
+	{
1152
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1153
+		$template_fields = '';
1154
+		$sidebar_fields  = '';
1155
+		//we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1156
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1157
+        
1158
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1159
+			? absint($this->_req_data['id'])
1160
+			: false;
1161
+        
1162
+		$this->_set_shortcodes(); //this also sets the _message_template property.
1163
+		$message_template_group = $this->_message_template_group;
1164
+		$c_label                = $message_template_group->context_label();
1165
+		$c_config               = $message_template_group->contexts_config();
1166
+        
1167
+		reset($c_config);
1168
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1169
+			? strtolower($this->_req_data['context'])
1170
+			: key($c_config);
1171
+        
1172
+        
1173
+		if (empty($GRP_ID)) {
1174
+			$action = 'insert_message_template';
1175
+			//$button_both = false;
1176
+			//$button_text = array( __( 'Save','event_espresso') );
1177
+			//$button_actions = array('something_different');
1178
+			//$referrer = false;
1179
+			$edit_message_template_form_url = add_query_arg(
1180
+				array('action' => $action, 'noheader' => true),
1181
+				EE_MSG_ADMIN_URL
1182
+			);
1183
+		} else {
1184
+			$action = 'update_message_template';
1185
+			//$button_both = true;
1186
+			//$button_text = array();
1187
+			//$button_actions = array();
1188
+			//$referrer = $this->_admin_base_url;
1189
+			$edit_message_template_form_url = add_query_arg(
1190
+				array('action' => $action, 'noheader' => true),
1191
+				EE_MSG_ADMIN_URL
1192
+			);
1193
+		}
1194
+        
1195
+		//set active messenger for this view
1196
+		$this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1197
+			$message_template_group->messenger()
1198
+		);
1199
+		$this->_active_message_type_name = $message_template_group->message_type();
1200
+        
1201
+        
1202
+		//Do we have any validation errors?
1203
+		$validators = $this->_get_transient();
1204
+		$v_fields   = ! empty($validators) ? array_keys($validators) : array();
1205
+        
1206
+        
1207
+		//we need to assemble the title from Various details
1208
+		$context_label = sprintf(
1209
+			__('(%s %s)', 'event_espresso'),
1210
+			$c_config[$context]['label'],
1211
+			ucwords($c_label['label'])
1212
+		);
1213
+        
1214
+		$title = sprintf(
1215
+			__(' %s %s Template %s', 'event_espresso'),
1216
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1217
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1218
+			$context_label
1219
+		);
1220
+        
1221
+		$this->_template_args['GRP_ID']           = $GRP_ID;
1222
+		$this->_template_args['message_template'] = $message_template_group;
1223
+		$this->_template_args['is_extra_fields']  = false;
1224
+        
1225
+        
1226
+		//let's get EEH_MSG_Template so we can get template form fields
1227
+		$template_field_structure = EEH_MSG_Template::get_fields(
1228
+			$message_template_group->messenger(),
1229
+			$message_template_group->message_type()
1230
+		);
1231
+        
1232
+		if ( ! $template_field_structure) {
1233
+			$template_field_structure = false;
1234
+			$template_fields          = __('There was an error in assembling the fields for this display (you should see an error message)',
1235
+				'event_espresso');
1236
+		}
1237
+        
1238
+        
1239
+		$message_templates = $message_template_group->context_templates();
1240
+        
1241
+        
1242
+		//if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1243
+		if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1244
+			foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1245
+				unset($template_field_structure[$context][$reference_field]);
1246
+			}
1247
+		}
1248
+        
1249
+		//let's loop through the template_field_structure and actually assemble the input fields!
1250
+		if ( ! empty($template_field_structure)) {
1251
+			foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1252
+				//if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1253
+				if ($template_field == 'extra') {
1254
+					$this->_template_args['is_extra_fields'] = true;
1255
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1256
+						$message_template = $message_templates[$context][$reference_field];
1257
+						$content          = $message_template instanceof EE_Message_Template
1258
+							? $message_template->get('MTP_content')
1259
+							: '';
1260
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1261
+							//let's verify if we need this extra field via the shortcodes parameter.
1262
+							$continue = false;
1263
+							if (isset($extra_array['shortcodes_required'])) {
1264
+								foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1265
+									if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266
+										$continue = true;
1267
+									}
1268
+								}
1269
+								if ($continue) {
1270
+									continue;
1271
+								}
1272
+							}
1273 1273
                             
1274
-                            $field_id                                = $reference_field . '-' . $extra_field . '-content';
1275
-                            $template_form_fields[$field_id]         = $extra_array;
1276
-                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1277
-                            $css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1274
+							$field_id                                = $reference_field . '-' . $extra_field . '-content';
1275
+							$template_form_fields[$field_id]         = $extra_array;
1276
+							$template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1277
+							$css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1278 1278
                             
1279
-                            $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1280
-                                                                            && in_array($extra_field, $v_fields)
1281
-                                                                            &&
1282
-                                                                            (
1283
-                                                                                is_array($validators[$extra_field])
1284
-                                                                                && isset($validators[$extra_field]['msg'])
1285
-                                                                            )
1286
-                                ? 'validate-error ' . $css_class
1287
-                                : $css_class;
1279
+							$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1280
+																			&& in_array($extra_field, $v_fields)
1281
+																			&&
1282
+																			(
1283
+																				is_array($validators[$extra_field])
1284
+																				&& isset($validators[$extra_field]['msg'])
1285
+																			)
1286
+								? 'validate-error ' . $css_class
1287
+								: $css_class;
1288 1288
                             
1289
-                            $template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
1290
-                                ? stripslashes(html_entity_decode($content[$extra_field], ENT_QUOTES, "UTF-8"))
1291
-                                : '';
1289
+							$template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
1290
+								? stripslashes(html_entity_decode($content[$extra_field], ENT_QUOTES, "UTF-8"))
1291
+								: '';
1292 1292
                             
1293
-                            //do we have a validation error?  if we do then let's use that value instead
1294
-                            $template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1293
+							//do we have a validation error?  if we do then let's use that value instead
1294
+							$template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1295 1295
                             
1296 1296
                             
1297
-                            $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1297
+							$template_form_fields[$field_id]['db-col'] = 'MTP_content';
1298 1298
                             
1299
-                            //shortcode selector
1300
-                            $field_name_to_use                                 = $extra_field == 'main' ? 'content' : $extra_field;
1301
-                            $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1302
-                                $field_name_to_use,
1303
-                                $field_id
1304
-                            );
1299
+							//shortcode selector
1300
+							$field_name_to_use                                 = $extra_field == 'main' ? 'content' : $extra_field;
1301
+							$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1302
+								$field_name_to_use,
1303
+								$field_id
1304
+							);
1305 1305
                             
1306
-                            if (isset($extra_array['input']) && $extra_array['input'] == 'wp_editor') {
1307
-                                //we want to decode the entities
1308
-                                $template_form_fields[$field_id]['value'] = stripslashes(
1309
-                                    html_entity_decode($template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1310
-                                );
1306
+							if (isset($extra_array['input']) && $extra_array['input'] == 'wp_editor') {
1307
+								//we want to decode the entities
1308
+								$template_form_fields[$field_id]['value'] = stripslashes(
1309
+									html_entity_decode($template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1310
+								);
1311 1311
                                 
1312
-                            }/**/
1313
-                        }
1314
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
-                        $templatefield_templatename_id = $reference_field . '-name';
1312
+							}/**/
1313
+						}
1314
+						$templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
+						$templatefield_templatename_id = $reference_field . '-name';
1316 1316
                         
1317
-                        $template_form_fields[$templatefield_MTP_id] = array(
1318
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1319
-                            'label'      => null,
1320
-                            'input'      => 'hidden',
1321
-                            'type'       => 'int',
1322
-                            'required'   => false,
1323
-                            'validation' => false,
1324
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1325
-                            'css_class'  => '',
1326
-                            'format'     => '%d',
1327
-                            'db-col'     => 'MTP_ID'
1328
-                        );
1317
+						$template_form_fields[$templatefield_MTP_id] = array(
1318
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1319
+							'label'      => null,
1320
+							'input'      => 'hidden',
1321
+							'type'       => 'int',
1322
+							'required'   => false,
1323
+							'validation' => false,
1324
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1325
+							'css_class'  => '',
1326
+							'format'     => '%d',
1327
+							'db-col'     => 'MTP_ID'
1328
+						);
1329 1329
                         
1330
-                        $template_form_fields[$templatefield_templatename_id] = array(
1331
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1332
-                            'label'      => null,
1333
-                            'input'      => 'hidden',
1334
-                            'type'       => 'string',
1335
-                            'required'   => false,
1336
-                            'validation' => true,
1337
-                            'value'      => $reference_field,
1338
-                            'css_class'  => '',
1339
-                            'format'     => '%s',
1340
-                            'db-col'     => 'MTP_template_field'
1341
-                        );
1342
-                    }
1343
-                    continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344
-                } else {
1345
-                    $field_id                                 = $template_field . '-content';
1346
-                    $template_form_fields[$field_id]          = $field_setup_array;
1347
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1348
-                    $message_template                         = isset($message_templates[$context][$template_field])
1349
-                        ? $message_templates[$context][$template_field]
1350
-                        : null;
1351
-                    $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1352
-                                                                && is_array($message_templates[$context])
1353
-                                                                && $message_template instanceof EE_Message_Template
1354
-                        ? $message_template->get('MTP_content')
1355
-                        : '';
1330
+						$template_form_fields[$templatefield_templatename_id] = array(
1331
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1332
+							'label'      => null,
1333
+							'input'      => 'hidden',
1334
+							'type'       => 'string',
1335
+							'required'   => false,
1336
+							'validation' => true,
1337
+							'value'      => $reference_field,
1338
+							'css_class'  => '',
1339
+							'format'     => '%s',
1340
+							'db-col'     => 'MTP_template_field'
1341
+						);
1342
+					}
1343
+					continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344
+				} else {
1345
+					$field_id                                 = $template_field . '-content';
1346
+					$template_form_fields[$field_id]          = $field_setup_array;
1347
+					$template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1348
+					$message_template                         = isset($message_templates[$context][$template_field])
1349
+						? $message_templates[$context][$template_field]
1350
+						: null;
1351
+					$template_form_fields[$field_id]['value'] = ! empty($message_templates)
1352
+																&& is_array($message_templates[$context])
1353
+																&& $message_template instanceof EE_Message_Template
1354
+						? $message_template->get('MTP_content')
1355
+						: '';
1356 1356
                     
1357
-                    //do we have a validator error for this field?  if we do then we'll use that value instead
1358
-                    $template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1359
-                        ? $validators[$template_field]['value']
1360
-                        : $template_form_fields[$field_id]['value'];
1357
+					//do we have a validator error for this field?  if we do then we'll use that value instead
1358
+					$template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1359
+						? $validators[$template_field]['value']
1360
+						: $template_form_fields[$field_id]['value'];
1361 1361
                     
1362 1362
                     
1363
-                    $template_form_fields[$field_id]['db-col']    = 'MTP_content';
1364
-                    $css_class                                    = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1365
-                    $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366
-                                                                    && in_array($template_field, $v_fields)
1367
-                                                                    && isset($validators[$template_field]['msg'])
1368
-                        ? 'validate-error ' . $css_class
1369
-                        : $css_class;
1363
+					$template_form_fields[$field_id]['db-col']    = 'MTP_content';
1364
+					$css_class                                    = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1365
+					$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366
+																	&& in_array($template_field, $v_fields)
1367
+																	&& isset($validators[$template_field]['msg'])
1368
+						? 'validate-error ' . $css_class
1369
+						: $css_class;
1370 1370
                     
1371
-                    //shortcode selector
1372
-                    $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1373
-                        $template_field, $field_id
1374
-                    );
1375
-                }
1371
+					//shortcode selector
1372
+					$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1373
+						$template_field, $field_id
1374
+					);
1375
+				}
1376 1376
                 
1377
-                //k took care of content field(s) now let's take care of others.
1377
+				//k took care of content field(s) now let's take care of others.
1378 1378
                 
1379
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
-                $templatefield_field_templatename_id = $template_field . '-name';
1379
+				$templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
+				$templatefield_field_templatename_id = $template_field . '-name';
1381 1381
                 
1382
-                //foreach template field there are actually two form fields created
1383
-                $template_form_fields[$templatefield_MTP_id] = array(
1384
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1385
-                    'label'      => null,
1386
-                    'input'      => 'hidden',
1387
-                    'type'       => 'int',
1388
-                    'required'   => false,
1389
-                    'validation' => true,
1390
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1391
-                    'css_class'  => '',
1392
-                    'format'     => '%d',
1393
-                    'db-col'     => 'MTP_ID'
1394
-                );
1382
+				//foreach template field there are actually two form fields created
1383
+				$template_form_fields[$templatefield_MTP_id] = array(
1384
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1385
+					'label'      => null,
1386
+					'input'      => 'hidden',
1387
+					'type'       => 'int',
1388
+					'required'   => false,
1389
+					'validation' => true,
1390
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1391
+					'css_class'  => '',
1392
+					'format'     => '%d',
1393
+					'db-col'     => 'MTP_ID'
1394
+				);
1395 1395
                 
1396
-                $template_form_fields[$templatefield_field_templatename_id] = array(
1397
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1398
-                    'label'      => null,
1399
-                    'input'      => 'hidden',
1400
-                    'type'       => 'string',
1401
-                    'required'   => false,
1402
-                    'validation' => true,
1403
-                    'value'      => $template_field,
1404
-                    'css_class'  => '',
1405
-                    'format'     => '%s',
1406
-                    'db-col'     => 'MTP_template_field'
1407
-                );
1396
+				$template_form_fields[$templatefield_field_templatename_id] = array(
1397
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1398
+					'label'      => null,
1399
+					'input'      => 'hidden',
1400
+					'type'       => 'string',
1401
+					'required'   => false,
1402
+					'validation' => true,
1403
+					'value'      => $template_field,
1404
+					'css_class'  => '',
1405
+					'format'     => '%s',
1406
+					'db-col'     => 'MTP_template_field'
1407
+				);
1408 1408
                 
1409
-            }
1409
+			}
1410 1410
             
1411
-            //add other fields
1412
-            $template_form_fields['ee-msg-current-context'] = array(
1413
-                'name'       => 'MTP_context',
1414
-                'label'      => null,
1415
-                'input'      => 'hidden',
1416
-                'type'       => 'string',
1417
-                'required'   => false,
1418
-                'validation' => true,
1419
-                'value'      => $context,
1420
-                'css_class'  => '',
1421
-                'format'     => '%s',
1422
-                'db-col'     => 'MTP_context'
1423
-            );
1411
+			//add other fields
1412
+			$template_form_fields['ee-msg-current-context'] = array(
1413
+				'name'       => 'MTP_context',
1414
+				'label'      => null,
1415
+				'input'      => 'hidden',
1416
+				'type'       => 'string',
1417
+				'required'   => false,
1418
+				'validation' => true,
1419
+				'value'      => $context,
1420
+				'css_class'  => '',
1421
+				'format'     => '%s',
1422
+				'db-col'     => 'MTP_context'
1423
+			);
1424 1424
             
1425
-            $template_form_fields['ee-msg-grp-id'] = array(
1426
-                'name'       => 'GRP_ID',
1427
-                'label'      => null,
1428
-                'input'      => 'hidden',
1429
-                'type'       => 'int',
1430
-                'required'   => false,
1431
-                'validation' => true,
1432
-                'value'      => $GRP_ID,
1433
-                'css_class'  => '',
1434
-                'format'     => '%d',
1435
-                'db-col'     => 'GRP_ID'
1436
-            );
1425
+			$template_form_fields['ee-msg-grp-id'] = array(
1426
+				'name'       => 'GRP_ID',
1427
+				'label'      => null,
1428
+				'input'      => 'hidden',
1429
+				'type'       => 'int',
1430
+				'required'   => false,
1431
+				'validation' => true,
1432
+				'value'      => $GRP_ID,
1433
+				'css_class'  => '',
1434
+				'format'     => '%d',
1435
+				'db-col'     => 'GRP_ID'
1436
+			);
1437 1437
             
1438
-            $template_form_fields['ee-msg-messenger'] = array(
1439
-                'name'       => 'MTP_messenger',
1440
-                'label'      => null,
1441
-                'input'      => 'hidden',
1442
-                'type'       => 'string',
1443
-                'required'   => false,
1444
-                'validation' => true,
1445
-                'value'      => $message_template_group->messenger(),
1446
-                'css_class'  => '',
1447
-                'format'     => '%s',
1448
-                'db-col'     => 'MTP_messenger'
1449
-            );
1438
+			$template_form_fields['ee-msg-messenger'] = array(
1439
+				'name'       => 'MTP_messenger',
1440
+				'label'      => null,
1441
+				'input'      => 'hidden',
1442
+				'type'       => 'string',
1443
+				'required'   => false,
1444
+				'validation' => true,
1445
+				'value'      => $message_template_group->messenger(),
1446
+				'css_class'  => '',
1447
+				'format'     => '%s',
1448
+				'db-col'     => 'MTP_messenger'
1449
+			);
1450 1450
             
1451
-            $template_form_fields['ee-msg-message-type'] = array(
1452
-                'name'       => 'MTP_message_type',
1453
-                'label'      => null,
1454
-                'input'      => 'hidden',
1455
-                'type'       => 'string',
1456
-                'required'   => false,
1457
-                'validation' => true,
1458
-                'value'      => $message_template_group->message_type(),
1459
-                'css_class'  => '',
1460
-                'format'     => '%s',
1461
-                'db-col'     => 'MTP_message_type'
1462
-            );
1451
+			$template_form_fields['ee-msg-message-type'] = array(
1452
+				'name'       => 'MTP_message_type',
1453
+				'label'      => null,
1454
+				'input'      => 'hidden',
1455
+				'type'       => 'string',
1456
+				'required'   => false,
1457
+				'validation' => true,
1458
+				'value'      => $message_template_group->message_type(),
1459
+				'css_class'  => '',
1460
+				'format'     => '%s',
1461
+				'db-col'     => 'MTP_message_type'
1462
+			);
1463 1463
             
1464
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1465
-                'name'       => 'MTP_is_global',
1466
-                'label'      => __('Global Template', 'event_espresso'),
1467
-                'input'      => 'hidden',
1468
-                'type'       => 'int',
1469
-                'required'   => false,
1470
-                'validation' => true,
1471
-                'value'      => $message_template_group->get('MTP_is_global'),
1472
-                'css_class'  => '',
1473
-                'format'     => '%d',
1474
-                'db-col'     => 'MTP_is_global'
1475
-            );
1464
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1465
+				'name'       => 'MTP_is_global',
1466
+				'label'      => __('Global Template', 'event_espresso'),
1467
+				'input'      => 'hidden',
1468
+				'type'       => 'int',
1469
+				'required'   => false,
1470
+				'validation' => true,
1471
+				'value'      => $message_template_group->get('MTP_is_global'),
1472
+				'css_class'  => '',
1473
+				'format'     => '%d',
1474
+				'db-col'     => 'MTP_is_global'
1475
+			);
1476 1476
             
1477
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1478
-                'name'       => 'MTP_is_override',
1479
-                'label'      => __('Override all custom', 'event_espresso'),
1480
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1481
-                'type'       => 'int',
1482
-                'required'   => false,
1483
-                'validation' => true,
1484
-                'value'      => $message_template_group->get('MTP_is_override'),
1485
-                'css_class'  => '',
1486
-                'format'     => '%d',
1487
-                'db-col'     => 'MTP_is_override'
1488
-            );
1477
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1478
+				'name'       => 'MTP_is_override',
1479
+				'label'      => __('Override all custom', 'event_espresso'),
1480
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1481
+				'type'       => 'int',
1482
+				'required'   => false,
1483
+				'validation' => true,
1484
+				'value'      => $message_template_group->get('MTP_is_override'),
1485
+				'css_class'  => '',
1486
+				'format'     => '%d',
1487
+				'db-col'     => 'MTP_is_override'
1488
+			);
1489 1489
             
1490
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1491
-                'name'       => 'MTP_is_active',
1492
-                'label'      => __('Active Template', 'event_espresso'),
1493
-                'input'      => 'hidden',
1494
-                'type'       => 'int',
1495
-                'required'   => false,
1496
-                'validation' => true,
1497
-                'value'      => $message_template_group->is_active(),
1498
-                'css_class'  => '',
1499
-                'format'     => '%d',
1500
-                'db-col'     => 'MTP_is_active'
1501
-            );
1490
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1491
+				'name'       => 'MTP_is_active',
1492
+				'label'      => __('Active Template', 'event_espresso'),
1493
+				'input'      => 'hidden',
1494
+				'type'       => 'int',
1495
+				'required'   => false,
1496
+				'validation' => true,
1497
+				'value'      => $message_template_group->is_active(),
1498
+				'css_class'  => '',
1499
+				'format'     => '%d',
1500
+				'db-col'     => 'MTP_is_active'
1501
+			);
1502 1502
             
1503
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1504
-                'name'       => 'MTP_deleted',
1505
-                'label'      => null,
1506
-                'input'      => 'hidden',
1507
-                'type'       => 'int',
1508
-                'required'   => false,
1509
-                'validation' => true,
1510
-                'value'      => $message_template_group->get('MTP_deleted'),
1511
-                'css_class'  => '',
1512
-                'format'     => '%d',
1513
-                'db-col'     => 'MTP_deleted'
1514
-            );
1515
-            $sidebar_form_fields['ee-msg-author']  = array(
1516
-                'name'       => 'MTP_user_id',
1517
-                'label'      => __('Author', 'event_espresso'),
1518
-                'input'      => 'hidden',
1519
-                'type'       => 'int',
1520
-                'required'   => false,
1521
-                'validation' => false,
1522
-                'value'      => $message_template_group->user(),
1523
-                'format'     => '%d',
1524
-                'db-col'     => 'MTP_user_id'
1525
-            );
1503
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1504
+				'name'       => 'MTP_deleted',
1505
+				'label'      => null,
1506
+				'input'      => 'hidden',
1507
+				'type'       => 'int',
1508
+				'required'   => false,
1509
+				'validation' => true,
1510
+				'value'      => $message_template_group->get('MTP_deleted'),
1511
+				'css_class'  => '',
1512
+				'format'     => '%d',
1513
+				'db-col'     => 'MTP_deleted'
1514
+			);
1515
+			$sidebar_form_fields['ee-msg-author']  = array(
1516
+				'name'       => 'MTP_user_id',
1517
+				'label'      => __('Author', 'event_espresso'),
1518
+				'input'      => 'hidden',
1519
+				'type'       => 'int',
1520
+				'required'   => false,
1521
+				'validation' => false,
1522
+				'value'      => $message_template_group->user(),
1523
+				'format'     => '%d',
1524
+				'db-col'     => 'MTP_user_id'
1525
+			);
1526 1526
             
1527
-            $sidebar_form_fields['ee-msg-route'] = array(
1528
-                'name'  => 'action',
1529
-                'input' => 'hidden',
1530
-                'type'  => 'string',
1531
-                'value' => $action
1532
-            );
1527
+			$sidebar_form_fields['ee-msg-route'] = array(
1528
+				'name'  => 'action',
1529
+				'input' => 'hidden',
1530
+				'type'  => 'string',
1531
+				'value' => $action
1532
+			);
1533 1533
             
1534
-            $sidebar_form_fields['ee-msg-id']        = array(
1535
-                'name'  => 'id',
1536
-                'input' => 'hidden',
1537
-                'type'  => 'int',
1538
-                'value' => $GRP_ID
1539
-            );
1540
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
-                'name'  => $action . '_nonce',
1542
-                'input' => 'hidden',
1543
-                'type'  => 'string',
1544
-                'value' => wp_create_nonce($action . '_nonce')
1545
-            );
1534
+			$sidebar_form_fields['ee-msg-id']        = array(
1535
+				'name'  => 'id',
1536
+				'input' => 'hidden',
1537
+				'type'  => 'int',
1538
+				'value' => $GRP_ID
1539
+			);
1540
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
+				'name'  => $action . '_nonce',
1542
+				'input' => 'hidden',
1543
+				'type'  => 'string',
1544
+				'value' => wp_create_nonce($action . '_nonce')
1545
+			);
1546 1546
             
1547
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1548
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1549
-                    'name'  => 'template_switch',
1550
-                    'input' => 'hidden',
1551
-                    'type'  => 'int',
1552
-                    'value' => 1
1553
-                );
1554
-            }
1547
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1548
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1549
+					'name'  => 'template_switch',
1550
+					'input' => 'hidden',
1551
+					'type'  => 'int',
1552
+					'value' => 1
1553
+				);
1554
+			}
1555 1555
             
1556 1556
             
1557
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1558
-            $sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1557
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1558
+			$sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1559 1559
             
1560 1560
             
1561
-        } //end if ( !empty($template_field_structure) )
1561
+		} //end if ( !empty($template_field_structure) )
1562 1562
         
1563
-        //set extra content for publish box
1564
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1565
-        $this->_set_publish_post_box_vars(
1566
-            'id',
1567
-            $GRP_ID,
1568
-            false,
1569
-            add_query_arg(
1570
-                array('action' => 'global_mtps'),
1571
-                $this->_admin_base_url
1572
-            )
1573
-        );
1574
-        
1575
-        //add preview button
1576
-        $preview_url    = parent::add_query_args_and_nonce(
1577
-            array(
1578
-                'message_type' => $message_template_group->message_type(),
1579
-                'messenger'    => $message_template_group->messenger(),
1580
-                'context'      => $context,
1581
-                'GRP_ID'       => $GRP_ID,
1582
-                'action'       => 'preview_message'
1583
-            ),
1584
-            $this->_admin_base_url
1585
-        );
1586
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
-                'event_espresso') . '</a>';
1588
-        
1589
-        
1590
-        //setup context switcher
1591
-        $context_switcher_args = array(
1592
-            'page'    => 'espresso_messages',
1593
-            'action'  => 'edit_message_template',
1594
-            'id'      => $GRP_ID,
1595
-            'context' => $context,
1596
-            'extra'   => $preview_button
1597
-        );
1598
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1599
-        
1600
-        
1601
-        //main box
1602
-        $this->_template_args['template_fields']                         = $template_fields;
1603
-        $this->_template_args['sidebar_box_id']                          = 'details';
1604
-        $this->_template_args['action']                                  = $action;
1605
-        $this->_template_args['context']                                 = $context;
1606
-        $this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1607
-        $this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1608
-        
1609
-        
1610
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1611
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1612
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613
-        
1614
-        $this->_template_path = $this->_template_args['GRP_ID']
1615
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1617
-        
1618
-        //send along EE_Message_Template_Group object for further template use.
1619
-        $this->_template_args['MTP'] = $message_template_group;
1620
-        
1621
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
1622
-            $this->_template_args, true);
1623
-        
1624
-        
1625
-        //finally, let's set the admin_page title
1626
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1627
-        
1628
-        
1629
-        //we need to take care of setting the shortcodes property for use elsewhere.
1630
-        $this->_set_shortcodes();
1631
-        
1632
-        
1633
-        //final template wrapper
1634
-        $this->display_admin_page_with_sidebar();
1635
-    }
1636
-    
1637
-    
1638
-    public function filter_tinymce_init($mceInit, $editor_id)
1639
-    {
1640
-        return $mceInit;
1641
-    }
1642
-    
1643
-    
1644
-    public function add_context_switcher()
1645
-    {
1646
-        return $this->_context_switcher;
1647
-    }
1648
-    
1649
-    public function _add_form_element_before()
1650
-    {
1651
-        return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1652
-    }
1653
-    
1654
-    public function _add_form_element_after()
1655
-    {
1656
-        return '</form>';
1657
-    }
1658
-    
1659
-    
1660
-    /**
1661
-     * This executes switching the template pack for a message template.
1662
-     *
1663
-     * @since 4.5.0
1664
-     *
1665
-     */
1666
-    public function switch_template_pack()
1667
-    {
1668
-        $GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1669
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1670
-        
1671
-        //verify we have needed values.
1672
-        if (empty($GRP_ID) || empty($template_pack)) {
1673
-            $this->_template_args['error'] = true;
1674
-            EE_Error::add_error(__('The required date for switching templates is not available.', 'event_espresso'),
1675
-                __FILE__, __FUNCTION__, __LINE__);
1676
-        } else {
1677
-            //get template, set the new template_pack and then reset to default
1678
-            /** @type EE_Message_Template_Group $message_template_group */
1679
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1563
+		//set extra content for publish box
1564
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1565
+		$this->_set_publish_post_box_vars(
1566
+			'id',
1567
+			$GRP_ID,
1568
+			false,
1569
+			add_query_arg(
1570
+				array('action' => 'global_mtps'),
1571
+				$this->_admin_base_url
1572
+			)
1573
+		);
1574
+        
1575
+		//add preview button
1576
+		$preview_url    = parent::add_query_args_and_nonce(
1577
+			array(
1578
+				'message_type' => $message_template_group->message_type(),
1579
+				'messenger'    => $message_template_group->messenger(),
1580
+				'context'      => $context,
1581
+				'GRP_ID'       => $GRP_ID,
1582
+				'action'       => 'preview_message'
1583
+			),
1584
+			$this->_admin_base_url
1585
+		);
1586
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
+				'event_espresso') . '</a>';
1588
+        
1589
+        
1590
+		//setup context switcher
1591
+		$context_switcher_args = array(
1592
+			'page'    => 'espresso_messages',
1593
+			'action'  => 'edit_message_template',
1594
+			'id'      => $GRP_ID,
1595
+			'context' => $context,
1596
+			'extra'   => $preview_button
1597
+		);
1598
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1599
+        
1600
+        
1601
+		//main box
1602
+		$this->_template_args['template_fields']                         = $template_fields;
1603
+		$this->_template_args['sidebar_box_id']                          = 'details';
1604
+		$this->_template_args['action']                                  = $action;
1605
+		$this->_template_args['context']                                 = $context;
1606
+		$this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1607
+		$this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1608
+        
1609
+        
1610
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1611
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1612
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613
+        
1614
+		$this->_template_path = $this->_template_args['GRP_ID']
1615
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1617
+        
1618
+		//send along EE_Message_Template_Group object for further template use.
1619
+		$this->_template_args['MTP'] = $message_template_group;
1620
+        
1621
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
1622
+			$this->_template_args, true);
1623
+        
1624
+        
1625
+		//finally, let's set the admin_page title
1626
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1627
+        
1628
+        
1629
+		//we need to take care of setting the shortcodes property for use elsewhere.
1630
+		$this->_set_shortcodes();
1631
+        
1632
+        
1633
+		//final template wrapper
1634
+		$this->display_admin_page_with_sidebar();
1635
+	}
1636
+    
1637
+    
1638
+	public function filter_tinymce_init($mceInit, $editor_id)
1639
+	{
1640
+		return $mceInit;
1641
+	}
1642
+    
1643
+    
1644
+	public function add_context_switcher()
1645
+	{
1646
+		return $this->_context_switcher;
1647
+	}
1648
+    
1649
+	public function _add_form_element_before()
1650
+	{
1651
+		return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1652
+	}
1653
+    
1654
+	public function _add_form_element_after()
1655
+	{
1656
+		return '</form>';
1657
+	}
1658
+    
1659
+    
1660
+	/**
1661
+	 * This executes switching the template pack for a message template.
1662
+	 *
1663
+	 * @since 4.5.0
1664
+	 *
1665
+	 */
1666
+	public function switch_template_pack()
1667
+	{
1668
+		$GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1669
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1670
+        
1671
+		//verify we have needed values.
1672
+		if (empty($GRP_ID) || empty($template_pack)) {
1673
+			$this->_template_args['error'] = true;
1674
+			EE_Error::add_error(__('The required date for switching templates is not available.', 'event_espresso'),
1675
+				__FILE__, __FUNCTION__, __LINE__);
1676
+		} else {
1677
+			//get template, set the new template_pack and then reset to default
1678
+			/** @type EE_Message_Template_Group $message_template_group */
1679
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1680 1680
             
1681
-            $message_template_group->set_template_pack_name($template_pack);
1682
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1683
-            $this->_req_data['mt']   = $message_template_group->message_type();
1681
+			$message_template_group->set_template_pack_name($template_pack);
1682
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1683
+			$this->_req_data['mt']   = $message_template_group->message_type();
1684 1684
             
1685
-            $query_args = $this->_reset_to_default_template();
1685
+			$query_args = $this->_reset_to_default_template();
1686 1686
             
1687
-            if (empty($query_args['id'])) {
1688
-                EE_Error::add_error(
1689
-                    __(
1690
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1691
-                        'event_espresso'
1692
-                    ),
1693
-                    __FILE__, __FUNCTION__, __LINE__
1694
-                );
1695
-                $this->_template_args['error'] = true;
1696
-            } else {
1697
-                $template_label       = $message_template_group->get_template_pack()->label;
1698
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1699
-                EE_Error::add_success(
1700
-                    sprintf(
1701
-                        __(
1702
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1703
-                            'event_espresso'
1704
-                        ),
1705
-                        $template_label,
1706
-                        $template_pack_labels->template_pack
1707
-                    )
1708
-                );
1709
-                //generate the redirect url for js.
1710
-                $url                                          = self::add_query_args_and_nonce($query_args,
1711
-                    $this->_admin_base_url);
1712
-                $this->_template_args['data']['redirect_url'] = $url;
1713
-                $this->_template_args['success']              = true;
1714
-            }
1687
+			if (empty($query_args['id'])) {
1688
+				EE_Error::add_error(
1689
+					__(
1690
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1691
+						'event_espresso'
1692
+					),
1693
+					__FILE__, __FUNCTION__, __LINE__
1694
+				);
1695
+				$this->_template_args['error'] = true;
1696
+			} else {
1697
+				$template_label       = $message_template_group->get_template_pack()->label;
1698
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1699
+				EE_Error::add_success(
1700
+					sprintf(
1701
+						__(
1702
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1703
+							'event_espresso'
1704
+						),
1705
+						$template_label,
1706
+						$template_pack_labels->template_pack
1707
+					)
1708
+				);
1709
+				//generate the redirect url for js.
1710
+				$url                                          = self::add_query_args_and_nonce($query_args,
1711
+					$this->_admin_base_url);
1712
+				$this->_template_args['data']['redirect_url'] = $url;
1713
+				$this->_template_args['success']              = true;
1714
+			}
1715 1715
             
1716
-            $this->_return_json();
1716
+			$this->_return_json();
1717 1717
             
1718
-        }
1719
-    }
1720
-    
1721
-    
1722
-    /**
1723
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1724
-     * they want.
1725
-     *
1726
-     * @access protected
1727
-     * @return array|null
1728
-     */
1729
-    protected function _reset_to_default_template()
1730
-    {
1731
-        
1732
-        $templates = array();
1733
-        $GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1734
-        //we need to make sure we've got the info we need.
1735
-        if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
1736
-            EE_Error::add_error(
1737
-                __(
1738
-                    'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
1739
-                    'event_espresso'
1740
-                ),
1741
-                __FILE__, __FUNCTION__, __LINE__
1742
-            );
1743
-        }
1744
-        
1745
-        // all templates will be reset to whatever the defaults are
1746
-        // for the global template matching the messenger and message type.
1747
-        $success = ! empty($GRP_ID) ? true : false;
1748
-        
1749
-        if ($success) {
1718
+		}
1719
+	}
1720
+    
1721
+    
1722
+	/**
1723
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1724
+	 * they want.
1725
+	 *
1726
+	 * @access protected
1727
+	 * @return array|null
1728
+	 */
1729
+	protected function _reset_to_default_template()
1730
+	{
1731
+        
1732
+		$templates = array();
1733
+		$GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1734
+		//we need to make sure we've got the info we need.
1735
+		if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
1736
+			EE_Error::add_error(
1737
+				__(
1738
+					'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
1739
+					'event_espresso'
1740
+				),
1741
+				__FILE__, __FUNCTION__, __LINE__
1742
+			);
1743
+		}
1744
+        
1745
+		// all templates will be reset to whatever the defaults are
1746
+		// for the global template matching the messenger and message type.
1747
+		$success = ! empty($GRP_ID) ? true : false;
1748
+        
1749
+		if ($success) {
1750 1750
             
1751
-            //let's first determine if the incoming template is a global template,
1752
-            // if it isn't then we need to get the global template matching messenger and message type.
1753
-            //$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1751
+			//let's first determine if the incoming template is a global template,
1752
+			// if it isn't then we need to get the global template matching messenger and message type.
1753
+			//$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1754 1754
             
1755 1755
             
1756
-            //note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1757
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
1756
+			//note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1757
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
1758 1758
             
1759
-            if ($success) {
1760
-                // if successfully deleted, lets generate the new ones.
1761
-                // Note. We set GLOBAL to true, because resets on ANY template
1762
-                // will use the related global template defaults for regeneration.
1763
-                // This means that if a custom template is reset it resets to whatever the related global template is.
1764
-                // HOWEVER, we DO keep the template pack and template variation set
1765
-                // for the current custom template when resetting.
1766
-                $templates = $this->_generate_new_templates(
1767
-                    $this->_req_data['msgr'],
1768
-                    $this->_req_data['mt'],
1769
-                    $GRP_ID,
1770
-                    true
1771
-                );
1772
-            }
1759
+			if ($success) {
1760
+				// if successfully deleted, lets generate the new ones.
1761
+				// Note. We set GLOBAL to true, because resets on ANY template
1762
+				// will use the related global template defaults for regeneration.
1763
+				// This means that if a custom template is reset it resets to whatever the related global template is.
1764
+				// HOWEVER, we DO keep the template pack and template variation set
1765
+				// for the current custom template when resetting.
1766
+				$templates = $this->_generate_new_templates(
1767
+					$this->_req_data['msgr'],
1768
+					$this->_req_data['mt'],
1769
+					$GRP_ID,
1770
+					true
1771
+				);
1772
+			}
1773 1773
             
1774
-        }
1775
-        
1776
-        //any error messages?
1777
-        if ( ! $success) {
1778
-            EE_Error::add_error(
1779
-                __('Something went wrong with deleting existing templates. Unable to reset to default',
1780
-                    'event_espresso'),
1781
-                __FILE__, __FUNCTION__, __LINE__
1782
-            );
1783
-        }
1784
-        
1785
-        //all good, let's add a success message!
1786
-        if ($success && ! empty($templates)) {
1787
-            $templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1788
-            EE_Error::overwrite_success();
1789
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
1790
-        }
1791
-        
1792
-        
1793
-        $query_args = array(
1794
-            'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
1795
-            'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
1796
-            'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
1797
-        );
1798
-        
1799
-        //if called via ajax then we return query args otherwise redirect
1800
-        if (defined('DOING_AJAX') && DOING_AJAX) {
1801
-            return $query_args;
1802
-        } else {
1803
-            $this->_redirect_after_action(false, '', '', $query_args, true);
1774
+		}
1775
+        
1776
+		//any error messages?
1777
+		if ( ! $success) {
1778
+			EE_Error::add_error(
1779
+				__('Something went wrong with deleting existing templates. Unable to reset to default',
1780
+					'event_espresso'),
1781
+				__FILE__, __FUNCTION__, __LINE__
1782
+			);
1783
+		}
1784
+        
1785
+		//all good, let's add a success message!
1786
+		if ($success && ! empty($templates)) {
1787
+			$templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1788
+			EE_Error::overwrite_success();
1789
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
1790
+		}
1791
+        
1792
+        
1793
+		$query_args = array(
1794
+			'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
1795
+			'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
1796
+			'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
1797
+		);
1798
+        
1799
+		//if called via ajax then we return query args otherwise redirect
1800
+		if (defined('DOING_AJAX') && DOING_AJAX) {
1801
+			return $query_args;
1802
+		} else {
1803
+			$this->_redirect_after_action(false, '', '', $query_args, true);
1804 1804
             
1805
-            return null;
1806
-        }
1807
-    }
1808
-    
1809
-    
1810
-    /**
1811
-     * Retrieve and set the message preview for display.
1812
-     *
1813
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1814
-     *
1815
-     * @return string
1816
-     */
1817
-    public function _preview_message($send = false)
1818
-    {
1819
-        //first make sure we've got the necessary parameters
1820
-        if (
1821
-        ! isset(
1822
-            $this->_req_data['message_type'],
1823
-            $this->_req_data['messenger'],
1824
-            $this->_req_data['messenger'],
1825
-            $this->_req_data['GRP_ID']
1826
-        )
1827
-        ) {
1828
-            EE_Error::add_error(
1829
-                __('Missing necessary parameters for displaying preview', 'event_espresso'),
1830
-                __FILE__, __FUNCTION__, __LINE__
1831
-            );
1832
-        }
1833
-        
1834
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
1835
-        
1836
-        
1837
-        //get the preview!
1838
-        $preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
1839
-            $this->_req_data['messenger'], $send);
1840
-        
1841
-        if ($send) {
1842
-            return $preview;
1843
-        }
1844
-        
1845
-        //let's add a button to go back to the edit view
1846
-        $query_args             = array(
1847
-            'id'      => $this->_req_data['GRP_ID'],
1848
-            'context' => $this->_req_data['context'],
1849
-            'action'  => 'edit_message_template'
1850
-        );
1851
-        $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
-        $preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
-                'event_espresso') . '</a>';
1854
-        $message_types          = $this->get_installed_message_types();
1855
-        $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856
-        $active_messenger_label = $active_messenger instanceof EE_messenger
1857
-            ? ucwords($active_messenger->label['singular'])
1858
-            : esc_html__('Unknown Messenger', 'event_espresso');
1859
-        //let's provide a helpful title for context
1860
-        $preview_title = sprintf(
1861
-            __('Viewing Preview for %s %s Message Template', 'event_espresso'),
1862
-            $active_messenger_label,
1863
-            ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
1864
-        );
1865
-        //setup display of preview.
1866
-        $this->_admin_page_title                    = $preview_title;
1867
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1868
-        $this->_template_args['data']['force_json'] = true;
1869
-        
1870
-        return '';
1871
-    }
1872
-    
1873
-    
1874
-    /**
1875
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1876
-     * gets called automatically.
1877
-     *
1878
-     * @since 4.5.0
1879
-     *
1880
-     * @return string
1881
-     */
1882
-    protected function _display_preview_message()
1883
-    {
1884
-        $this->display_admin_page_with_no_sidebar();
1885
-    }
1886
-    
1887
-    
1888
-    /**
1889
-     * registers metaboxes that should show up on the "edit_message_template" page
1890
-     *
1891
-     * @access protected
1892
-     * @return void
1893
-     */
1894
-    protected function _register_edit_meta_boxes()
1895
-    {
1896
-        add_meta_box('mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'),
1897
-            array($this, 'shortcode_meta_box'), $this->_current_screen->id, 'side', 'default');
1898
-        add_meta_box('mtp_extra_actions', __('Extra Actions', 'event_espresso'), array($this, 'extra_actions_meta_box'),
1899
-            $this->_current_screen->id, 'side', 'high');
1900
-        add_meta_box('mtp_templates', __('Template Styles', 'event_espresso'), array($this, 'template_pack_meta_box'),
1901
-            $this->_current_screen->id, 'side', 'high');
1902
-    }
1903
-    
1904
-    
1905
-    /**
1906
-     * metabox content for all template pack and variation selection.
1907
-     *
1908
-     * @since 4.5.0
1909
-     *
1910
-     * @return string
1911
-     */
1912
-    public function template_pack_meta_box()
1913
-    {
1914
-        $this->_set_message_template_group();
1915
-        
1916
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
1917
-        
1918
-        $tp_select_values = array();
1919
-        
1920
-        foreach ($tp_collection as $tp) {
1921
-            //only include template packs that support this messenger and message type!
1922
-            $supports = $tp->get_supports();
1923
-            if (
1924
-                ! isset($supports[$this->_message_template_group->messenger()])
1925
-                || ! in_array(
1926
-                    $this->_message_template_group->message_type(),
1927
-                    $supports[$this->_message_template_group->messenger()]
1928
-                )
1929
-            ) {
1930
-                //not supported
1931
-                continue;
1932
-            }
1805
+			return null;
1806
+		}
1807
+	}
1808
+    
1809
+    
1810
+	/**
1811
+	 * Retrieve and set the message preview for display.
1812
+	 *
1813
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1814
+	 *
1815
+	 * @return string
1816
+	 */
1817
+	public function _preview_message($send = false)
1818
+	{
1819
+		//first make sure we've got the necessary parameters
1820
+		if (
1821
+		! isset(
1822
+			$this->_req_data['message_type'],
1823
+			$this->_req_data['messenger'],
1824
+			$this->_req_data['messenger'],
1825
+			$this->_req_data['GRP_ID']
1826
+		)
1827
+		) {
1828
+			EE_Error::add_error(
1829
+				__('Missing necessary parameters for displaying preview', 'event_espresso'),
1830
+				__FILE__, __FUNCTION__, __LINE__
1831
+			);
1832
+		}
1833
+        
1834
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
1835
+        
1836
+        
1837
+		//get the preview!
1838
+		$preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
1839
+			$this->_req_data['messenger'], $send);
1840
+        
1841
+		if ($send) {
1842
+			return $preview;
1843
+		}
1844
+        
1845
+		//let's add a button to go back to the edit view
1846
+		$query_args             = array(
1847
+			'id'      => $this->_req_data['GRP_ID'],
1848
+			'context' => $this->_req_data['context'],
1849
+			'action'  => 'edit_message_template'
1850
+		);
1851
+		$go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
+		$preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
+				'event_espresso') . '</a>';
1854
+		$message_types          = $this->get_installed_message_types();
1855
+		$active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856
+		$active_messenger_label = $active_messenger instanceof EE_messenger
1857
+			? ucwords($active_messenger->label['singular'])
1858
+			: esc_html__('Unknown Messenger', 'event_espresso');
1859
+		//let's provide a helpful title for context
1860
+		$preview_title = sprintf(
1861
+			__('Viewing Preview for %s %s Message Template', 'event_espresso'),
1862
+			$active_messenger_label,
1863
+			ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
1864
+		);
1865
+		//setup display of preview.
1866
+		$this->_admin_page_title                    = $preview_title;
1867
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1868
+		$this->_template_args['data']['force_json'] = true;
1869
+        
1870
+		return '';
1871
+	}
1872
+    
1873
+    
1874
+	/**
1875
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1876
+	 * gets called automatically.
1877
+	 *
1878
+	 * @since 4.5.0
1879
+	 *
1880
+	 * @return string
1881
+	 */
1882
+	protected function _display_preview_message()
1883
+	{
1884
+		$this->display_admin_page_with_no_sidebar();
1885
+	}
1886
+    
1887
+    
1888
+	/**
1889
+	 * registers metaboxes that should show up on the "edit_message_template" page
1890
+	 *
1891
+	 * @access protected
1892
+	 * @return void
1893
+	 */
1894
+	protected function _register_edit_meta_boxes()
1895
+	{
1896
+		add_meta_box('mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'),
1897
+			array($this, 'shortcode_meta_box'), $this->_current_screen->id, 'side', 'default');
1898
+		add_meta_box('mtp_extra_actions', __('Extra Actions', 'event_espresso'), array($this, 'extra_actions_meta_box'),
1899
+			$this->_current_screen->id, 'side', 'high');
1900
+		add_meta_box('mtp_templates', __('Template Styles', 'event_espresso'), array($this, 'template_pack_meta_box'),
1901
+			$this->_current_screen->id, 'side', 'high');
1902
+	}
1903
+    
1904
+    
1905
+	/**
1906
+	 * metabox content for all template pack and variation selection.
1907
+	 *
1908
+	 * @since 4.5.0
1909
+	 *
1910
+	 * @return string
1911
+	 */
1912
+	public function template_pack_meta_box()
1913
+	{
1914
+		$this->_set_message_template_group();
1915
+        
1916
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
1917
+        
1918
+		$tp_select_values = array();
1919
+        
1920
+		foreach ($tp_collection as $tp) {
1921
+			//only include template packs that support this messenger and message type!
1922
+			$supports = $tp->get_supports();
1923
+			if (
1924
+				! isset($supports[$this->_message_template_group->messenger()])
1925
+				|| ! in_array(
1926
+					$this->_message_template_group->message_type(),
1927
+					$supports[$this->_message_template_group->messenger()]
1928
+				)
1929
+			) {
1930
+				//not supported
1931
+				continue;
1932
+			}
1933 1933
             
1934
-            $tp_select_values[] = array(
1935
-                'text' => $tp->label,
1936
-                'id'   => $tp->dbref
1937
-            );
1938
-        }
1939
-        
1940
-        //if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1941
-        if (empty($tp_select_values)) {
1942
-            $tp_select_values[] = array(
1943
-                'text' => __('Default', 'event_espresso'),
1944
-                'id'   => 'default'
1945
-            );
1946
-        }
1947
-        
1948
-        //setup variation select values for the currently selected template.
1949
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
1950
-            $this->_message_template_group->messenger(),
1951
-            $this->_message_template_group->message_type()
1952
-        );
1953
-        $variations_select_values = array();
1954
-        foreach ($variations as $variation => $label) {
1955
-            $variations_select_values[] = array(
1956
-                'text' => $label,
1957
-                'id'   => $variation
1958
-            );
1959
-        }
1960
-        
1961
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962
-        
1963
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1964
-            'MTP_template_pack',
1965
-            $tp_select_values,
1966
-            $this->_message_template_group->get_template_pack_name()
1967
-        );
1968
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
1969
-            'MTP_template_variation',
1970
-            $variations_select_values,
1971
-            $this->_message_template_group->get_template_pack_variation()
1972
-        );
1973
-        $template_args['template_pack_label']            = $template_pack_labels->template_pack;
1974
-        $template_args['template_variation_label']       = $template_pack_labels->template_variation;
1975
-        $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977
-        
1978
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1979
-        
1980
-        EEH_Template::display_template($template, $template_args);
1981
-    }
1982
-    
1983
-    
1984
-    /**
1985
-     * This meta box holds any extra actions related to Message Templates
1986
-     * For now, this includes Resetting templates to defaults and sending a test email.
1987
-     *
1988
-     * @access  public
1989
-     * @return void
1990
-     * @throws \EE_Error
1991
-     */
1992
-    public function extra_actions_meta_box()
1993
-    {
1994
-        $template_form_fields = array();
1995
-        
1996
-        $extra_args = array(
1997
-            'msgr'   => $this->_message_template_group->messenger(),
1998
-            'mt'     => $this->_message_template_group->message_type(),
1999
-            'GRP_ID' => $this->_message_template_group->GRP_ID()
2000
-        );
2001
-        //first we need to see if there are any fields
2002
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2003
-        
2004
-        if ( ! empty($fields)) {
2005
-            //yup there be fields
2006
-            foreach ($fields as $field => $config) {
2007
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2008
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009
-                $default  = isset($config['default']) ? $config['default'] : '';
2010
-                $default  = isset($config['value']) ? $config['value'] : $default;
1934
+			$tp_select_values[] = array(
1935
+				'text' => $tp->label,
1936
+				'id'   => $tp->dbref
1937
+			);
1938
+		}
1939
+        
1940
+		//if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1941
+		if (empty($tp_select_values)) {
1942
+			$tp_select_values[] = array(
1943
+				'text' => __('Default', 'event_espresso'),
1944
+				'id'   => 'default'
1945
+			);
1946
+		}
1947
+        
1948
+		//setup variation select values for the currently selected template.
1949
+		$variations               = $this->_message_template_group->get_template_pack()->get_variations(
1950
+			$this->_message_template_group->messenger(),
1951
+			$this->_message_template_group->message_type()
1952
+		);
1953
+		$variations_select_values = array();
1954
+		foreach ($variations as $variation => $label) {
1955
+			$variations_select_values[] = array(
1956
+				'text' => $label,
1957
+				'id'   => $variation
1958
+			);
1959
+		}
1960
+        
1961
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962
+        
1963
+		$template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1964
+			'MTP_template_pack',
1965
+			$tp_select_values,
1966
+			$this->_message_template_group->get_template_pack_name()
1967
+		);
1968
+		$template_args['variations_selector']            = EEH_Form_Fields::select_input(
1969
+			'MTP_template_variation',
1970
+			$variations_select_values,
1971
+			$this->_message_template_group->get_template_pack_variation()
1972
+		);
1973
+		$template_args['template_pack_label']            = $template_pack_labels->template_pack;
1974
+		$template_args['template_variation_label']       = $template_pack_labels->template_variation;
1975
+		$template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977
+        
1978
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1979
+        
1980
+		EEH_Template::display_template($template, $template_args);
1981
+	}
1982
+    
1983
+    
1984
+	/**
1985
+	 * This meta box holds any extra actions related to Message Templates
1986
+	 * For now, this includes Resetting templates to defaults and sending a test email.
1987
+	 *
1988
+	 * @access  public
1989
+	 * @return void
1990
+	 * @throws \EE_Error
1991
+	 */
1992
+	public function extra_actions_meta_box()
1993
+	{
1994
+		$template_form_fields = array();
1995
+        
1996
+		$extra_args = array(
1997
+			'msgr'   => $this->_message_template_group->messenger(),
1998
+			'mt'     => $this->_message_template_group->message_type(),
1999
+			'GRP_ID' => $this->_message_template_group->GRP_ID()
2000
+		);
2001
+		//first we need to see if there are any fields
2002
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2003
+        
2004
+		if ( ! empty($fields)) {
2005
+			//yup there be fields
2006
+			foreach ($fields as $field => $config) {
2007
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2008
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009
+				$default  = isset($config['default']) ? $config['default'] : '';
2010
+				$default  = isset($config['value']) ? $config['value'] : $default;
2011 2011
                 
2012
-                // if type is hidden and the value is empty
2013
-                // something may have gone wrong so let's correct with the defaults
2014
-                $fix              = $config['input'] === 'hidden' && isset($existing[$field]) && empty($existing[$field])
2015
-                    ? $default
2016
-                    : '';
2017
-                $existing[$field] = isset($existing[$field]) && empty($fix)
2018
-                    ? $existing[$field]
2019
-                    : $fix;
2012
+				// if type is hidden and the value is empty
2013
+				// something may have gone wrong so let's correct with the defaults
2014
+				$fix              = $config['input'] === 'hidden' && isset($existing[$field]) && empty($existing[$field])
2015
+					? $default
2016
+					: '';
2017
+				$existing[$field] = isset($existing[$field]) && empty($fix)
2018
+					? $existing[$field]
2019
+					: $fix;
2020 2020
                 
2021
-                $template_form_fields[$field_id] = array(
2022
-                    'name'       => 'test_settings_fld[' . $field . ']',
2023
-                    'label'      => $config['label'],
2024
-                    'input'      => $config['input'],
2025
-                    'type'       => $config['type'],
2026
-                    'required'   => $config['required'],
2027
-                    'validation' => $config['validation'],
2028
-                    'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2029
-                    'css_class'  => $config['css_class'],
2030
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2031
-                    'default'    => $default,
2032
-                    'format'     => $config['format']
2033
-                );
2034
-            }
2035
-        }
2036
-        
2037
-        $test_settings_fields = ! empty($template_form_fields)
2038
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2039
-            : '';
2040
-        
2041
-        $test_settings_html = '';
2042
-        //print out $test_settings_fields
2043
-        if ( ! empty($test_settings_fields)) {
2044
-            echo $test_settings_fields;
2045
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2046
-            $test_settings_html .= 'name="test_button" value="';
2047
-            $test_settings_html .= __('Test Send', 'event_espresso');
2048
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2049
-        }
2050
-        
2051
-        //and button
2052
-        $test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2053
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054
-        $test_settings_html .= $this->get_action_link_or_button(
2055
-            'reset_to_default',
2056
-            'reset',
2057
-            $extra_args,
2058
-            'button-primary reset-default-button'
2059
-        );
2060
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2061
-        echo $test_settings_html;
2062
-    }
2063
-    
2064
-    
2065
-    /**
2066
-     * This returns the shortcode selector skeleton for a given context and field.
2067
-     *
2068
-     * @since 4.9.rc.000
2069
-     *
2070
-     * @param string $field           The name of the field retrieving shortcodes for.
2071
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2072
-     *
2073
-     * @return string
2074
-     */
2075
-    protected function _get_shortcode_selector($field, $linked_input_id)
2076
-    {
2077
-        $template_args = array(
2078
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2079
-            'fieldname'       => $field,
2080
-            'linked_input_id' => $linked_input_id
2081
-        );
2082
-        
2083
-        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2084
-            $template_args, true);
2085
-    }
2086
-    
2087
-    
2088
-    /**
2089
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2090
-     * page)
2091
-     *
2092
-     * @access public
2093
-     * @return void
2094
-     */
2095
-    public function shortcode_meta_box()
2096
-    {
2097
-        $shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2098
-        //$messenger = $this->_message_template_group->messenger_obj();
2099
-        //now let's set the content depending on the status of the shortcodes array
2100
-        if (empty($shortcodes)) {
2101
-            $content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2102
-            echo $content;
2103
-        } else {
2104
-            //$alt = 0;
2105
-            ?>
2021
+				$template_form_fields[$field_id] = array(
2022
+					'name'       => 'test_settings_fld[' . $field . ']',
2023
+					'label'      => $config['label'],
2024
+					'input'      => $config['input'],
2025
+					'type'       => $config['type'],
2026
+					'required'   => $config['required'],
2027
+					'validation' => $config['validation'],
2028
+					'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2029
+					'css_class'  => $config['css_class'],
2030
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2031
+					'default'    => $default,
2032
+					'format'     => $config['format']
2033
+				);
2034
+			}
2035
+		}
2036
+        
2037
+		$test_settings_fields = ! empty($template_form_fields)
2038
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2039
+			: '';
2040
+        
2041
+		$test_settings_html = '';
2042
+		//print out $test_settings_fields
2043
+		if ( ! empty($test_settings_fields)) {
2044
+			echo $test_settings_fields;
2045
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2046
+			$test_settings_html .= 'name="test_button" value="';
2047
+			$test_settings_html .= __('Test Send', 'event_espresso');
2048
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2049
+		}
2050
+        
2051
+		//and button
2052
+		$test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2053
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054
+		$test_settings_html .= $this->get_action_link_or_button(
2055
+			'reset_to_default',
2056
+			'reset',
2057
+			$extra_args,
2058
+			'button-primary reset-default-button'
2059
+		);
2060
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2061
+		echo $test_settings_html;
2062
+	}
2063
+    
2064
+    
2065
+	/**
2066
+	 * This returns the shortcode selector skeleton for a given context and field.
2067
+	 *
2068
+	 * @since 4.9.rc.000
2069
+	 *
2070
+	 * @param string $field           The name of the field retrieving shortcodes for.
2071
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2072
+	 *
2073
+	 * @return string
2074
+	 */
2075
+	protected function _get_shortcode_selector($field, $linked_input_id)
2076
+	{
2077
+		$template_args = array(
2078
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2079
+			'fieldname'       => $field,
2080
+			'linked_input_id' => $linked_input_id
2081
+		);
2082
+        
2083
+		return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2084
+			$template_args, true);
2085
+	}
2086
+    
2087
+    
2088
+	/**
2089
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2090
+	 * page)
2091
+	 *
2092
+	 * @access public
2093
+	 * @return void
2094
+	 */
2095
+	public function shortcode_meta_box()
2096
+	{
2097
+		$shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2098
+		//$messenger = $this->_message_template_group->messenger_obj();
2099
+		//now let's set the content depending on the status of the shortcodes array
2100
+		if (empty($shortcodes)) {
2101
+			$content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2102
+			echo $content;
2103
+		} else {
2104
+			//$alt = 0;
2105
+			?>
2106 2106
             <div
2107 2107
                 style="float:right; margin-top:10px"><?php echo $this->_get_help_tab_link('message_template_shortcodes'); ?></div>
2108 2108
             <p class="small-text"><?php printf(__('You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2109
-                    'event_espresso'), '<span class="dashicons dashicons-menu"></span>'); ?></p>
2109
+					'event_espresso'), '<span class="dashicons dashicons-menu"></span>'); ?></p>
2110 2110
             <?php
2111
-        }
2112
-        
2113
-        
2114
-    }
2115
-    
2116
-    
2117
-    /**
2118
-     * used to set the $_shortcodes property for when its needed elsewhere.
2119
-     *
2120
-     * @access protected
2121
-     * @return void
2122
-     */
2123
-    protected function _set_shortcodes()
2124
-    {
2125
-        
2126
-        //no need to run this if the property is already set
2127
-        if ( ! empty($this->_shortcodes)) {
2128
-            return;
2129
-        }
2130
-        
2131
-        $this->_shortcodes = $this->_get_shortcodes();
2132
-    }
2133
-    
2134
-    
2135
-    /**
2136
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2137
-     * property)
2138
-     *
2139
-     * @access  protected
2140
-     *
2141
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2142
-     *                         for. Defaults to all (for the given context)
2143
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2144
-     *
2145
-     * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2146
-     *                        true just an array of shortcode/label pairs.
2147
-     */
2148
-    protected function _get_shortcodes($fields = array(), $merged = true)
2149
-    {
2150
-        $this->_set_message_template_group();
2151
-        
2152
-        //we need the messenger and message template to retrieve the valid shortcodes array.
2153
-        $GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id']) : false;
2154
-        $context = isset($this->_req_data['context']) ? $this->_req_data['context'] : key($this->_message_template_group->contexts_config());
2155
-        
2156
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2157
-    }
2158
-    
2159
-    
2160
-    /**
2161
-     * This sets the _message_template property (containing the called message_template object)
2162
-     *
2163
-     * @access protected
2164
-     * @return  void
2165
-     */
2166
-    protected function _set_message_template_group()
2167
-    {
2168
-        
2169
-        if ( ! empty($this->_message_template_group)) {
2170
-            return;
2171
-        } //get out if this is already set.
2172
-        
2173
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2174
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2175
-        
2176
-        //let's get the message templates
2177
-        $MTP = EEM_Message_Template_Group::instance();
2178
-        
2179
-        if (empty($GRP_ID)) {
2180
-            $this->_message_template_group = $MTP->create_default_object();
2181
-        } else {
2182
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2183
-        }
2184
-        
2185
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2186
-        $this->_variation     = $this->_message_template_group->get_template_pack_variation();
2187
-        
2188
-    }
2189
-    
2190
-    
2191
-    /**
2192
-     * sets up a context switcher for edit forms
2193
-     *
2194
-     * @access  protected
2195
-     *
2196
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2197
-     * @param array                      $args                  various things the context switcher needs.
2198
-     *
2199
-     */
2200
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2201
-    {
2202
-        $context_details = $template_group_object->contexts_config();
2203
-        $context_label   = $template_group_object->context_label();
2204
-        ob_start();
2205
-        ?>
2111
+		}
2112
+        
2113
+        
2114
+	}
2115
+    
2116
+    
2117
+	/**
2118
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2119
+	 *
2120
+	 * @access protected
2121
+	 * @return void
2122
+	 */
2123
+	protected function _set_shortcodes()
2124
+	{
2125
+        
2126
+		//no need to run this if the property is already set
2127
+		if ( ! empty($this->_shortcodes)) {
2128
+			return;
2129
+		}
2130
+        
2131
+		$this->_shortcodes = $this->_get_shortcodes();
2132
+	}
2133
+    
2134
+    
2135
+	/**
2136
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2137
+	 * property)
2138
+	 *
2139
+	 * @access  protected
2140
+	 *
2141
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2142
+	 *                         for. Defaults to all (for the given context)
2143
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2144
+	 *
2145
+	 * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2146
+	 *                        true just an array of shortcode/label pairs.
2147
+	 */
2148
+	protected function _get_shortcodes($fields = array(), $merged = true)
2149
+	{
2150
+		$this->_set_message_template_group();
2151
+        
2152
+		//we need the messenger and message template to retrieve the valid shortcodes array.
2153
+		$GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id']) : false;
2154
+		$context = isset($this->_req_data['context']) ? $this->_req_data['context'] : key($this->_message_template_group->contexts_config());
2155
+        
2156
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2157
+	}
2158
+    
2159
+    
2160
+	/**
2161
+	 * This sets the _message_template property (containing the called message_template object)
2162
+	 *
2163
+	 * @access protected
2164
+	 * @return  void
2165
+	 */
2166
+	protected function _set_message_template_group()
2167
+	{
2168
+        
2169
+		if ( ! empty($this->_message_template_group)) {
2170
+			return;
2171
+		} //get out if this is already set.
2172
+        
2173
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2174
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2175
+        
2176
+		//let's get the message templates
2177
+		$MTP = EEM_Message_Template_Group::instance();
2178
+        
2179
+		if (empty($GRP_ID)) {
2180
+			$this->_message_template_group = $MTP->create_default_object();
2181
+		} else {
2182
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2183
+		}
2184
+        
2185
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2186
+		$this->_variation     = $this->_message_template_group->get_template_pack_variation();
2187
+        
2188
+	}
2189
+    
2190
+    
2191
+	/**
2192
+	 * sets up a context switcher for edit forms
2193
+	 *
2194
+	 * @access  protected
2195
+	 *
2196
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2197
+	 * @param array                      $args                  various things the context switcher needs.
2198
+	 *
2199
+	 */
2200
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2201
+	{
2202
+		$context_details = $template_group_object->contexts_config();
2203
+		$context_label   = $template_group_object->context_label();
2204
+		ob_start();
2205
+		?>
2206 2206
         <div class="ee-msg-switcher-container">
2207 2207
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2208 2208
                 <?php
2209
-                foreach ($args as $name => $value) {
2210
-                    if ($name == 'context' || empty($value) || $name == 'extra') {
2211
-                        continue;
2212
-                    }
2213
-                    ?>
2209
+				foreach ($args as $name => $value) {
2210
+					if ($name == 'context' || empty($value) || $name == 'extra') {
2211
+						continue;
2212
+					}
2213
+					?>
2214 2214
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2215 2215
                     <?php
2216
-                }
2217
-                //setup nonce_url
2218
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2219
-                ?>
2216
+				}
2217
+				//setup nonce_url
2218
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2219
+				?>
2220 2220
                 <select name="context">
2221 2221
                     <?php
2222
-                    $context_templates = $template_group_object->context_templates();
2223
-                    if (is_array($context_templates)) :
2224
-                        foreach ($context_templates as $context => $template_fields) :
2225
-                            $checked = ($context == $args['context']) ? 'selected="selected"' : '';
2226
-                            ?>
2222
+					$context_templates = $template_group_object->context_templates();
2223
+					if (is_array($context_templates)) :
2224
+						foreach ($context_templates as $context => $template_fields) :
2225
+							$checked = ($context == $args['context']) ? 'selected="selected"' : '';
2226
+							?>
2227 2227
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2228 2228
                                 <?php echo $context_details[$context]['label']; ?>
2229 2229
                             </option>
@@ -2236,1560 +2236,1560 @@  discard block
 block discarded – undo
2236 2236
             <?php echo $args['extra']; ?>
2237 2237
         </div> <!-- end .ee-msg-switcher-container -->
2238 2238
         <?php
2239
-        $output = ob_get_contents();
2240
-        ob_clean();
2241
-        $this->_context_switcher = $output;
2242
-    }
2243
-    
2244
-    
2245
-    /**
2246
-     * utility for sanitizing new values coming in.
2247
-     * Note: this is only used when updating a context.
2248
-     *
2249
-     * @access protected
2250
-     *
2251
-     * @param int $index This helps us know which template field to select from the request array.
2252
-     *
2253
-     * @return array
2254
-     */
2255
-    protected function _set_message_template_column_values($index)
2256
-    {
2257
-        if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2258
-            foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2259
-                $this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2260
-            }
2261
-        } /*else {
2239
+		$output = ob_get_contents();
2240
+		ob_clean();
2241
+		$this->_context_switcher = $output;
2242
+	}
2243
+    
2244
+    
2245
+	/**
2246
+	 * utility for sanitizing new values coming in.
2247
+	 * Note: this is only used when updating a context.
2248
+	 *
2249
+	 * @access protected
2250
+	 *
2251
+	 * @param int $index This helps us know which template field to select from the request array.
2252
+	 *
2253
+	 * @return array
2254
+	 */
2255
+	protected function _set_message_template_column_values($index)
2256
+	{
2257
+		if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2258
+			foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2259
+				$this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2260
+			}
2261
+		} /*else {
2262 2262
 			$this->_req_data['MTP_template_fields'][$index]['content'] = $this->_req_data['MTP_template_fields'][$index]['content'];
2263 2263
 		}*/
2264 2264
         
2265 2265
         
2266
-        $set_column_values = array(
2267
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2268
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2269
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2270
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2271
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2272
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2273
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2274
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2275
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2276
-                ? absint($this->_req_data['MTP_is_global'])
2277
-                : 0,
2278
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2279
-                ? absint($this->_req_data['MTP_is_override'])
2280
-                : 0,
2281
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2282
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2283
-        );
2284
-        
2285
-        
2286
-        return $set_column_values;
2287
-    }
2288
-    
2289
-    
2290
-    protected function _insert_or_update_message_template($new = false)
2291
-    {
2292
-        
2293
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2294
-        $success  = 0;
2295
-        $override = false;
2296
-        
2297
-        //setup notices description
2298
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2299
-        
2300
-        //need the message type and messenger objects to be able to use the labels for the notices
2301
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2302
-        $messenger_label  = $messenger_object instanceof EE_messenger ? ucwords($messenger_object->label['singular']) : '';
2303
-        
2304
-        $message_type_slug   = ! empty($this->_req_data['MTP_message_type']) ? $this->_req_data['MTP_message_type'] : '';
2305
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2306
-        
2307
-        $message_type_label = $message_type_object instanceof EE_message_type
2308
-            ? ucwords($message_type_object->label['singular'])
2309
-            : '';
2310
-        
2311
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2312
-            ? $this->_req_data['MTP_context']
2313
-            : '';
2314
-        $context      = ucwords(str_replace('_', ' ', $context_slug));
2315
-        
2316
-        $item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2317
-        $item_desc .= 'Message Template';
2318
-        $query_args  = array();
2319
-        $edit_array  = array();
2320
-        $action_desc = '';
2321
-        
2322
-        //if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2323
-        if ($new) {
2324
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2325
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2326
-                if (empty($edit_array)) {
2327
-                    $success = 0;
2328
-                } else {
2329
-                    $success    = 1;
2330
-                    $edit_array = $edit_array[0];
2331
-                    $query_args = array(
2332
-                        'id'      => $edit_array['GRP_ID'],
2333
-                        'context' => $edit_array['MTP_context'],
2334
-                        'action'  => 'edit_message_template'
2335
-                    );
2336
-                }
2337
-            }
2338
-            $action_desc = 'created';
2339
-        } else {
2340
-            $MTPG = EEM_Message_Template_Group::instance();
2341
-            $MTP  = EEM_Message_Template::instance();
2266
+		$set_column_values = array(
2267
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2268
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2269
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2270
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2271
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2272
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2273
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2274
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2275
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2276
+				? absint($this->_req_data['MTP_is_global'])
2277
+				: 0,
2278
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2279
+				? absint($this->_req_data['MTP_is_override'])
2280
+				: 0,
2281
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2282
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2283
+		);
2284
+        
2285
+        
2286
+		return $set_column_values;
2287
+	}
2288
+    
2289
+    
2290
+	protected function _insert_or_update_message_template($new = false)
2291
+	{
2292
+        
2293
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2294
+		$success  = 0;
2295
+		$override = false;
2296
+        
2297
+		//setup notices description
2298
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2299
+        
2300
+		//need the message type and messenger objects to be able to use the labels for the notices
2301
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2302
+		$messenger_label  = $messenger_object instanceof EE_messenger ? ucwords($messenger_object->label['singular']) : '';
2303
+        
2304
+		$message_type_slug   = ! empty($this->_req_data['MTP_message_type']) ? $this->_req_data['MTP_message_type'] : '';
2305
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2306
+        
2307
+		$message_type_label = $message_type_object instanceof EE_message_type
2308
+			? ucwords($message_type_object->label['singular'])
2309
+			: '';
2310
+        
2311
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2312
+			? $this->_req_data['MTP_context']
2313
+			: '';
2314
+		$context      = ucwords(str_replace('_', ' ', $context_slug));
2315
+        
2316
+		$item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2317
+		$item_desc .= 'Message Template';
2318
+		$query_args  = array();
2319
+		$edit_array  = array();
2320
+		$action_desc = '';
2321
+        
2322
+		//if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2323
+		if ($new) {
2324
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2325
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2326
+				if (empty($edit_array)) {
2327
+					$success = 0;
2328
+				} else {
2329
+					$success    = 1;
2330
+					$edit_array = $edit_array[0];
2331
+					$query_args = array(
2332
+						'id'      => $edit_array['GRP_ID'],
2333
+						'context' => $edit_array['MTP_context'],
2334
+						'action'  => 'edit_message_template'
2335
+					);
2336
+				}
2337
+			}
2338
+			$action_desc = 'created';
2339
+		} else {
2340
+			$MTPG = EEM_Message_Template_Group::instance();
2341
+			$MTP  = EEM_Message_Template::instance();
2342 2342
             
2343 2343
             
2344
-            //run update for each template field in displayed context
2345
-            if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2346
-                EE_Error::add_error(
2347
-                    __('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2348
-                        'event_espresso'),
2349
-                    __FILE__, __FUNCTION__, __LINE__
2350
-                );
2351
-                $success = 0;
2344
+			//run update for each template field in displayed context
2345
+			if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2346
+				EE_Error::add_error(
2347
+					__('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2348
+						'event_espresso'),
2349
+					__FILE__, __FUNCTION__, __LINE__
2350
+				);
2351
+				$success = 0;
2352 2352
                 
2353
-            } else {
2354
-                //first validate all fields!
2355
-                $validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2356
-                    $message_type_slug);
2353
+			} else {
2354
+				//first validate all fields!
2355
+				$validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2356
+					$message_type_slug);
2357 2357
                 
2358
-                //if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2359
-                if (is_array($validates) && ! empty($validates)) {
2360
-                    //add the transient so when the form loads we know which fields to highlight
2361
-                    $this->_add_transient('edit_message_template', $validates);
2358
+				//if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2359
+				if (is_array($validates) && ! empty($validates)) {
2360
+					//add the transient so when the form loads we know which fields to highlight
2361
+					$this->_add_transient('edit_message_template', $validates);
2362 2362
                     
2363
-                    $success = 0;
2363
+					$success = 0;
2364 2364
                     
2365
-                    //setup notices
2366
-                    foreach ($validates as $field => $error) {
2367
-                        if (isset($error['msg'])) {
2368
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2369
-                        }
2370
-                    }
2365
+					//setup notices
2366
+					foreach ($validates as $field => $error) {
2367
+						if (isset($error['msg'])) {
2368
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2369
+						}
2370
+					}
2371 2371
                     
2372
-                } else {
2373
-                    $set_column_values = array();
2374
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2375
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2372
+				} else {
2373
+					$set_column_values = array();
2374
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2375
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2376 2376
                         
2377
-                        $where_cols_n_values = array(
2378
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2379
-                        );
2377
+						$where_cols_n_values = array(
2378
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2379
+						);
2380 2380
                         
2381
-                        $message_template_fields = array(
2382
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2383
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2384
-                            'MTP_context'        => $set_column_values['MTP_context'],
2385
-                            'MTP_content'        => $set_column_values['MTP_content']
2386
-                        );
2387
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2388
-                            if ($updated === false) {
2389
-                                EE_Error::add_error(
2390
-                                    sprintf(
2391
-                                        __('%s field was NOT updated for some reason', 'event_espresso'),
2392
-                                        $template_field
2393
-                                    ),
2394
-                                    __FILE__, __FUNCTION__, __LINE__
2395
-                                );
2396
-                            } else {
2397
-                                $success = 1;
2398
-                            }
2399
-                        }
2400
-                        $action_desc = 'updated';
2401
-                    }
2381
+						$message_template_fields = array(
2382
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2383
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2384
+							'MTP_context'        => $set_column_values['MTP_context'],
2385
+							'MTP_content'        => $set_column_values['MTP_content']
2386
+						);
2387
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2388
+							if ($updated === false) {
2389
+								EE_Error::add_error(
2390
+									sprintf(
2391
+										__('%s field was NOT updated for some reason', 'event_espresso'),
2392
+										$template_field
2393
+									),
2394
+									__FILE__, __FUNCTION__, __LINE__
2395
+								);
2396
+							} else {
2397
+								$success = 1;
2398
+							}
2399
+						}
2400
+						$action_desc = 'updated';
2401
+					}
2402 2402
                     
2403
-                    //we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2404
-                    $mtpg_fields = array(
2405
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2406
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2407
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2408
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2409
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2410
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2411
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2412
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2413
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2414
-                            : '',
2415
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2416
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2417
-                            : ''
2418
-                    );
2403
+					//we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2404
+					$mtpg_fields = array(
2405
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2406
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2407
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2408
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2409
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2410
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2411
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2412
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2413
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2414
+							: '',
2415
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2416
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2417
+							: ''
2418
+					);
2419 2419
                     
2420
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2421
-                    $updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2420
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2421
+					$updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2422 2422
                     
2423
-                    if ($updated === false) {
2424
-                        EE_Error::add_error(
2425
-                            sprintf(
2426
-                                __('The Message Template Group (%d) was NOT updated for some reason', 'event_espresso'),
2427
-                                $set_column_values['GRP_ID']
2428
-                            ),
2429
-                            __FILE__, __FUNCTION__, __LINE__
2430
-                        );
2431
-                    } else {
2432
-                        //k now we need to ensure the template_pack and template_variation fields are set.
2433
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2434
-                            ? $this->_req_data['MTP_template_pack']
2435
-                            : 'default';
2423
+					if ($updated === false) {
2424
+						EE_Error::add_error(
2425
+							sprintf(
2426
+								__('The Message Template Group (%d) was NOT updated for some reason', 'event_espresso'),
2427
+								$set_column_values['GRP_ID']
2428
+							),
2429
+							__FILE__, __FUNCTION__, __LINE__
2430
+						);
2431
+					} else {
2432
+						//k now we need to ensure the template_pack and template_variation fields are set.
2433
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2434
+							? $this->_req_data['MTP_template_pack']
2435
+							: 'default';
2436 2436
                         
2437
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2438
-                            ? $this->_req_data['MTP_template_variation']
2439
-                            : 'default';
2437
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2438
+							? $this->_req_data['MTP_template_variation']
2439
+							: 'default';
2440 2440
                         
2441
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2442
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2443
-                            $mtpg_obj->set_template_pack_name($template_pack);
2444
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2445
-                        }
2446
-                        $success = 1;
2447
-                    }
2448
-                }
2449
-            }
2441
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2442
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2443
+							$mtpg_obj->set_template_pack_name($template_pack);
2444
+							$mtpg_obj->set_template_pack_variation($template_variation);
2445
+						}
2446
+						$success = 1;
2447
+					}
2448
+				}
2449
+			}
2450 2450
             
2451
-        }
2452
-        
2453
-        //we return things differently if doing ajax
2454
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2455
-            $this->_template_args['success'] = $success;
2456
-            $this->_template_args['error']   = ! $success ? true : false;
2457
-            $this->_template_args['content'] = '';
2458
-            $this->_template_args['data']    = array(
2459
-                'grpID'        => $edit_array['GRP_ID'],
2460
-                'templateName' => $edit_array['template_name']
2461
-            );
2462
-            if ($success) {
2463
-                EE_Error::overwrite_success();
2464
-                EE_Error::add_success(__('The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2465
-                    'event_espresso'));
2466
-            }
2451
+		}
2452
+        
2453
+		//we return things differently if doing ajax
2454
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2455
+			$this->_template_args['success'] = $success;
2456
+			$this->_template_args['error']   = ! $success ? true : false;
2457
+			$this->_template_args['content'] = '';
2458
+			$this->_template_args['data']    = array(
2459
+				'grpID'        => $edit_array['GRP_ID'],
2460
+				'templateName' => $edit_array['template_name']
2461
+			);
2462
+			if ($success) {
2463
+				EE_Error::overwrite_success();
2464
+				EE_Error::add_success(__('The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2465
+					'event_espresso'));
2466
+			}
2467 2467
             
2468
-            $this->_return_json();
2469
-        }
2470
-        
2471
-        
2472
-        //was a test send triggered?
2473
-        if (isset($this->_req_data['test_button'])) {
2474
-            EE_Error::overwrite_success();
2475
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2476
-            $override = true;
2477
-        }
2478
-        
2479
-        if (empty($query_args)) {
2480
-            $query_args = array(
2481
-                'id'      => $this->_req_data['GRP_ID'],
2482
-                'context' => $context_slug,
2483
-                'action'  => 'edit_message_template'
2484
-            );
2485
-        }
2486
-        
2487
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2488
-    }
2489
-    
2490
-    
2491
-    /**
2492
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2493
-     *
2494
-     * @param  string $context      what context being tested
2495
-     * @param  string $messenger    messenger being tested
2496
-     * @param  string $message_type message type being tested
2497
-     *
2498
-     */
2499
-    protected function _do_test_send($context, $messenger, $message_type)
2500
-    {
2501
-        //set things up for preview
2502
-        $this->_req_data['messenger']    = $messenger;
2503
-        $this->_req_data['message_type'] = $message_type;
2504
-        $this->_req_data['context']      = $context;
2505
-        $this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2506
-        $active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2507
-        
2508
-        //let's save any existing fields that might be required by the messenger
2509
-        if (
2510
-            isset($this->_req_data['test_settings_fld'])
2511
-            && $active_messenger instanceof EE_messenger
2512
-            && apply_filters(
2513
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2514
-                true,
2515
-                $this->_req_data['test_settings_fld'],
2516
-                $active_messenger
2517
-            )
2518
-        ) {
2519
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2520
-        }
2521
-        
2522
-        $success = $this->_preview_message(true);
2523
-        
2524
-        if ($success) {
2525
-            EE_Error::add_success(__('Test message sent', 'event_espresso'));
2526
-        } else {
2527
-            EE_Error::add_error(__('The test message was not sent', 'event_espresso'), __FILE__, __FUNCTION__,
2528
-                __LINE__);
2529
-        }
2530
-    }
2531
-    
2532
-    
2533
-    /**
2534
-     * _generate_new_templates
2535
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2536
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2537
-     * for the event.
2538
-     *
2539
-     *
2540
-     * @param  string $messenger     the messenger we are generating templates for
2541
-     * @param array   $message_types array of message types that the templates are generated for.
2542
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2543
-     *                               indicate the message_template_group being used as the base.
2544
-     *
2545
-     * @param bool    $global
2546
-     *
2547
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
2548
-     *                               encountering problems.
2549
-     * @throws \EE_Error
2550
-     */
2551
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2552
-    {
2553
-        
2554
-        //if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2555
-        if (empty($message_types)) {
2556
-            return true;
2557
-        }
2558
-        
2559
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2560
-    }
2561
-    
2562
-    
2563
-    /**
2564
-     * [_trash_or_restore_message_template]
2565
-     *
2566
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2567
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2568
-     *                        an individual context (FALSE).
2569
-     *
2570
-     * @return void
2571
-     */
2572
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
2573
-    {
2574
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2575
-        $MTP = EEM_Message_Template_Group::instance();
2576
-        
2577
-        $success = 1;
2578
-        
2579
-        //incoming GRP_IDs
2580
-        if ($all) {
2581
-            //Checkboxes
2582
-            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2583
-                //if array has more than one element then success message should be plural.
2584
-                //todo: what about nonce?
2585
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2468
+			$this->_return_json();
2469
+		}
2470
+        
2471
+        
2472
+		//was a test send triggered?
2473
+		if (isset($this->_req_data['test_button'])) {
2474
+			EE_Error::overwrite_success();
2475
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2476
+			$override = true;
2477
+		}
2478
+        
2479
+		if (empty($query_args)) {
2480
+			$query_args = array(
2481
+				'id'      => $this->_req_data['GRP_ID'],
2482
+				'context' => $context_slug,
2483
+				'action'  => 'edit_message_template'
2484
+			);
2485
+		}
2486
+        
2487
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2488
+	}
2489
+    
2490
+    
2491
+	/**
2492
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2493
+	 *
2494
+	 * @param  string $context      what context being tested
2495
+	 * @param  string $messenger    messenger being tested
2496
+	 * @param  string $message_type message type being tested
2497
+	 *
2498
+	 */
2499
+	protected function _do_test_send($context, $messenger, $message_type)
2500
+	{
2501
+		//set things up for preview
2502
+		$this->_req_data['messenger']    = $messenger;
2503
+		$this->_req_data['message_type'] = $message_type;
2504
+		$this->_req_data['context']      = $context;
2505
+		$this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2506
+		$active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2507
+        
2508
+		//let's save any existing fields that might be required by the messenger
2509
+		if (
2510
+			isset($this->_req_data['test_settings_fld'])
2511
+			&& $active_messenger instanceof EE_messenger
2512
+			&& apply_filters(
2513
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2514
+				true,
2515
+				$this->_req_data['test_settings_fld'],
2516
+				$active_messenger
2517
+			)
2518
+		) {
2519
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2520
+		}
2521
+        
2522
+		$success = $this->_preview_message(true);
2523
+        
2524
+		if ($success) {
2525
+			EE_Error::add_success(__('Test message sent', 'event_espresso'));
2526
+		} else {
2527
+			EE_Error::add_error(__('The test message was not sent', 'event_espresso'), __FILE__, __FUNCTION__,
2528
+				__LINE__);
2529
+		}
2530
+	}
2531
+    
2532
+    
2533
+	/**
2534
+	 * _generate_new_templates
2535
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2536
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2537
+	 * for the event.
2538
+	 *
2539
+	 *
2540
+	 * @param  string $messenger     the messenger we are generating templates for
2541
+	 * @param array   $message_types array of message types that the templates are generated for.
2542
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2543
+	 *                               indicate the message_template_group being used as the base.
2544
+	 *
2545
+	 * @param bool    $global
2546
+	 *
2547
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
2548
+	 *                               encountering problems.
2549
+	 * @throws \EE_Error
2550
+	 */
2551
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2552
+	{
2553
+        
2554
+		//if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2555
+		if (empty($message_types)) {
2556
+			return true;
2557
+		}
2558
+        
2559
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2560
+	}
2561
+    
2562
+    
2563
+	/**
2564
+	 * [_trash_or_restore_message_template]
2565
+	 *
2566
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2567
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2568
+	 *                        an individual context (FALSE).
2569
+	 *
2570
+	 * @return void
2571
+	 */
2572
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
2573
+	{
2574
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2575
+		$MTP = EEM_Message_Template_Group::instance();
2576
+        
2577
+		$success = 1;
2578
+        
2579
+		//incoming GRP_IDs
2580
+		if ($all) {
2581
+			//Checkboxes
2582
+			if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2583
+				//if array has more than one element then success message should be plural.
2584
+				//todo: what about nonce?
2585
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2586 2586
                 
2587
-                //cycle through checkboxes
2588
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2589
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2590
-                    if ( ! $trashed_or_restored) {
2591
-                        $success = 0;
2592
-                    }
2593
-                }
2594
-            } else {
2595
-                //grab single GRP_ID and handle
2596
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
2597
-                if ( ! empty($GRP_ID)) {
2598
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2599
-                    if ( ! $trashed_or_restored) {
2600
-                        $success = 0;
2601
-                    }
2602
-                } else {
2603
-                    $success = 0;
2604
-                }
2605
-            }
2587
+				//cycle through checkboxes
2588
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2589
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2590
+					if ( ! $trashed_or_restored) {
2591
+						$success = 0;
2592
+					}
2593
+				}
2594
+			} else {
2595
+				//grab single GRP_ID and handle
2596
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
2597
+				if ( ! empty($GRP_ID)) {
2598
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2599
+					if ( ! $trashed_or_restored) {
2600
+						$success = 0;
2601
+					}
2602
+				} else {
2603
+					$success = 0;
2604
+				}
2605
+			}
2606 2606
             
2607
-        }
2607
+		}
2608 2608
         
2609
-        $action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2609
+		$action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2610 2610
         
2611
-        $action_desc = ! empty($this->_req_data['template_switch']) ? __('switched') : $action_desc;
2611
+		$action_desc = ! empty($this->_req_data['template_switch']) ? __('switched') : $action_desc;
2612 2612
         
2613
-        $item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
2614
-            'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2613
+		$item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
2614
+			'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2615 2615
         
2616
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
2617
-            'event_espresso') : $item_desc;
2616
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
2617
+			'event_espresso') : $item_desc;
2618 2618
         
2619
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
2619
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
2620 2620
         
2621
-    }
2621
+	}
2622 2622
     
2623 2623
     
2624
-    /**
2625
-     * [_delete_message_template]
2626
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2627
-     * @return void
2628
-     */
2629
-    protected function _delete_message_template()
2630
-    {
2631
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2624
+	/**
2625
+	 * [_delete_message_template]
2626
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2627
+	 * @return void
2628
+	 */
2629
+	protected function _delete_message_template()
2630
+	{
2631
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2632 2632
         
2633
-        //checkboxes
2634
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2635
-            //if array has more than one element then success message should be plural
2636
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2633
+		//checkboxes
2634
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2635
+			//if array has more than one element then success message should be plural
2636
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2637 2637
             
2638
-            //cycle through bulk action checkboxes
2639
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2640
-                $success = $this->_delete_mtp_permanently($GRP_ID);
2641
-            }
2642
-        } else {
2643
-            //grab single grp_id and delete
2644
-            $GRP_ID  = absint($this->_req_data['id']);
2645
-            $success = $this->_delete_mtp_permanently($GRP_ID);
2646
-        }
2647
-        
2648
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
2649
-        
2650
-    }
2651
-    
2652
-    
2653
-    /**
2654
-     * helper for permanently deleting a mtP group and all related message_templates
2655
-     *
2656
-     * @param  int  $GRP_ID        The group being deleted
2657
-     * @param  bool $include_group whether to delete the Message Template Group as well.
2658
-     *
2659
-     * @return bool        boolean to indicate the success of the deletes or not.
2660
-     */
2661
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
2662
-    {
2663
-        $success = 1;
2664
-        $MTPG    = EEM_Message_Template_Group::instance();
2665
-        //first let's GET this group
2666
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
2667
-        //then delete permanently all the related Message Templates
2668
-        $deleted = $MTG->delete_related_permanently('Message_Template');
2669
-        
2670
-        if ($deleted === 0) {
2671
-            $success = 0;
2672
-        }
2673
-        
2674
-        //now delete permanently this particular group
2675
-        
2676
-        if ($include_group && ! $MTG->delete_permanently()) {
2677
-            $success = 0;
2678
-        }
2679
-        
2680
-        return $success;
2681
-    }
2682
-    
2683
-    
2684
-    /**
2685
-     *    _learn_more_about_message_templates_link
2686
-     * @access protected
2687
-     * @return string
2688
-     */
2689
-    protected function _learn_more_about_message_templates_link()
2690
-    {
2691
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2692
-            'event_espresso') . '</a>';
2693
-    }
2694
-    
2695
-    
2696
-    /**
2697
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2698
-     * ajax and other routes.
2699
-     * @return void
2700
-     */
2701
-    protected function _settings()
2702
-    {
2703
-        
2704
-        
2705
-        $this->_set_m_mt_settings();
2706
-        
2707
-        $selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2708
-        
2709
-        //let's setup the messenger tabs
2710
-        $this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links($this->_m_mt_settings['messenger_tabs'],
2711
-            'messenger_links', '|', $selected_messenger);
2712
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2713
-        $this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
2714
-        
2715
-        $this->display_admin_page_with_sidebar();
2716
-        
2717
-    }
2718
-    
2719
-    
2720
-    /**
2721
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2722
-     *
2723
-     * @access protected
2724
-     * @return void
2725
-     */
2726
-    protected function _set_m_mt_settings()
2727
-    {
2728
-        //first if this is already set then lets get out no need to regenerate data.
2729
-        if ( ! empty($this->_m_mt_settings)) {
2730
-            return;
2731
-        }
2732
-        
2733
-        //$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2734
-        
2735
-        //get all installed messengers and message_types
2736
-        /** @type EE_messenger[] $messengers */
2737
-        $messengers = $this->_message_resource_manager->installed_messengers();
2738
-        /** @type EE_message_type[] $message_types */
2739
-        $message_types = $this->_message_resource_manager->installed_message_types();
2740
-        
2741
-        
2742
-        //assemble the array for the _tab_text_links helper
2743
-        
2744
-        foreach ($messengers as $messenger) {
2745
-            $this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2746
-                'label' => ucwords($messenger->label['singular']),
2747
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name) ? 'messenger-active' : '',
2748
-                'href'  => $messenger->name,
2749
-                'title' => __('Modify this Messenger', 'event_espresso'),
2750
-                'slug'  => $messenger->name,
2751
-                'obj'   => $messenger
2752
-            );
2638
+			//cycle through bulk action checkboxes
2639
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2640
+				$success = $this->_delete_mtp_permanently($GRP_ID);
2641
+			}
2642
+		} else {
2643
+			//grab single grp_id and delete
2644
+			$GRP_ID  = absint($this->_req_data['id']);
2645
+			$success = $this->_delete_mtp_permanently($GRP_ID);
2646
+		}
2647
+        
2648
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
2649
+        
2650
+	}
2651
+    
2652
+    
2653
+	/**
2654
+	 * helper for permanently deleting a mtP group and all related message_templates
2655
+	 *
2656
+	 * @param  int  $GRP_ID        The group being deleted
2657
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
2658
+	 *
2659
+	 * @return bool        boolean to indicate the success of the deletes or not.
2660
+	 */
2661
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
2662
+	{
2663
+		$success = 1;
2664
+		$MTPG    = EEM_Message_Template_Group::instance();
2665
+		//first let's GET this group
2666
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
2667
+		//then delete permanently all the related Message Templates
2668
+		$deleted = $MTG->delete_related_permanently('Message_Template');
2669
+        
2670
+		if ($deleted === 0) {
2671
+			$success = 0;
2672
+		}
2673
+        
2674
+		//now delete permanently this particular group
2675
+        
2676
+		if ($include_group && ! $MTG->delete_permanently()) {
2677
+			$success = 0;
2678
+		}
2679
+        
2680
+		return $success;
2681
+	}
2682
+    
2683
+    
2684
+	/**
2685
+	 *    _learn_more_about_message_templates_link
2686
+	 * @access protected
2687
+	 * @return string
2688
+	 */
2689
+	protected function _learn_more_about_message_templates_link()
2690
+	{
2691
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2692
+			'event_espresso') . '</a>';
2693
+	}
2694
+    
2695
+    
2696
+	/**
2697
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2698
+	 * ajax and other routes.
2699
+	 * @return void
2700
+	 */
2701
+	protected function _settings()
2702
+	{
2703
+        
2704
+        
2705
+		$this->_set_m_mt_settings();
2706
+        
2707
+		$selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2708
+        
2709
+		//let's setup the messenger tabs
2710
+		$this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links($this->_m_mt_settings['messenger_tabs'],
2711
+			'messenger_links', '|', $selected_messenger);
2712
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2713
+		$this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
2714
+        
2715
+		$this->display_admin_page_with_sidebar();
2716
+        
2717
+	}
2718
+    
2719
+    
2720
+	/**
2721
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2722
+	 *
2723
+	 * @access protected
2724
+	 * @return void
2725
+	 */
2726
+	protected function _set_m_mt_settings()
2727
+	{
2728
+		//first if this is already set then lets get out no need to regenerate data.
2729
+		if ( ! empty($this->_m_mt_settings)) {
2730
+			return;
2731
+		}
2732
+        
2733
+		//$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2734
+        
2735
+		//get all installed messengers and message_types
2736
+		/** @type EE_messenger[] $messengers */
2737
+		$messengers = $this->_message_resource_manager->installed_messengers();
2738
+		/** @type EE_message_type[] $message_types */
2739
+		$message_types = $this->_message_resource_manager->installed_message_types();
2740
+        
2741
+        
2742
+		//assemble the array for the _tab_text_links helper
2743
+        
2744
+		foreach ($messengers as $messenger) {
2745
+			$this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2746
+				'label' => ucwords($messenger->label['singular']),
2747
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name) ? 'messenger-active' : '',
2748
+				'href'  => $messenger->name,
2749
+				'title' => __('Modify this Messenger', 'event_espresso'),
2750
+				'slug'  => $messenger->name,
2751
+				'obj'   => $messenger
2752
+			);
2753 2753
             
2754 2754
             
2755
-            $message_types_for_messenger = $messenger->get_valid_message_types();
2755
+			$message_types_for_messenger = $messenger->get_valid_message_types();
2756 2756
             
2757
-            foreach ($message_types as $message_type) {
2758
-                //first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2759
-                if ( ! in_array($message_type->name, $message_types_for_messenger)) {
2760
-                    continue;
2761
-                }
2757
+			foreach ($message_types as $message_type) {
2758
+				//first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2759
+				if ( ! in_array($message_type->name, $message_types_for_messenger)) {
2760
+					continue;
2761
+				}
2762 2762
                 
2763
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger($messenger->name,
2764
-                    $message_type->name) ? 'active' : 'inactive';
2763
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger($messenger->name,
2764
+					$message_type->name) ? 'active' : 'inactive';
2765 2765
                 
2766
-                $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2767
-                    'label'    => ucwords($message_type->label['singular']),
2768
-                    'class'    => 'message-type-' . $a_or_i,
2769
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2770
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2771
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2772
-                    'title'    => $a_or_i == 'active'
2773
-                        ? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2774
-                        : __('Drag this message type to the messenger to activate', 'event_espresso'),
2775
-                    'content'  => $a_or_i == 'active'
2776
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
2777
-                        : $this->_message_type_settings_content($message_type, $messenger),
2778
-                    'slug'     => $message_type->name,
2779
-                    'active'   => $a_or_i == 'active' ? true : false,
2780
-                    'obj'      => $message_type
2781
-                );
2782
-            }
2783
-        }
2784
-    }
2785
-    
2786
-    
2787
-    /**
2788
-     * This just prepares the content for the message type settings
2789
-     *
2790
-     * @param  object  $message_type The message type object
2791
-     * @param  object  $messenger    The messenger object
2792
-     * @param  boolean $active       Whether the message type is active or not
2793
-     *
2794
-     * @return string                html output for the content
2795
-     */
2796
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
2797
-    {
2798
-        //get message type fields
2799
-        $fields                                         = $message_type->get_admin_settings_fields();
2800
-        $settings_template_args['template_form_fields'] = '';
2801
-        
2802
-        if ( ! empty($fields) && $active) {
2766
+				$this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2767
+					'label'    => ucwords($message_type->label['singular']),
2768
+					'class'    => 'message-type-' . $a_or_i,
2769
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2770
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2771
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2772
+					'title'    => $a_or_i == 'active'
2773
+						? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2774
+						: __('Drag this message type to the messenger to activate', 'event_espresso'),
2775
+					'content'  => $a_or_i == 'active'
2776
+						? $this->_message_type_settings_content($message_type, $messenger, true)
2777
+						: $this->_message_type_settings_content($message_type, $messenger),
2778
+					'slug'     => $message_type->name,
2779
+					'active'   => $a_or_i == 'active' ? true : false,
2780
+					'obj'      => $message_type
2781
+				);
2782
+			}
2783
+		}
2784
+	}
2785
+    
2786
+    
2787
+	/**
2788
+	 * This just prepares the content for the message type settings
2789
+	 *
2790
+	 * @param  object  $message_type The message type object
2791
+	 * @param  object  $messenger    The messenger object
2792
+	 * @param  boolean $active       Whether the message type is active or not
2793
+	 *
2794
+	 * @return string                html output for the content
2795
+	 */
2796
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
2797
+	{
2798
+		//get message type fields
2799
+		$fields                                         = $message_type->get_admin_settings_fields();
2800
+		$settings_template_args['template_form_fields'] = '';
2801
+        
2802
+		if ( ! empty($fields) && $active) {
2803 2803
             
2804
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2804
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2805 2805
             
2806
-            foreach ($fields as $fldname => $fldprops) {
2807
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2808
-                $template_form_field[$field_id] = array(
2809
-                    'name'       => 'message_type_settings[' . $fldname . ']',
2810
-                    'label'      => $fldprops['label'],
2811
-                    'input'      => $fldprops['field_type'],
2812
-                    'type'       => $fldprops['value_type'],
2813
-                    'required'   => $fldprops['required'],
2814
-                    'validation' => $fldprops['validation'],
2815
-                    'value'      => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2816
-                    'options'    => isset($fldprops['options']) ? $fldprops['options'] : array(),
2817
-                    'default'    => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2818
-                    'css_class'  => 'no-drag',
2819
-                    'format'     => $fldprops['format']
2820
-                );
2821
-            }
2806
+			foreach ($fields as $fldname => $fldprops) {
2807
+				$field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2808
+				$template_form_field[$field_id] = array(
2809
+					'name'       => 'message_type_settings[' . $fldname . ']',
2810
+					'label'      => $fldprops['label'],
2811
+					'input'      => $fldprops['field_type'],
2812
+					'type'       => $fldprops['value_type'],
2813
+					'required'   => $fldprops['required'],
2814
+					'validation' => $fldprops['validation'],
2815
+					'value'      => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2816
+					'options'    => isset($fldprops['options']) ? $fldprops['options'] : array(),
2817
+					'default'    => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2818
+					'css_class'  => 'no-drag',
2819
+					'format'     => $fldprops['format']
2820
+				);
2821
+			}
2822 2822
             
2823 2823
             
2824
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field) ? $this->_generate_admin_form_fields($template_form_field,
2825
-                'string', 'ee_mt_activate_form') : '';
2826
-        }
2827
-        
2828
-        $settings_template_args['description'] = $message_type->description;
2829
-        //we also need some hidden fields
2830
-        $settings_template_args['hidden_fields'] = array(
2831
-            'message_type_settings[messenger]'    => array(
2832
-                'type'  => 'hidden',
2833
-                'value' => $messenger->name
2834
-            ),
2835
-            'message_type_settings[message_type]' => array(
2836
-                'type'  => 'hidden',
2837
-                'value' => $message_type->name
2838
-            ),
2839
-            'type'                                => array(
2840
-                'type'  => 'hidden',
2841
-                'value' => 'message_type'
2842
-            )
2843
-        );
2844
-        
2845
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields($settings_template_args['hidden_fields'],
2846
-            'array');
2847
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2848
-        
2849
-        
2850
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2851
-        $content  = EEH_Template::display_template($template, $settings_template_args, true);
2852
-        
2853
-        return $content;
2854
-    }
2855
-    
2856
-    
2857
-    /**
2858
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
2859
-     *
2860
-     * @access protected
2861
-     * @return void
2862
-     */
2863
-    protected function _messages_settings_metaboxes()
2864
-    {
2865
-        $this->_set_m_mt_settings();
2866
-        $m_boxes         = $mt_boxes = array();
2867
-        $m_template_args = $mt_template_args = array();
2868
-        
2869
-        $selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2870
-        
2871
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
2872
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
2873
-                $hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
2874
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
2875
-                //messenger meta boxes
2876
-                $active                                 = $selected_messenger == $messenger ? true : false;
2877
-                $active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2878
-                    ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2879
-                    : '';
2880
-                $m_boxes[$messenger . '_a_box']         = sprintf(
2881
-                    __('%s Settings', 'event_espresso'),
2882
-                    $tab_array['label']
2883
-                );
2884
-                $m_template_args[$messenger . '_a_box'] = array(
2885
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2886
-                    'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2887
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2888
-                        : '',
2889
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
2890
-                    'hidden'                 => $active ? '' : ' hidden',
2891
-                    'hide_on_message'        => $hide_on_message,
2892
-                    'messenger'              => $messenger,
2893
-                    'active'                 => $active
2894
-                );
2895
-                // message type meta boxes
2896
-                // (which is really just the inactive container for each messenger
2897
-                // showing inactive message types for that messenger)
2898
-                $mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2899
-                $mt_template_args[$messenger . '_i_box'] = array(
2900
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2901
-                    'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2902
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2903
-                        : '',
2904
-                    'hidden'                 => $active ? '' : ' hidden',
2905
-                    'hide_on_message'        => $hide_on_message,
2906
-                    'hide_off_message'       => $hide_off_message,
2907
-                    'messenger'              => $messenger,
2908
-                    'active'                 => $active
2909
-                );
2910
-            }
2911
-        }
2912
-        
2913
-        
2914
-        //register messenger metaboxes
2915
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2916
-        foreach ($m_boxes as $box => $label) {
2917
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2918
-            $msgr          = str_replace('_a_box', '', $box);
2919
-            add_meta_box(
2920
-                'espresso_' . $msgr . '_settings',
2921
-                $label,
2922
-                function ($post, $metabox) {
2923
-                    echo EEH_Template::display_template($metabox["args"]["template_path"],
2924
-                        $metabox["args"]["template_args"], true);
2925
-                },
2926
-                $this->_current_screen->id,
2927
-                'normal',
2928
-                'high',
2929
-                $callback_args
2930
-            );
2931
-        }
2932
-        
2933
-        //register message type metaboxes
2934
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2935
-        foreach ($mt_boxes as $box => $label) {
2936
-            $callback_args = array(
2937
-                'template_path' => $mt_template_path,
2938
-                'template_args' => $mt_template_args[$box]
2939
-            );
2940
-            $mt            = str_replace('_i_box', '', $box);
2941
-            add_meta_box(
2942
-                'espresso_' . $mt . '_inactive_mts',
2943
-                $label,
2944
-                function ($post, $metabox) {
2945
-                    echo EEH_Template::display_template($metabox["args"]["template_path"],
2946
-                        $metabox["args"]["template_args"], true);
2947
-                },
2948
-                $this->_current_screen->id,
2949
-                'side',
2950
-                'high',
2951
-                $callback_args
2952
-            );
2953
-        }
2954
-        
2955
-        //register metabox for global messages settings but only when on the main site.  On single site installs this will
2956
-        //always result in the metabox showing, on multisite installs the metabox will only show on the main site.
2957
-        if (is_main_site()) {
2958
-            add_meta_box(
2959
-                'espresso_global_message_settings',
2960
-                __('Global Message Settings', 'event_espresso'),
2961
-                array($this, 'global_messages_settings_metabox_content'),
2962
-                $this->_current_screen->id,
2963
-                'normal',
2964
-                'low',
2965
-                array()
2966
-            );
2967
-        }
2968
-        
2969
-    }
2970
-    
2971
-    
2972
-    /**
2973
-     *  This generates the content for the global messages settings metabox.
2974
-     * @return string
2975
-     */
2976
-    public function global_messages_settings_metabox_content()
2977
-    {
2978
-        $form = $this->_generate_global_settings_form();
2979
-        echo $form->form_open(
2980
-                $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
2981
-                'POST'
2982
-            )
2983
-             . $form->get_html()
2984
-             . $form->form_close();
2985
-    }
2986
-    
2987
-    
2988
-    /**
2989
-     * This generates and returns the form object for the global messages settings.
2990
-     * @return EE_Form_Section_Proper
2991
-     */
2992
-    protected function _generate_global_settings_form()
2993
-    {
2994
-        EE_Registry::instance()->load_helper('HTML');
2995
-        /** @var EE_Network_Core_Config $network_config */
2996
-        $network_config = EE_Registry::instance()->NET_CFG->core;
2997
-        
2998
-        return new EE_Form_Section_Proper(
2999
-            array(
3000
-                'name'            => 'global_messages_settings',
3001
-                'html_id'         => 'global_messages_settings',
3002
-                'html_class'      => 'form-table',
3003
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3004
-                'subsections'     => apply_filters(
3005
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3006
-                    array(
3007
-                        'do_messages_on_same_request' => new EE_Select_Input(
3008
-                            array(
3009
-                                true  => __("On the same request", "event_espresso"),
3010
-                                false => __("On a separate request", "event_espresso")
3011
-                            ),
3012
-                            array(
3013
-                                'default'         => $network_config->do_messages_on_same_request,
3014
-                                'html_label_text' => __('Generate and send all messages:', 'event_espresso'),
3015
-                                'html_help_text'  => __('By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3016
-                                    'event_espresso'),
3017
-                            )
3018
-                        ),
3019
-                        'update_settings'             => new EE_Submit_Input(
3020
-                            array(
3021
-                                'default'         => __('Update', 'event_espresso'),
3022
-                                'html_label_text' => '&nbsp'
3023
-                            )
3024
-                        )
3025
-                    )
3026
-                )
3027
-            )
3028
-        );
3029
-    }
3030
-    
3031
-    
3032
-    /**
3033
-     * This handles updating the global settings set on the admin page.
3034
-     * @throws \EE_Error
3035
-     */
3036
-    protected function _update_global_settings()
3037
-    {
3038
-        /** @var EE_Network_Core_Config $network_config */
3039
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3040
-        $form           = $this->_generate_global_settings_form();
3041
-        if ($form->was_submitted()) {
3042
-            $form->receive_form_submission();
3043
-            if ($form->is_valid()) {
3044
-                $valid_data = $form->valid_data();
3045
-                foreach ($valid_data as $property => $value) {
3046
-                    $setter = 'set_' . $property;
3047
-                    if (method_exists($network_config, $setter)) {
3048
-                        $network_config->{$setter}($value);
3049
-                    } else if (
3050
-                        property_exists($network_config, $property)
3051
-                        && $network_config->{$property} !== $value
3052
-                    ) {
3053
-                        $network_config->{$property} = $value;
3054
-                    }
3055
-                }
3056
-                //only update if the form submission was valid!
3057
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3058
-                EE_Error::overwrite_success();
3059
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3060
-            }
3061
-        }
3062
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3063
-    }
3064
-    
3065
-    
3066
-    /**
3067
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3068
-     *
3069
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3070
-     *
3071
-     * @return string            html formatted tabs
3072
-     */
3073
-    protected function _get_mt_tabs($tab_array)
3074
-    {
3075
-        $tab_array = (array)$tab_array;
3076
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3077
-        $tabs      = '';
3078
-        
3079
-        foreach ($tab_array as $tab) {
3080
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3081
-        }
3082
-        
3083
-        return $tabs;
3084
-    }
3085
-    
3086
-    
3087
-    /**
3088
-     * This prepares the content of the messenger meta box admin settings
3089
-     *
3090
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3091
-     *
3092
-     * @return string            html formatted content
3093
-     */
3094
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3095
-    {
3096
-        
3097
-        $fields                                         = $messenger->get_admin_settings_fields();
3098
-        $settings_template_args['template_form_fields'] = '';
3099
-        
3100
-        //is $messenger active?
3101
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3102
-        
3103
-        
3104
-        if ( ! empty($fields)) {
2824
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field) ? $this->_generate_admin_form_fields($template_form_field,
2825
+				'string', 'ee_mt_activate_form') : '';
2826
+		}
2827
+        
2828
+		$settings_template_args['description'] = $message_type->description;
2829
+		//we also need some hidden fields
2830
+		$settings_template_args['hidden_fields'] = array(
2831
+			'message_type_settings[messenger]'    => array(
2832
+				'type'  => 'hidden',
2833
+				'value' => $messenger->name
2834
+			),
2835
+			'message_type_settings[message_type]' => array(
2836
+				'type'  => 'hidden',
2837
+				'value' => $message_type->name
2838
+			),
2839
+			'type'                                => array(
2840
+				'type'  => 'hidden',
2841
+				'value' => 'message_type'
2842
+			)
2843
+		);
2844
+        
2845
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields($settings_template_args['hidden_fields'],
2846
+			'array');
2847
+		$settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2848
+        
2849
+        
2850
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2851
+		$content  = EEH_Template::display_template($template, $settings_template_args, true);
2852
+        
2853
+		return $content;
2854
+	}
2855
+    
2856
+    
2857
+	/**
2858
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
2859
+	 *
2860
+	 * @access protected
2861
+	 * @return void
2862
+	 */
2863
+	protected function _messages_settings_metaboxes()
2864
+	{
2865
+		$this->_set_m_mt_settings();
2866
+		$m_boxes         = $mt_boxes = array();
2867
+		$m_template_args = $mt_template_args = array();
2868
+        
2869
+		$selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2870
+        
2871
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
2872
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
2873
+				$hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
2874
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
2875
+				//messenger meta boxes
2876
+				$active                                 = $selected_messenger == $messenger ? true : false;
2877
+				$active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2878
+					? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2879
+					: '';
2880
+				$m_boxes[$messenger . '_a_box']         = sprintf(
2881
+					__('%s Settings', 'event_espresso'),
2882
+					$tab_array['label']
2883
+				);
2884
+				$m_template_args[$messenger . '_a_box'] = array(
2885
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2886
+					'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2887
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2888
+						: '',
2889
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
2890
+					'hidden'                 => $active ? '' : ' hidden',
2891
+					'hide_on_message'        => $hide_on_message,
2892
+					'messenger'              => $messenger,
2893
+					'active'                 => $active
2894
+				);
2895
+				// message type meta boxes
2896
+				// (which is really just the inactive container for each messenger
2897
+				// showing inactive message types for that messenger)
2898
+				$mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2899
+				$mt_template_args[$messenger . '_i_box'] = array(
2900
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2901
+					'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2902
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2903
+						: '',
2904
+					'hidden'                 => $active ? '' : ' hidden',
2905
+					'hide_on_message'        => $hide_on_message,
2906
+					'hide_off_message'       => $hide_off_message,
2907
+					'messenger'              => $messenger,
2908
+					'active'                 => $active
2909
+				);
2910
+			}
2911
+		}
2912
+        
2913
+        
2914
+		//register messenger metaboxes
2915
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2916
+		foreach ($m_boxes as $box => $label) {
2917
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2918
+			$msgr          = str_replace('_a_box', '', $box);
2919
+			add_meta_box(
2920
+				'espresso_' . $msgr . '_settings',
2921
+				$label,
2922
+				function ($post, $metabox) {
2923
+					echo EEH_Template::display_template($metabox["args"]["template_path"],
2924
+						$metabox["args"]["template_args"], true);
2925
+				},
2926
+				$this->_current_screen->id,
2927
+				'normal',
2928
+				'high',
2929
+				$callback_args
2930
+			);
2931
+		}
2932
+        
2933
+		//register message type metaboxes
2934
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2935
+		foreach ($mt_boxes as $box => $label) {
2936
+			$callback_args = array(
2937
+				'template_path' => $mt_template_path,
2938
+				'template_args' => $mt_template_args[$box]
2939
+			);
2940
+			$mt            = str_replace('_i_box', '', $box);
2941
+			add_meta_box(
2942
+				'espresso_' . $mt . '_inactive_mts',
2943
+				$label,
2944
+				function ($post, $metabox) {
2945
+					echo EEH_Template::display_template($metabox["args"]["template_path"],
2946
+						$metabox["args"]["template_args"], true);
2947
+				},
2948
+				$this->_current_screen->id,
2949
+				'side',
2950
+				'high',
2951
+				$callback_args
2952
+			);
2953
+		}
2954
+        
2955
+		//register metabox for global messages settings but only when on the main site.  On single site installs this will
2956
+		//always result in the metabox showing, on multisite installs the metabox will only show on the main site.
2957
+		if (is_main_site()) {
2958
+			add_meta_box(
2959
+				'espresso_global_message_settings',
2960
+				__('Global Message Settings', 'event_espresso'),
2961
+				array($this, 'global_messages_settings_metabox_content'),
2962
+				$this->_current_screen->id,
2963
+				'normal',
2964
+				'low',
2965
+				array()
2966
+			);
2967
+		}
2968
+        
2969
+	}
2970
+    
2971
+    
2972
+	/**
2973
+	 *  This generates the content for the global messages settings metabox.
2974
+	 * @return string
2975
+	 */
2976
+	public function global_messages_settings_metabox_content()
2977
+	{
2978
+		$form = $this->_generate_global_settings_form();
2979
+		echo $form->form_open(
2980
+				$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
2981
+				'POST'
2982
+			)
2983
+			 . $form->get_html()
2984
+			 . $form->form_close();
2985
+	}
2986
+    
2987
+    
2988
+	/**
2989
+	 * This generates and returns the form object for the global messages settings.
2990
+	 * @return EE_Form_Section_Proper
2991
+	 */
2992
+	protected function _generate_global_settings_form()
2993
+	{
2994
+		EE_Registry::instance()->load_helper('HTML');
2995
+		/** @var EE_Network_Core_Config $network_config */
2996
+		$network_config = EE_Registry::instance()->NET_CFG->core;
2997
+        
2998
+		return new EE_Form_Section_Proper(
2999
+			array(
3000
+				'name'            => 'global_messages_settings',
3001
+				'html_id'         => 'global_messages_settings',
3002
+				'html_class'      => 'form-table',
3003
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3004
+				'subsections'     => apply_filters(
3005
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3006
+					array(
3007
+						'do_messages_on_same_request' => new EE_Select_Input(
3008
+							array(
3009
+								true  => __("On the same request", "event_espresso"),
3010
+								false => __("On a separate request", "event_espresso")
3011
+							),
3012
+							array(
3013
+								'default'         => $network_config->do_messages_on_same_request,
3014
+								'html_label_text' => __('Generate and send all messages:', 'event_espresso'),
3015
+								'html_help_text'  => __('By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3016
+									'event_espresso'),
3017
+							)
3018
+						),
3019
+						'update_settings'             => new EE_Submit_Input(
3020
+							array(
3021
+								'default'         => __('Update', 'event_espresso'),
3022
+								'html_label_text' => '&nbsp'
3023
+							)
3024
+						)
3025
+					)
3026
+				)
3027
+			)
3028
+		);
3029
+	}
3030
+    
3031
+    
3032
+	/**
3033
+	 * This handles updating the global settings set on the admin page.
3034
+	 * @throws \EE_Error
3035
+	 */
3036
+	protected function _update_global_settings()
3037
+	{
3038
+		/** @var EE_Network_Core_Config $network_config */
3039
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3040
+		$form           = $this->_generate_global_settings_form();
3041
+		if ($form->was_submitted()) {
3042
+			$form->receive_form_submission();
3043
+			if ($form->is_valid()) {
3044
+				$valid_data = $form->valid_data();
3045
+				foreach ($valid_data as $property => $value) {
3046
+					$setter = 'set_' . $property;
3047
+					if (method_exists($network_config, $setter)) {
3048
+						$network_config->{$setter}($value);
3049
+					} else if (
3050
+						property_exists($network_config, $property)
3051
+						&& $network_config->{$property} !== $value
3052
+					) {
3053
+						$network_config->{$property} = $value;
3054
+					}
3055
+				}
3056
+				//only update if the form submission was valid!
3057
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3058
+				EE_Error::overwrite_success();
3059
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3060
+			}
3061
+		}
3062
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3063
+	}
3064
+    
3065
+    
3066
+	/**
3067
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3068
+	 *
3069
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3070
+	 *
3071
+	 * @return string            html formatted tabs
3072
+	 */
3073
+	protected function _get_mt_tabs($tab_array)
3074
+	{
3075
+		$tab_array = (array)$tab_array;
3076
+		$template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3077
+		$tabs      = '';
3078
+        
3079
+		foreach ($tab_array as $tab) {
3080
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3081
+		}
3082
+        
3083
+		return $tabs;
3084
+	}
3085
+    
3086
+    
3087
+	/**
3088
+	 * This prepares the content of the messenger meta box admin settings
3089
+	 *
3090
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3091
+	 *
3092
+	 * @return string            html formatted content
3093
+	 */
3094
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3095
+	{
3096
+        
3097
+		$fields                                         = $messenger->get_admin_settings_fields();
3098
+		$settings_template_args['template_form_fields'] = '';
3099
+        
3100
+		//is $messenger active?
3101
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3102
+        
3103
+        
3104
+		if ( ! empty($fields)) {
3105 3105
             
3106
-            $existing_settings = $messenger->get_existing_admin_settings();
3106
+			$existing_settings = $messenger->get_existing_admin_settings();
3107 3107
             
3108
-            foreach ($fields as $fldname => $fldprops) {
3109
-                $field_id                       = $messenger->name . '-' . $fldname;
3110
-                $template_form_field[$field_id] = array(
3111
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3112
-                    'label'      => $fldprops['label'],
3113
-                    'input'      => $fldprops['field_type'],
3114
-                    'type'       => $fldprops['value_type'],
3115
-                    'required'   => $fldprops['required'],
3116
-                    'validation' => $fldprops['validation'],
3117
-                    'value'      => isset($existing_settings[$field_id])
3118
-                        ? $existing_settings[$field_id]
3119
-                        : $fldprops['default'],
3120
-                    'css_class'  => '',
3121
-                    'format'     => $fldprops['format']
3122
-                );
3123
-            }
3108
+			foreach ($fields as $fldname => $fldprops) {
3109
+				$field_id                       = $messenger->name . '-' . $fldname;
3110
+				$template_form_field[$field_id] = array(
3111
+					'name'       => 'messenger_settings[' . $field_id . ']',
3112
+					'label'      => $fldprops['label'],
3113
+					'input'      => $fldprops['field_type'],
3114
+					'type'       => $fldprops['value_type'],
3115
+					'required'   => $fldprops['required'],
3116
+					'validation' => $fldprops['validation'],
3117
+					'value'      => isset($existing_settings[$field_id])
3118
+						? $existing_settings[$field_id]
3119
+						: $fldprops['default'],
3120
+					'css_class'  => '',
3121
+					'format'     => $fldprops['format']
3122
+				);
3123
+			}
3124 3124
             
3125 3125
             
3126
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3127
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3128
-                : '';
3129
-        }
3130
-        
3131
-        //we also need some hidden fields
3132
-        $settings_template_args['hidden_fields'] = array(
3133
-            'messenger_settings[messenger]' => array(
3134
-                'type'  => 'hidden',
3135
-                'value' => $messenger->name
3136
-            ),
3137
-            'type'                          => array(
3138
-                'type'  => 'hidden',
3139
-                'value' => 'messenger'
3140
-            )
3141
-        );
3142
-        
3143
-        //make sure any active message types that are existing are included in the hidden fields
3144
-        if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3145
-            foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3146
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3147
-                    'type'  => 'hidden',
3148
-                    'value' => $mt
3149
-                );
3150
-            }
3151
-        }
3152
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3153
-            $settings_template_args['hidden_fields'],
3154
-            'array'
3155
-        );
3156
-        $active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3157
-        
3158
-        $settings_template_args['messenger']           = $messenger->name;
3159
-        $settings_template_args['description']         = $messenger->description;
3160
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3161
-        
3162
-        
3163
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active($messenger->name)
3164
-            ? $settings_template_args['show_hide_edit_form']
3165
-            : ' hidden';
3166
-        
3167
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3168
-            ? ' hidden'
3169
-            : $settings_template_args['show_hide_edit_form'];
3170
-        
3171
-        
3172
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3173
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3174
-        $settings_template_args['on_off_status'] = $active ? true : false;
3175
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3176
-        $content                                 = EEH_Template::display_template($template, $settings_template_args,
3177
-            true);
3178
-        
3179
-        return $content;
3180
-    }
3181
-    
3182
-    
3183
-    /**
3184
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3185
-     */
3186
-    public function activate_messenger_toggle()
3187
-    {
3188
-        $success = true;
3189
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3190
-        //let's check that we have required data
3191
-        if ( ! isset($this->_req_data['messenger'])) {
3192
-            EE_Error::add_error(
3193
-                __('Messenger name needed to toggle activation. None given', 'event_espresso'),
3194
-                __FILE__,
3195
-                __FUNCTION__,
3196
-                __LINE__
3197
-            );
3198
-            $success = false;
3199
-        }
3200
-        
3201
-        //do a nonce check here since we're not arriving via a normal route
3202
-        $nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3203
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3204
-        
3205
-        $this->_verify_nonce($nonce, $nonce_ref);
3206
-        
3207
-        
3208
-        if ( ! isset($this->_req_data['status'])) {
3209
-            EE_Error::add_error(
3210
-                __(
3211
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3212
-                    'event_espresso'
3213
-                ),
3214
-                __FILE__,
3215
-                __FUNCTION__,
3216
-                __LINE__
3217
-            );
3218
-            $success = false;
3219
-        }
3220
-        
3221
-        //do check to verify we have a valid status.
3222
-        $status = $this->_req_data['status'];
3223
-        
3224
-        if ($status != 'off' && $status != 'on') {
3225
-            EE_Error::add_error(
3226
-                sprintf(
3227
-                    __('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3228
-                    $this->_req_data['status']
3229
-                ),
3230
-                __FILE__,
3231
-                __FUNCTION__,
3232
-                __LINE__
3233
-            );
3234
-            $success = false;
3235
-        }
3236
-        
3237
-        if ($success) {
3238
-            //made it here?  Stop dawdling then!!
3239
-            $success = $status == 'off'
3240
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3241
-                : $this->_activate_messenger($this->_req_data['messenger']);
3242
-        }
3243
-        
3244
-        $this->_template_args['success'] = $success;
3245
-        
3246
-        //no special instructions so let's just do the json return (which should automatically do all the special stuff).
3247
-        $this->_return_json();
3248
-        
3249
-    }
3250
-    
3251
-    
3252
-    /**
3253
-     * used by ajax from the messages settings page to activate|deactivate a message type
3254
-     *
3255
-     */
3256
-    public function activate_mt_toggle()
3257
-    {
3258
-        $success = true;
3259
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3260
-        
3261
-        //let's make sure we have the necessary data
3262
-        if ( ! isset($this->_req_data['message_type'])) {
3263
-            EE_Error::add_error(
3264
-                __('Message Type name needed to toggle activation. None given', 'event_espresso'),
3265
-                __FILE__, __FUNCTION__, __LINE__
3266
-            );
3267
-            $success = false;
3268
-        }
3269
-        
3270
-        if ( ! isset($this->_req_data['messenger'])) {
3271
-            EE_Error::add_error(
3272
-                __('Messenger name needed to toggle activation. None given', 'event_espresso'),
3273
-                __FILE__, __FUNCTION__, __LINE__
3274
-            );
3275
-            $success = false;
3276
-        }
3277
-        
3278
-        if ( ! isset($this->_req_data['status'])) {
3279
-            EE_Error::add_error(
3280
-                __('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3281
-                    'event_espresso'),
3282
-                __FILE__, __FUNCTION__, __LINE__
3283
-            );
3284
-            $success = false;
3285
-        }
3286
-        
3287
-        
3288
-        //do check to verify we have a valid status.
3289
-        $status = $this->_req_data['status'];
3290
-        
3291
-        if ($status != 'activate' && $status != 'deactivate') {
3292
-            EE_Error::add_error(
3293
-                sprintf(
3294
-                    __('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3295
-                    $this->_req_data['status']
3296
-                ),
3297
-                __FILE__, __FUNCTION__, __LINE__
3298
-            );
3299
-            $success = false;
3300
-        }
3301
-        
3302
-        
3303
-        //do a nonce check here since we're not arriving via a normal route
3304
-        $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3305
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3306
-        
3307
-        $this->_verify_nonce($nonce, $nonce_ref);
3308
-        
3309
-        if ($success) {
3310
-            //made it here? um, what are you waiting for then?
3311
-            $success = $status == 'deactivate'
3312
-                ? $this->_deactivate_message_type_for_messenger($this->_req_data['messenger'],
3313
-                    $this->_req_data['message_type'])
3314
-                : $this->_activate_message_type_for_messenger($this->_req_data['messenger'],
3315
-                    $this->_req_data['message_type']);
3316
-        }
3317
-        
3318
-        $this->_template_args['success'] = $success;
3319
-        $this->_return_json();
3320
-    }
3321
-    
3322
-    
3323
-    /**
3324
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3325
-     *
3326
-     * @param string $messenger_name The name of the messenger being activated
3327
-     *
3328
-     * @return bool
3329
-     */
3330
-    protected function _activate_messenger($messenger_name)
3331
-    {
3332
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3333
-        $active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3334
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3335
-        
3336
-        //ensure is active
3337
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3338
-        
3339
-        //set response_data for reload
3340
-        foreach ($message_types_to_activate as $message_type_name) {
3341
-            /** @var EE_message_type $message_type */
3342
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3343
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3344
-                    $message_type_name)
3345
-                && $message_type instanceof EE_message_type
3346
-            ) {
3347
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
3348
-                if ($message_type->get_admin_settings_fields()) {
3349
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
3350
-                }
3351
-            }
3352
-        }
3353
-        
3354
-        //add success message for activating messenger
3355
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3356
-        
3357
-    }
3358
-    
3359
-    
3360
-    /**
3361
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
3362
-     *
3363
-     * @param string $messenger_name The name of the messenger being activated
3364
-     *
3365
-     * @return bool
3366
-     */
3367
-    protected function _deactivate_messenger($messenger_name)
3368
-    {
3369
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3370
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3371
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
3372
-        
3373
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3374
-    }
3375
-    
3376
-    
3377
-    /**
3378
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3379
-     *
3380
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
3381
-     * @param string $message_type_name The name of the message type being activated for the messenger
3382
-     *
3383
-     * @return bool
3384
-     */
3385
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3386
-    {
3387
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3388
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3389
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3390
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3391
-        
3392
-        //ensure is active
3393
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3394
-        
3395
-        //set response for load
3396
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3397
-            $message_type_name)
3398
-        ) {
3399
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
3400
-            if ($message_type_to_activate->get_admin_settings_fields()) {
3401
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
3402
-            }
3403
-        }
3404
-        
3405
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3406
-            $message_type_to_activate);
3407
-    }
3408
-    
3409
-    
3410
-    /**
3411
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3412
-     *
3413
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3414
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
3415
-     *
3416
-     * @return bool
3417
-     */
3418
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
3419
-    {
3420
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3421
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3422
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3423
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
3424
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
3425
-        
3426
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
3427
-            $message_type_to_deactivate);
3428
-    }
3429
-    
3430
-    
3431
-    /**
3432
-     * This just initializes the defaults for activating messenger and message type responses.
3433
-     */
3434
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
3435
-    {
3436
-        $this->_template_args['data']['active_mts'] = array();
3437
-        $this->_template_args['data']['mt_reload']  = array();
3438
-    }
3439
-    
3440
-    
3441
-    /**
3442
-     * Setup appropriate response for activating a messenger and/or message types
3443
-     *
3444
-     * @param EE_messenger         $messenger
3445
-     * @param EE_message_type|null $message_type
3446
-     *
3447
-     * @return bool
3448
-     * @throws EE_Error
3449
-     */
3450
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
3451
-        $messenger,
3452
-        EE_Message_Type $message_type = null
3453
-    ) {
3454
-        //if $messenger isn't a valid messenger object then get out.
3455
-        if ( ! $messenger instanceof EE_Messenger) {
3456
-            EE_Error::add_error(
3457
-                __('The messenger being activated is not a valid messenger', 'event_espresso'),
3458
-                __FILE__,
3459
-                __FUNCTION__,
3460
-                __LINE__
3461
-            );
3126
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3127
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3128
+				: '';
3129
+		}
3130
+        
3131
+		//we also need some hidden fields
3132
+		$settings_template_args['hidden_fields'] = array(
3133
+			'messenger_settings[messenger]' => array(
3134
+				'type'  => 'hidden',
3135
+				'value' => $messenger->name
3136
+			),
3137
+			'type'                          => array(
3138
+				'type'  => 'hidden',
3139
+				'value' => 'messenger'
3140
+			)
3141
+		);
3142
+        
3143
+		//make sure any active message types that are existing are included in the hidden fields
3144
+		if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3145
+			foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3146
+				$settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3147
+					'type'  => 'hidden',
3148
+					'value' => $mt
3149
+				);
3150
+			}
3151
+		}
3152
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3153
+			$settings_template_args['hidden_fields'],
3154
+			'array'
3155
+		);
3156
+		$active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3157
+        
3158
+		$settings_template_args['messenger']           = $messenger->name;
3159
+		$settings_template_args['description']         = $messenger->description;
3160
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3161
+        
3162
+        
3163
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active($messenger->name)
3164
+			? $settings_template_args['show_hide_edit_form']
3165
+			: ' hidden';
3166
+        
3167
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3168
+			? ' hidden'
3169
+			: $settings_template_args['show_hide_edit_form'];
3170
+        
3171
+        
3172
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3173
+		$settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3174
+		$settings_template_args['on_off_status'] = $active ? true : false;
3175
+		$template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3176
+		$content                                 = EEH_Template::display_template($template, $settings_template_args,
3177
+			true);
3178
+        
3179
+		return $content;
3180
+	}
3181
+    
3182
+    
3183
+	/**
3184
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3185
+	 */
3186
+	public function activate_messenger_toggle()
3187
+	{
3188
+		$success = true;
3189
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3190
+		//let's check that we have required data
3191
+		if ( ! isset($this->_req_data['messenger'])) {
3192
+			EE_Error::add_error(
3193
+				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3194
+				__FILE__,
3195
+				__FUNCTION__,
3196
+				__LINE__
3197
+			);
3198
+			$success = false;
3199
+		}
3200
+        
3201
+		//do a nonce check here since we're not arriving via a normal route
3202
+		$nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3203
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3204
+        
3205
+		$this->_verify_nonce($nonce, $nonce_ref);
3206
+        
3207
+        
3208
+		if ( ! isset($this->_req_data['status'])) {
3209
+			EE_Error::add_error(
3210
+				__(
3211
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3212
+					'event_espresso'
3213
+				),
3214
+				__FILE__,
3215
+				__FUNCTION__,
3216
+				__LINE__
3217
+			);
3218
+			$success = false;
3219
+		}
3220
+        
3221
+		//do check to verify we have a valid status.
3222
+		$status = $this->_req_data['status'];
3223
+        
3224
+		if ($status != 'off' && $status != 'on') {
3225
+			EE_Error::add_error(
3226
+				sprintf(
3227
+					__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3228
+					$this->_req_data['status']
3229
+				),
3230
+				__FILE__,
3231
+				__FUNCTION__,
3232
+				__LINE__
3233
+			);
3234
+			$success = false;
3235
+		}
3236
+        
3237
+		if ($success) {
3238
+			//made it here?  Stop dawdling then!!
3239
+			$success = $status == 'off'
3240
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3241
+				: $this->_activate_messenger($this->_req_data['messenger']);
3242
+		}
3243
+        
3244
+		$this->_template_args['success'] = $success;
3245
+        
3246
+		//no special instructions so let's just do the json return (which should automatically do all the special stuff).
3247
+		$this->_return_json();
3248
+        
3249
+	}
3250
+    
3251
+    
3252
+	/**
3253
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3254
+	 *
3255
+	 */
3256
+	public function activate_mt_toggle()
3257
+	{
3258
+		$success = true;
3259
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3260
+        
3261
+		//let's make sure we have the necessary data
3262
+		if ( ! isset($this->_req_data['message_type'])) {
3263
+			EE_Error::add_error(
3264
+				__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3265
+				__FILE__, __FUNCTION__, __LINE__
3266
+			);
3267
+			$success = false;
3268
+		}
3269
+        
3270
+		if ( ! isset($this->_req_data['messenger'])) {
3271
+			EE_Error::add_error(
3272
+				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3273
+				__FILE__, __FUNCTION__, __LINE__
3274
+			);
3275
+			$success = false;
3276
+		}
3277
+        
3278
+		if ( ! isset($this->_req_data['status'])) {
3279
+			EE_Error::add_error(
3280
+				__('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3281
+					'event_espresso'),
3282
+				__FILE__, __FUNCTION__, __LINE__
3283
+			);
3284
+			$success = false;
3285
+		}
3286
+        
3287
+        
3288
+		//do check to verify we have a valid status.
3289
+		$status = $this->_req_data['status'];
3290
+        
3291
+		if ($status != 'activate' && $status != 'deactivate') {
3292
+			EE_Error::add_error(
3293
+				sprintf(
3294
+					__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3295
+					$this->_req_data['status']
3296
+				),
3297
+				__FILE__, __FUNCTION__, __LINE__
3298
+			);
3299
+			$success = false;
3300
+		}
3301
+        
3302
+        
3303
+		//do a nonce check here since we're not arriving via a normal route
3304
+		$nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3305
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3306
+        
3307
+		$this->_verify_nonce($nonce, $nonce_ref);
3308
+        
3309
+		if ($success) {
3310
+			//made it here? um, what are you waiting for then?
3311
+			$success = $status == 'deactivate'
3312
+				? $this->_deactivate_message_type_for_messenger($this->_req_data['messenger'],
3313
+					$this->_req_data['message_type'])
3314
+				: $this->_activate_message_type_for_messenger($this->_req_data['messenger'],
3315
+					$this->_req_data['message_type']);
3316
+		}
3317
+        
3318
+		$this->_template_args['success'] = $success;
3319
+		$this->_return_json();
3320
+	}
3321
+    
3322
+    
3323
+	/**
3324
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3325
+	 *
3326
+	 * @param string $messenger_name The name of the messenger being activated
3327
+	 *
3328
+	 * @return bool
3329
+	 */
3330
+	protected function _activate_messenger($messenger_name)
3331
+	{
3332
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3333
+		$active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3334
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3335
+        
3336
+		//ensure is active
3337
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3338
+        
3339
+		//set response_data for reload
3340
+		foreach ($message_types_to_activate as $message_type_name) {
3341
+			/** @var EE_message_type $message_type */
3342
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3343
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3344
+					$message_type_name)
3345
+				&& $message_type instanceof EE_message_type
3346
+			) {
3347
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
3348
+				if ($message_type->get_admin_settings_fields()) {
3349
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
3350
+				}
3351
+			}
3352
+		}
3353
+        
3354
+		//add success message for activating messenger
3355
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3356
+        
3357
+	}
3358
+    
3359
+    
3360
+	/**
3361
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
3362
+	 *
3363
+	 * @param string $messenger_name The name of the messenger being activated
3364
+	 *
3365
+	 * @return bool
3366
+	 */
3367
+	protected function _deactivate_messenger($messenger_name)
3368
+	{
3369
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3370
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3371
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
3372
+        
3373
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3374
+	}
3375
+    
3376
+    
3377
+	/**
3378
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3379
+	 *
3380
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
3381
+	 * @param string $message_type_name The name of the message type being activated for the messenger
3382
+	 *
3383
+	 * @return bool
3384
+	 */
3385
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3386
+	{
3387
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3388
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3389
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3390
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3391
+        
3392
+		//ensure is active
3393
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3394
+        
3395
+		//set response for load
3396
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3397
+			$message_type_name)
3398
+		) {
3399
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
3400
+			if ($message_type_to_activate->get_admin_settings_fields()) {
3401
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
3402
+			}
3403
+		}
3404
+        
3405
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3406
+			$message_type_to_activate);
3407
+	}
3408
+    
3409
+    
3410
+	/**
3411
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3412
+	 *
3413
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3414
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
3415
+	 *
3416
+	 * @return bool
3417
+	 */
3418
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
3419
+	{
3420
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3421
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3422
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3423
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
3424
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
3425
+        
3426
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
3427
+			$message_type_to_deactivate);
3428
+	}
3429
+    
3430
+    
3431
+	/**
3432
+	 * This just initializes the defaults for activating messenger and message type responses.
3433
+	 */
3434
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
3435
+	{
3436
+		$this->_template_args['data']['active_mts'] = array();
3437
+		$this->_template_args['data']['mt_reload']  = array();
3438
+	}
3439
+    
3440
+    
3441
+	/**
3442
+	 * Setup appropriate response for activating a messenger and/or message types
3443
+	 *
3444
+	 * @param EE_messenger         $messenger
3445
+	 * @param EE_message_type|null $message_type
3446
+	 *
3447
+	 * @return bool
3448
+	 * @throws EE_Error
3449
+	 */
3450
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
3451
+		$messenger,
3452
+		EE_Message_Type $message_type = null
3453
+	) {
3454
+		//if $messenger isn't a valid messenger object then get out.
3455
+		if ( ! $messenger instanceof EE_Messenger) {
3456
+			EE_Error::add_error(
3457
+				__('The messenger being activated is not a valid messenger', 'event_espresso'),
3458
+				__FILE__,
3459
+				__FUNCTION__,
3460
+				__LINE__
3461
+			);
3462 3462
             
3463
-            return false;
3464
-        }
3465
-        //activated
3466
-        if ($this->_template_args['data']['active_mts']) {
3467
-            EE_Error::overwrite_success();
3468
-            //activated a message type with the messenger
3469
-            if ($message_type instanceof EE_message_type) {
3470
-                EE_Error::add_success(
3471
-                    sprintf(
3472
-                        __('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3473
-                        ucwords($message_type->label['singular']),
3474
-                        ucwords($messenger->label['singular'])
3475
-                    )
3476
-                );
3463
+			return false;
3464
+		}
3465
+		//activated
3466
+		if ($this->_template_args['data']['active_mts']) {
3467
+			EE_Error::overwrite_success();
3468
+			//activated a message type with the messenger
3469
+			if ($message_type instanceof EE_message_type) {
3470
+				EE_Error::add_success(
3471
+					sprintf(
3472
+						__('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3473
+						ucwords($message_type->label['singular']),
3474
+						ucwords($messenger->label['singular'])
3475
+					)
3476
+				);
3477 3477
                 
3478
-                //if message type was invoice then let's make sure we activate the invoice payment method.
3479
-                if ($message_type->name == 'invoice') {
3480
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
3481
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
3482
-                    if ($pm instanceof EE_Payment_Method) {
3483
-                        EE_Error::add_attention(__('Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
3484
-                            'event_espresso'));
3485
-                    }
3486
-                }
3487
-                //just toggles the entire messenger
3488
-            } else {
3489
-                EE_Error::add_success(
3490
-                    sprintf(
3491
-                        __('%s messenger has been successfully activated', 'event_espresso'),
3492
-                        ucwords($messenger->label['singular'])
3493
-                    )
3494
-                );
3495
-            }
3478
+				//if message type was invoice then let's make sure we activate the invoice payment method.
3479
+				if ($message_type->name == 'invoice') {
3480
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
3481
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
3482
+					if ($pm instanceof EE_Payment_Method) {
3483
+						EE_Error::add_attention(__('Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
3484
+							'event_espresso'));
3485
+					}
3486
+				}
3487
+				//just toggles the entire messenger
3488
+			} else {
3489
+				EE_Error::add_success(
3490
+					sprintf(
3491
+						__('%s messenger has been successfully activated', 'event_espresso'),
3492
+						ucwords($messenger->label['singular'])
3493
+					)
3494
+				);
3495
+			}
3496 3496
             
3497
-            return true;
3497
+			return true;
3498 3498
             
3499
-            //possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3500
-            //message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3501
-            //in which case we just give a success message for the messenger being successfully activated.
3502
-        } else {
3503
-            if ( ! $messenger->get_default_message_types()) {
3504
-                //messenger doesn't have any default message types so still a success.
3505
-                EE_Error::add_success(
3506
-                    sprintf(
3507
-                        __('%s messenger was successfully activated.', 'event_espresso'),
3508
-                        ucwords($messenger->label['singular'])
3509
-                    )
3510
-                );
3499
+			//possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3500
+			//message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3501
+			//in which case we just give a success message for the messenger being successfully activated.
3502
+		} else {
3503
+			if ( ! $messenger->get_default_message_types()) {
3504
+				//messenger doesn't have any default message types so still a success.
3505
+				EE_Error::add_success(
3506
+					sprintf(
3507
+						__('%s messenger was successfully activated.', 'event_espresso'),
3508
+						ucwords($messenger->label['singular'])
3509
+					)
3510
+				);
3511 3511
                 
3512
-                return true;
3513
-            } else {
3514
-                EE_Error::add_error(
3515
-                    $message_type instanceof EE_message_type
3516
-                        ? sprintf(
3517
-                        __('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
3518
-                        ucwords($message_type->label['singular']),
3519
-                        ucwords($messenger->label['singular'])
3520
-                    )
3521
-                        : sprintf(
3522
-                        __('%s messenger was not successfully activated', 'event_espresso'),
3523
-                        ucwords($messenger->label['singular'])
3524
-                    ),
3525
-                    __FILE__,
3526
-                    __FUNCTION__,
3527
-                    __LINE__
3528
-                );
3512
+				return true;
3513
+			} else {
3514
+				EE_Error::add_error(
3515
+					$message_type instanceof EE_message_type
3516
+						? sprintf(
3517
+						__('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
3518
+						ucwords($message_type->label['singular']),
3519
+						ucwords($messenger->label['singular'])
3520
+					)
3521
+						: sprintf(
3522
+						__('%s messenger was not successfully activated', 'event_espresso'),
3523
+						ucwords($messenger->label['singular'])
3524
+					),
3525
+					__FILE__,
3526
+					__FUNCTION__,
3527
+					__LINE__
3528
+				);
3529 3529
                 
3530
-                return false;
3531
-            }
3532
-        }
3533
-    }
3534
-    
3535
-    
3536
-    /**
3537
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
3538
-     *
3539
-     * @param EE_messenger         $messenger
3540
-     * @param EE_message_type|null $message_type
3541
-     *
3542
-     * @return bool
3543
-     */
3544
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3545
-        $messenger,
3546
-        EE_message_type $message_type = null
3547
-    ) {
3548
-        EE_Error::overwrite_success();
3549
-        
3550
-        //if $messenger isn't a valid messenger object then get out.
3551
-        if ( ! $messenger instanceof EE_Messenger) {
3552
-            EE_Error::add_error(
3553
-                __('The messenger being deactivated is not a valid messenger', 'event_espresso'),
3554
-                __FILE__,
3555
-                __FUNCTION__,
3556
-                __LINE__
3557
-            );
3530
+				return false;
3531
+			}
3532
+		}
3533
+	}
3534
+    
3535
+    
3536
+	/**
3537
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
3538
+	 *
3539
+	 * @param EE_messenger         $messenger
3540
+	 * @param EE_message_type|null $message_type
3541
+	 *
3542
+	 * @return bool
3543
+	 */
3544
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3545
+		$messenger,
3546
+		EE_message_type $message_type = null
3547
+	) {
3548
+		EE_Error::overwrite_success();
3549
+        
3550
+		//if $messenger isn't a valid messenger object then get out.
3551
+		if ( ! $messenger instanceof EE_Messenger) {
3552
+			EE_Error::add_error(
3553
+				__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
3554
+				__FILE__,
3555
+				__FUNCTION__,
3556
+				__LINE__
3557
+			);
3558 3558
             
3559
-            return false;
3560
-        }
3561
-        
3562
-        if ($message_type instanceof EE_message_type) {
3563
-            $message_type_name = $message_type->name;
3564
-            EE_Error::add_success(
3565
-                sprintf(
3566
-                    __('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3567
-                    ucwords($message_type->label['singular']),
3568
-                    ucwords($messenger->label['singular'])
3569
-                )
3570
-            );
3571
-        } else {
3572
-            $message_type_name = '';
3573
-            EE_Error::add_success(
3574
-                sprintf(
3575
-                    __('%s messenger has been successfully deactivated.', 'event_espresso'),
3576
-                    ucwords($messenger->label['singular'])
3577
-                )
3578
-            );
3579
-        }
3580
-        
3581
-        //if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3582
-        if ($messenger->name == 'html' || $message_type_name == 'invoice') {
3583
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
3584
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
3585
-            if ($count_updated > 0) {
3586
-                $msg = $message_type_name == 'invoice'
3587
-                    ? __('Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
3588
-                        'event_espresso')
3589
-                    : __('Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
3590
-                        'event_espresso');
3591
-                EE_Error::add_attention($msg);
3592
-            }
3593
-        }
3594
-        
3595
-        return true;
3596
-    }
3597
-    
3598
-    
3599
-    /**
3600
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3601
-     */
3602
-    public function update_mt_form()
3603
-    {
3604
-        if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
3605
-            EE_Error::add_error(__('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__,
3606
-                __LINE__);
3607
-            $this->_return_json();
3608
-        }
3609
-        
3610
-        $message_types = $this->get_installed_message_types();
3611
-        
3612
-        $message_type = $message_types[$this->_req_data['message_type']];
3613
-        $messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
3614
-        
3615
-        $content                         = $this->_message_type_settings_content($message_type, $messenger, true);
3616
-        $this->_template_args['success'] = true;
3617
-        $this->_template_args['content'] = $content;
3618
-        $this->_return_json();
3619
-    }
3620
-    
3621
-    
3622
-    /**
3623
-     * this handles saving the settings for a messenger or message type
3624
-     *
3625
-     */
3626
-    public function save_settings()
3627
-    {
3628
-        if ( ! isset($this->_req_data['type'])) {
3629
-            EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
3630
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3631
-            $this->_template_args['error'] = true;
3632
-            $this->_return_json();
3633
-        }
3634
-        
3635
-        
3636
-        if ($this->_req_data['type'] == 'messenger') {
3637
-            $settings  = $this->_req_data['messenger_settings']; //this should be an array.
3638
-            $messenger = $settings['messenger'];
3639
-            //let's setup the settings data
3640
-            foreach ($settings as $key => $value) {
3641
-                switch ($key) {
3642
-                    case 'messenger' :
3643
-                        unset($settings['messenger']);
3644
-                        break;
3645
-                    case 'message_types' :
3646
-                        unset($settings['message_types']);
3647
-                        break;
3648
-                    default :
3649
-                        $settings[$key] = $value;
3650
-                        break;
3651
-                }
3652
-            }
3653
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
3654
-        } else if ($this->_req_data['type'] == 'message_type') {
3655
-            $settings     = $this->_req_data['message_type_settings'];
3656
-            $messenger    = $settings['messenger'];
3657
-            $message_type = $settings['message_type'];
3559
+			return false;
3560
+		}
3561
+        
3562
+		if ($message_type instanceof EE_message_type) {
3563
+			$message_type_name = $message_type->name;
3564
+			EE_Error::add_success(
3565
+				sprintf(
3566
+					__('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3567
+					ucwords($message_type->label['singular']),
3568
+					ucwords($messenger->label['singular'])
3569
+				)
3570
+			);
3571
+		} else {
3572
+			$message_type_name = '';
3573
+			EE_Error::add_success(
3574
+				sprintf(
3575
+					__('%s messenger has been successfully deactivated.', 'event_espresso'),
3576
+					ucwords($messenger->label['singular'])
3577
+				)
3578
+			);
3579
+		}
3580
+        
3581
+		//if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3582
+		if ($messenger->name == 'html' || $message_type_name == 'invoice') {
3583
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
3584
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
3585
+			if ($count_updated > 0) {
3586
+				$msg = $message_type_name == 'invoice'
3587
+					? __('Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
3588
+						'event_espresso')
3589
+					: __('Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
3590
+						'event_espresso');
3591
+				EE_Error::add_attention($msg);
3592
+			}
3593
+		}
3594
+        
3595
+		return true;
3596
+	}
3597
+    
3598
+    
3599
+	/**
3600
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3601
+	 */
3602
+	public function update_mt_form()
3603
+	{
3604
+		if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
3605
+			EE_Error::add_error(__('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__,
3606
+				__LINE__);
3607
+			$this->_return_json();
3608
+		}
3609
+        
3610
+		$message_types = $this->get_installed_message_types();
3611
+        
3612
+		$message_type = $message_types[$this->_req_data['message_type']];
3613
+		$messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
3614
+        
3615
+		$content                         = $this->_message_type_settings_content($message_type, $messenger, true);
3616
+		$this->_template_args['success'] = true;
3617
+		$this->_template_args['content'] = $content;
3618
+		$this->_return_json();
3619
+	}
3620
+    
3621
+    
3622
+	/**
3623
+	 * this handles saving the settings for a messenger or message type
3624
+	 *
3625
+	 */
3626
+	public function save_settings()
3627
+	{
3628
+		if ( ! isset($this->_req_data['type'])) {
3629
+			EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
3630
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3631
+			$this->_template_args['error'] = true;
3632
+			$this->_return_json();
3633
+		}
3634
+        
3635
+        
3636
+		if ($this->_req_data['type'] == 'messenger') {
3637
+			$settings  = $this->_req_data['messenger_settings']; //this should be an array.
3638
+			$messenger = $settings['messenger'];
3639
+			//let's setup the settings data
3640
+			foreach ($settings as $key => $value) {
3641
+				switch ($key) {
3642
+					case 'messenger' :
3643
+						unset($settings['messenger']);
3644
+						break;
3645
+					case 'message_types' :
3646
+						unset($settings['message_types']);
3647
+						break;
3648
+					default :
3649
+						$settings[$key] = $value;
3650
+						break;
3651
+				}
3652
+			}
3653
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
3654
+		} else if ($this->_req_data['type'] == 'message_type') {
3655
+			$settings     = $this->_req_data['message_type_settings'];
3656
+			$messenger    = $settings['messenger'];
3657
+			$message_type = $settings['message_type'];
3658 3658
             
3659
-            foreach ($settings as $key => $value) {
3660
-                switch ($key) {
3661
-                    case 'messenger' :
3662
-                        unset($settings['messenger']);
3663
-                        break;
3664
-                    case 'message_type' :
3665
-                        unset($settings['message_type']);
3666
-                        break;
3667
-                    default :
3668
-                        $settings[$key] = $value;
3669
-                        break;
3670
-                }
3671
-            }
3659
+			foreach ($settings as $key => $value) {
3660
+				switch ($key) {
3661
+					case 'messenger' :
3662
+						unset($settings['messenger']);
3663
+						break;
3664
+					case 'message_type' :
3665
+						unset($settings['message_type']);
3666
+						break;
3667
+					default :
3668
+						$settings[$key] = $value;
3669
+						break;
3670
+				}
3671
+			}
3672 3672
             
3673
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
3674
-        }
3675
-        
3676
-        //okay we should have the data all setup.  Now we just update!
3677
-        $success = $this->_message_resource_manager->update_active_messengers_option();
3678
-        
3679
-        if ($success) {
3680
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
3681
-        } else {
3682
-            EE_Error::add_error(__('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3683
-        }
3684
-        
3685
-        $this->_template_args['success'] = $success;
3686
-        $this->_return_json();
3687
-    }
3688
-    
3689
-    
3690
-    
3691
-    
3692
-    /**  EE MESSAGE PROCESSING ACTIONS **/
3693
-    
3694
-    
3695
-    /**
3696
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3697
-     * However, this does not send immediately, it just queues for sending.
3698
-     *
3699
-     * @since 4.9.0
3700
-     */
3701
-    protected function _generate_now()
3702
-    {
3703
-        $msg_ids = $this->_get_msg_ids_from_request();
3704
-        EED_Messages::generate_now($msg_ids);
3705
-        $this->_redirect_after_action(false, '', '', array(), true);
3706
-    }
3707
-    
3708
-    
3709
-    /**
3710
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
3711
-     * are EEM_Message::status_resend or EEM_Message::status_idle
3712
-     *
3713
-     * @since 4.9.0
3714
-     *
3715
-     */
3716
-    protected function _generate_and_send_now()
3717
-    {
3718
-        $this->_generate_now();
3719
-        $this->_send_now();
3720
-        $this->_redirect_after_action(false, '', '', array(), true);
3721
-    }
3722
-    
3723
-    
3724
-    /**
3725
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3726
-     *
3727
-     * @since 4.9.0
3728
-     */
3729
-    protected function _queue_for_resending()
3730
-    {
3731
-        $msg_ids = $this->_get_msg_ids_from_request();
3732
-        EED_Messages::queue_for_resending($msg_ids);
3733
-        $this->_redirect_after_action(false, '', '', array(), true);
3734
-    }
3735
-    
3736
-    
3737
-    /**
3738
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3739
-     *
3740
-     * @since 4.9.0
3741
-     */
3742
-    protected function _send_now()
3743
-    {
3744
-        $msg_ids = $this->_get_msg_ids_from_request();
3745
-        EED_Messages::send_now($msg_ids);
3746
-        $this->_redirect_after_action(false, '', '', array(), true);
3747
-    }
3748
-    
3749
-    
3750
-    /**
3751
-     * Deletes EE_messages for IDs in the request.
3752
-     *
3753
-     * @since 4.9.0
3754
-     */
3755
-    protected function _delete_ee_messages()
3756
-    {
3757
-        $msg_ids       = $this->_get_msg_ids_from_request();
3758
-        $deleted_count = 0;
3759
-        foreach ($msg_ids as $msg_id) {
3760
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
3761
-                $deleted_count++;
3762
-            }
3763
-        }
3764
-        if ($deleted_count) {
3765
-            $this->_redirect_after_action(
3766
-                true,
3767
-                _n('message', 'messages', $deleted_count, 'event_espresso'),
3768
-                __('deleted', 'event_espresso')
3769
-            );
3770
-        } else {
3771
-            EE_Error::add_error(
3772
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
3773
-                __FILE__, __FUNCTION__, __LINE__
3774
-            );
3775
-            $this->_redirect_after_action(false, '', '', array(), true);
3776
-        }
3777
-    }
3778
-    
3779
-    
3780
-    /**
3781
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3782
-     * @since 4.9.0
3783
-     * @return array
3784
-     */
3785
-    protected function _get_msg_ids_from_request()
3786
-    {
3787
-        if ( ! isset($this->_req_data['MSG_ID'])) {
3788
-            return array();
3789
-        }
3790
-        
3791
-        return is_array($this->_req_data['MSG_ID']) ? array_keys($this->_req_data['MSG_ID']) : array($this->_req_data['MSG_ID']);
3792
-    }
3673
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
3674
+		}
3675
+        
3676
+		//okay we should have the data all setup.  Now we just update!
3677
+		$success = $this->_message_resource_manager->update_active_messengers_option();
3678
+        
3679
+		if ($success) {
3680
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
3681
+		} else {
3682
+			EE_Error::add_error(__('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3683
+		}
3684
+        
3685
+		$this->_template_args['success'] = $success;
3686
+		$this->_return_json();
3687
+	}
3688
+    
3689
+    
3690
+    
3691
+    
3692
+	/**  EE MESSAGE PROCESSING ACTIONS **/
3693
+    
3694
+    
3695
+	/**
3696
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3697
+	 * However, this does not send immediately, it just queues for sending.
3698
+	 *
3699
+	 * @since 4.9.0
3700
+	 */
3701
+	protected function _generate_now()
3702
+	{
3703
+		$msg_ids = $this->_get_msg_ids_from_request();
3704
+		EED_Messages::generate_now($msg_ids);
3705
+		$this->_redirect_after_action(false, '', '', array(), true);
3706
+	}
3707
+    
3708
+    
3709
+	/**
3710
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
3711
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
3712
+	 *
3713
+	 * @since 4.9.0
3714
+	 *
3715
+	 */
3716
+	protected function _generate_and_send_now()
3717
+	{
3718
+		$this->_generate_now();
3719
+		$this->_send_now();
3720
+		$this->_redirect_after_action(false, '', '', array(), true);
3721
+	}
3722
+    
3723
+    
3724
+	/**
3725
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3726
+	 *
3727
+	 * @since 4.9.0
3728
+	 */
3729
+	protected function _queue_for_resending()
3730
+	{
3731
+		$msg_ids = $this->_get_msg_ids_from_request();
3732
+		EED_Messages::queue_for_resending($msg_ids);
3733
+		$this->_redirect_after_action(false, '', '', array(), true);
3734
+	}
3735
+    
3736
+    
3737
+	/**
3738
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3739
+	 *
3740
+	 * @since 4.9.0
3741
+	 */
3742
+	protected function _send_now()
3743
+	{
3744
+		$msg_ids = $this->_get_msg_ids_from_request();
3745
+		EED_Messages::send_now($msg_ids);
3746
+		$this->_redirect_after_action(false, '', '', array(), true);
3747
+	}
3748
+    
3749
+    
3750
+	/**
3751
+	 * Deletes EE_messages for IDs in the request.
3752
+	 *
3753
+	 * @since 4.9.0
3754
+	 */
3755
+	protected function _delete_ee_messages()
3756
+	{
3757
+		$msg_ids       = $this->_get_msg_ids_from_request();
3758
+		$deleted_count = 0;
3759
+		foreach ($msg_ids as $msg_id) {
3760
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
3761
+				$deleted_count++;
3762
+			}
3763
+		}
3764
+		if ($deleted_count) {
3765
+			$this->_redirect_after_action(
3766
+				true,
3767
+				_n('message', 'messages', $deleted_count, 'event_espresso'),
3768
+				__('deleted', 'event_espresso')
3769
+			);
3770
+		} else {
3771
+			EE_Error::add_error(
3772
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
3773
+				__FILE__, __FUNCTION__, __LINE__
3774
+			);
3775
+			$this->_redirect_after_action(false, '', '', array(), true);
3776
+		}
3777
+	}
3778
+    
3779
+    
3780
+	/**
3781
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3782
+	 * @since 4.9.0
3783
+	 * @return array
3784
+	 */
3785
+	protected function _get_msg_ids_from_request()
3786
+	{
3787
+		if ( ! isset($this->_req_data['MSG_ID'])) {
3788
+			return array();
3789
+		}
3790
+        
3791
+		return is_array($this->_req_data['MSG_ID']) ? array_keys($this->_req_data['MSG_ID']) : array($this->_req_data['MSG_ID']);
3792
+	}
3793 3793
     
3794 3794
     
3795 3795
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Payment_Method.model.php 1 patch
Spacing   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  *
@@ -37,33 +37,33 @@  discard block
 block discarded – undo
37 37
 	 * @access   protected
38 38
 	 * @return EEM_Payment_Method
39 39
 	 */
40
-	protected function __construct( $timezone = NULL ) {
41
-		$this->singlular_item = __( 'Payment Method', 'event_espresso' );
42
-		$this->plural_item = __( 'Payment Methods', 'event_espresso' );
43
-		$this->_tables = array( 'Payment_Method' => new EE_Primary_Table( 'esp_payment_method', 'PMD_ID' ) );
40
+	protected function __construct($timezone = NULL) {
41
+		$this->singlular_item = __('Payment Method', 'event_espresso');
42
+		$this->plural_item = __('Payment Methods', 'event_espresso');
43
+		$this->_tables = array('Payment_Method' => new EE_Primary_Table('esp_payment_method', 'PMD_ID'));
44 44
 		$this->_fields = array(
45 45
 			'Payment_Method' => array(
46
-				'PMD_ID' => new EE_Primary_Key_Int_Field( 'PMD_ID', __( "ID", 'event_espresso' ) ),
47
-				'PMD_type' => new EE_Plain_Text_Field( 'PMD_type', __( "Payment Method Type", 'event_espresso' ), FALSE, 'Admin_Only' ),
48
-				'PMD_name' => new EE_Plain_Text_Field( 'PMD_name', __( "Name", 'event_espresso' ), FALSE ),
49
-				'PMD_desc' => new EE_Post_Content_Field( 'PMD_desc', __( "Description", 'event_espresso' ), FALSE, '' ),
50
-				'PMD_admin_name' => new EE_Plain_Text_Field( 'PMD_admin_name', __( "Admin-Only Name", 'event_espresso' ), TRUE ),
51
-				'PMD_admin_desc' => new EE_Post_Content_Field( 'PMD_admin_desc', __( "Admin-Only Description", 'event_espresso' ), TRUE ),
52
-				'PMD_slug' => new EE_Slug_Field( 'PMD_slug', __( "Slug", 'event_espresso' ), FALSE ),
53
-				'PMD_order' => new EE_Integer_Field( 'PMD_order', __( "Order", 'event_espresso' ), FALSE, 0 ),
54
-				'PMD_debug_mode' => new EE_Boolean_Field( 'PMD_debug_mode', __( "Debug Mode On?", 'event_espresso' ), FALSE, FALSE ),
55
-				'PMD_wp_user' => new EE_WP_User_Field( 'PMD_wp_user', __( "Payment Method Creator ID", 'event_espresso' ), FALSE ),
56
-				'PMD_open_by_default' => new EE_Boolean_Field( 'PMD_open_by_default', __( "Open by Default?", 'event_espresso' ), FALSE, FALSE ), 'PMD_button_url' => new EE_Plain_Text_Field( 'PMD_button_url', __( "Button URL", 'event_espresso' ), TRUE, '' ),
57
-				'PMD_scope' => new EE_Serialized_Text_Field( 'PMD_scope', __( "Usable From?", 'event_espresso' ), FALSE, array() ), //possible values currently are 'CART','ADMIN','API'
46
+				'PMD_ID' => new EE_Primary_Key_Int_Field('PMD_ID', __("ID", 'event_espresso')),
47
+				'PMD_type' => new EE_Plain_Text_Field('PMD_type', __("Payment Method Type", 'event_espresso'), FALSE, 'Admin_Only'),
48
+				'PMD_name' => new EE_Plain_Text_Field('PMD_name', __("Name", 'event_espresso'), FALSE),
49
+				'PMD_desc' => new EE_Post_Content_Field('PMD_desc', __("Description", 'event_espresso'), FALSE, ''),
50
+				'PMD_admin_name' => new EE_Plain_Text_Field('PMD_admin_name', __("Admin-Only Name", 'event_espresso'), TRUE),
51
+				'PMD_admin_desc' => new EE_Post_Content_Field('PMD_admin_desc', __("Admin-Only Description", 'event_espresso'), TRUE),
52
+				'PMD_slug' => new EE_Slug_Field('PMD_slug', __("Slug", 'event_espresso'), FALSE),
53
+				'PMD_order' => new EE_Integer_Field('PMD_order', __("Order", 'event_espresso'), FALSE, 0),
54
+				'PMD_debug_mode' => new EE_Boolean_Field('PMD_debug_mode', __("Debug Mode On?", 'event_espresso'), FALSE, FALSE),
55
+				'PMD_wp_user' => new EE_WP_User_Field('PMD_wp_user', __("Payment Method Creator ID", 'event_espresso'), FALSE),
56
+				'PMD_open_by_default' => new EE_Boolean_Field('PMD_open_by_default', __("Open by Default?", 'event_espresso'), FALSE, FALSE), 'PMD_button_url' => new EE_Plain_Text_Field('PMD_button_url', __("Button URL", 'event_espresso'), TRUE, ''),
57
+				'PMD_scope' => new EE_Serialized_Text_Field('PMD_scope', __("Usable From?", 'event_espresso'), FALSE, array()), //possible values currently are 'CART','ADMIN','API'
58 58
 		) );
59 59
 		$this->_model_relations = array(
60 60
  //			'Event'=>new EE_HABTM_Relation('Event_Payment_Method'),
61 61
 			'Payment' => new EE_Has_Many_Relation(),
62
-			'Currency' => new EE_HABTM_Relation( 'Currency_Payment_Method' ),
62
+			'Currency' => new EE_HABTM_Relation('Currency_Payment_Method'),
63 63
 			'Transaction' => new EE_Has_Many_Relation(),
64 64
 			'WP_User' => new EE_Belongs_To_Relation(),
65 65
 		);
66
-		parent::__construct( $timezone );
66
+		parent::__construct($timezone);
67 67
 	}
68 68
 
69 69
 
@@ -73,8 +73,8 @@  discard block
 block discarded – undo
73 73
 	 * @param string $slug
74 74
 	 * @return EE_Payment_Method
75 75
 	 */
76
-	public function get_one_by_slug( $slug ) {
77
-		return $this->get_one( array( array( 'PMD_slug' => $slug ) ) );
76
+	public function get_one_by_slug($slug) {
77
+		return $this->get_one(array(array('PMD_slug' => $slug)));
78 78
 	}
79 79
 
80 80
 
@@ -88,8 +88,8 @@  discard block
 block discarded – undo
88 88
 		return apply_filters(
89 89
 			'FHEE__EEM_Payment_Method__scopes',
90 90
 			array(
91
-				self::scope_cart 		=> __( "Front-end Registration Page", 'event_espresso' ),
92
-				self::scope_admin 	=> __( "Admin Registration Page (no online processing)", 'event_espresso' )
91
+				self::scope_cart 		=> __("Front-end Registration Page", 'event_espresso'),
92
+				self::scope_admin 	=> __("Admin Registration Page (no online processing)", 'event_espresso')
93 93
 			)
94 94
 		);
95 95
 	}
@@ -101,9 +101,9 @@  discard block
 block discarded – undo
101 101
 	 * @param string $scope like one of EEM_Payment_Method::instance()->scopes()
102 102
 	 * @return boolean
103 103
 	 */
104
-	public function is_valid_scope( $scope ) {
104
+	public function is_valid_scope($scope) {
105 105
 		$scopes = $this->scopes();
106
-		if ( isset( $scopes[ $scope ] ) ) {
106
+		if (isset($scopes[$scope])) {
107 107
 			return TRUE;
108 108
 		} else {
109 109
 			return FALSE;
@@ -119,11 +119,11 @@  discard block
 block discarded – undo
119 119
 	 * @throws EE_Error
120 120
 	 * @return EE_Payment_Method[]
121 121
 	 */
122
-	public function get_all_active( $scope = NULL, $query_params = array() ) {
123
-		if( ! isset( $query_params[ 'order_by' ] ) && ! isset( $query_params[ 'order' ] ) ) {
124
-			$query_params['order_by'] = array( 'PMD_order' => 'ASC', 'PMD_ID' => 'ASC' );
122
+	public function get_all_active($scope = NULL, $query_params = array()) {
123
+		if ( ! isset($query_params['order_by']) && ! isset($query_params['order'])) {
124
+			$query_params['order_by'] = array('PMD_order' => 'ASC', 'PMD_ID' => 'ASC');
125 125
 		}
126
-		return $this->get_all( $this->_get_query_params_for_all_active( $scope, $query_params ) );
126
+		return $this->get_all($this->_get_query_params_for_all_active($scope, $query_params));
127 127
 	}
128 128
 
129 129
 	/**
@@ -132,8 +132,8 @@  discard block
 block discarded – undo
132 132
 	 * @param array $query_params
133 133
 	 * @return int
134 134
 	 */
135
-	public function count_active( $scope = NULL, $query_params = array() ){
136
-		return $this->count( $this->_get_query_params_for_all_active( $scope, $query_params ) );
135
+	public function count_active($scope = NULL, $query_params = array()) {
136
+		return $this->count($this->_get_query_params_for_all_active($scope, $query_params));
137 137
 	}
138 138
 
139 139
 	/**
@@ -144,21 +144,21 @@  discard block
 block discarded – undo
144 144
 	 * @return array like param of EEM_Base::get_all()
145 145
 	 * @throws EE_Error
146 146
 	 */
147
-	protected function _get_query_params_for_all_active( $scope = NULL, $query_params = array() ){
148
-		if ( $scope ) {
149
-			if ( $this->is_valid_scope( $scope ) ) {
150
-				return array_replace_recursive( array( array( 'PMD_scope' => array( 'LIKE', "%$scope%" ) ) ), $query_params );
147
+	protected function _get_query_params_for_all_active($scope = NULL, $query_params = array()) {
148
+		if ($scope) {
149
+			if ($this->is_valid_scope($scope)) {
150
+				return array_replace_recursive(array(array('PMD_scope' => array('LIKE', "%$scope%"))), $query_params);
151 151
 			} else {
152
-				throw new EE_Error( sprintf( __( "'%s' is not a valid scope for a payment method", "event_espresso" ), $scope ) );
152
+				throw new EE_Error(sprintf(__("'%s' is not a valid scope for a payment method", "event_espresso"), $scope));
153 153
 			}
154 154
 		} else {
155 155
 			$acceptable_scopes = array();
156 156
 			$count = 0;
157
-			foreach ( $this->scopes() as $scope_name => $desc ) {
157
+			foreach ($this->scopes() as $scope_name => $desc) {
158 158
 				$count++;
159
-				$acceptable_scopes[ 'PMD_scope*' . $count ] = array( 'LIKE', '%' . $scope_name . '%' );
159
+				$acceptable_scopes['PMD_scope*'.$count] = array('LIKE', '%'.$scope_name.'%');
160 160
 			}
161
-			return array_replace_recursive( array( array( 'OR*active_scope' => $acceptable_scopes ) ), $query_params );
161
+			return array_replace_recursive(array(array('OR*active_scope' => $acceptable_scopes)), $query_params);
162 162
 		}
163 163
 	}
164 164
 
@@ -170,8 +170,8 @@  discard block
 block discarded – undo
170 170
 	 * @return array like param of EEM_Base::get_all()
171 171
 	 * @throws EE_Error
172 172
 	 */
173
-	public function get_query_params_for_all_active( $scope = NULL, $query_params = array() ) {
174
-		return $this->_get_query_params_for_all_active( $scope, $query_params );
173
+	public function get_query_params_for_all_active($scope = NULL, $query_params = array()) {
174
+		return $this->_get_query_params_for_all_active($scope, $query_params);
175 175
 	}
176 176
 
177 177
 
@@ -181,8 +181,8 @@  discard block
 block discarded – undo
181 181
 	 * @param array  $query_params
182 182
 	 * @return EE_Payment_Method
183 183
 	 */
184
-	public function get_one_active( $scope = NULL, $query_params = array() ) {
185
-		return $this->get_one( $this->_get_query_params_for_all_active( $scope, $query_params ) );
184
+	public function get_one_active($scope = NULL, $query_params = array()) {
185
+		return $this->get_one($this->_get_query_params_for_all_active($scope, $query_params));
186 186
 	}
187 187
 
188 188
 
@@ -192,8 +192,8 @@  discard block
 block discarded – undo
192 192
 	 * @param string $type
193 193
 	 * @return EE_Payment_Method
194 194
 	 */
195
-	public function get_one_of_type( $type ) {
196
-		return $this->get_one( array( array( 'PMD_type' => $type ) ) );
195
+	public function get_one_of_type($type) {
196
+		return $this->get_one(array(array('PMD_type' => $type)));
197 197
 	}
198 198
 
199 199
 
@@ -206,22 +206,22 @@  discard block
 block discarded – undo
206 206
 	 * @return EE_Payment_Method
207 207
 	 * @throws EE_Error
208 208
 	 */
209
-	public function ensure_is_obj( $base_class_obj_or_id, $ensure_is_in_db = FALSE ) {
209
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = FALSE) {
210 210
 		//first: check if it's a slug
211
-		if( is_string( $base_class_obj_or_id ) ) {
212
-			$obj = $this->get_one_by_slug( $base_class_obj_or_id );
213
-			if( $obj ) {
211
+		if (is_string($base_class_obj_or_id)) {
212
+			$obj = $this->get_one_by_slug($base_class_obj_or_id);
213
+			if ($obj) {
214 214
 				return $obj;
215 215
 			}
216 216
 		}
217 217
 		//ok so it wasn't a slug we were passed. try the usual then (ie, it's an object or an ID)
218 218
 		try {
219
-			return parent::ensure_is_obj( $base_class_obj_or_id, $ensure_is_in_db );
219
+			return parent::ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db);
220 220
 		}
221
-		catch ( EE_Error $e ) {
221
+		catch (EE_Error $e) {
222 222
 			//handle it outside the catch
223 223
 		}
224
-		throw new EE_Error( sprintf( __( "'%s' is neither a Payment Method ID, slug, nor object.", "event_espresso" ), $base_class_obj_or_id ) );
224
+		throw new EE_Error(sprintf(__("'%s' is neither a Payment Method ID, slug, nor object.", "event_espresso"), $base_class_obj_or_id));
225 225
 	}
226 226
 
227 227
 
@@ -232,12 +232,12 @@  discard block
 block discarded – undo
232 232
 	 * @param mixed $base_obj_or_id_or_slug
233 233
 	 * @return int
234 234
 	 */
235
-	function ensure_is_ID( $base_obj_or_id_or_slug ) {
236
-		if ( is_string( $base_obj_or_id_or_slug ) ) {
235
+	function ensure_is_ID($base_obj_or_id_or_slug) {
236
+		if (is_string($base_obj_or_id_or_slug)) {
237 237
 			//assume it's a slug
238
-			$base_obj_or_id_or_slug = $this->get_one_by_slug( $base_obj_or_id_or_slug );
238
+			$base_obj_or_id_or_slug = $this->get_one_by_slug($base_obj_or_id_or_slug);
239 239
 		}
240
-		return parent::ensure_is_ID( $base_obj_or_id_or_slug );
240
+		return parent::ensure_is_ID($base_obj_or_id_or_slug);
241 241
 	}
242 242
 
243 243
 
@@ -246,36 +246,36 @@  discard block
 block discarded – undo
246 246
 	 * Verifies the button urls on all the passed payment methods have a valid button url. If not, resets them to their default.
247 247
 	 * @param EE_Payment_Method[] $payment_methods. If NULL is provided defaults to all payment methods active in the cart
248 248
 	 */
249
-	function verify_button_urls( $payment_methods = NULL ) {
250
-		$payment_methods = is_array( $payment_methods ) ? $payment_methods : $this->get_all_active(EEM_Payment_Method::scope_cart);
251
-		foreach ( $payment_methods as $payment_method ) {
249
+	function verify_button_urls($payment_methods = NULL) {
250
+		$payment_methods = is_array($payment_methods) ? $payment_methods : $this->get_all_active(EEM_Payment_Method::scope_cart);
251
+		foreach ($payment_methods as $payment_method) {
252 252
 			try {
253 253
 				$current_button_url = $payment_method->button_url();
254
-				$buttons_urls_to_try = apply_filters( 'FHEE__EEM_Payment_Method__verify_button_urls__button_urls_to_try', array(
255
-					'current_ssl' => str_replace( "http://", "https://", $current_button_url ),
256
-					'current' => str_replace( "https://", "http://", $current_button_url ),
257
-					'default_ssl' => str_replace( "http://", "https://", $payment_method->type_obj()->default_button_url() ),
258
-					'default' => str_replace( "https://", "http://", $payment_method->type_obj()->default_button_url() ),
259
-				) );
260
-				foreach( $buttons_urls_to_try as $button_url_to_try ) {
261
-					if(
254
+				$buttons_urls_to_try = apply_filters('FHEE__EEM_Payment_Method__verify_button_urls__button_urls_to_try', array(
255
+					'current_ssl' => str_replace("http://", "https://", $current_button_url),
256
+					'current' => str_replace("https://", "http://", $current_button_url),
257
+					'default_ssl' => str_replace("http://", "https://", $payment_method->type_obj()->default_button_url()),
258
+					'default' => str_replace("https://", "http://", $payment_method->type_obj()->default_button_url()),
259
+				));
260
+				foreach ($buttons_urls_to_try as $button_url_to_try) {
261
+					if (
262 262
 							(//this is the current url and it exists, regardless of SSL issues
263 263
 								$button_url_to_try == $current_button_url &&
264 264
 								EEH_URL::remote_file_exists(
265 265
 										$button_url_to_try,
266 266
 										array(
267 267
 											'sslverify' => false,
268
-											'limit_response_size' => 4095,//we don't really care for a full response, but we do want headers at least. Lets just ask for a one block
268
+											'limit_response_size' => 4095, //we don't really care for a full response, but we do want headers at least. Lets just ask for a one block
269 269
 											) )
270 270
 							)
271 271
 							||
272 272
 							(//this is NOT the current url and it exists with a working SSL cert
273 273
 								$button_url_to_try != $current_button_url &&
274
-								EEH_URL::remote_file_exists( $button_url_to_try )
274
+								EEH_URL::remote_file_exists($button_url_to_try)
275 275
 							) ) {
276
-						if( $current_button_url != $button_url_to_try ){
277
-							$payment_method->save( array( 'PMD_button_url' => $button_url_to_try ) );
278
-							EE_Error::add_attention( sprintf( __( "Payment Method %s's button url was set to %s, because the old image either didnt exist or SSL was recently enabled.", "event_espresso" ), $payment_method->name(), $button_url_to_try ) );
276
+						if ($current_button_url != $button_url_to_try) {
277
+							$payment_method->save(array('PMD_button_url' => $button_url_to_try));
278
+							EE_Error::add_attention(sprintf(__("Payment Method %s's button url was set to %s, because the old image either didnt exist or SSL was recently enabled.", "event_espresso"), $payment_method->name(), $button_url_to_try));
279 279
 						}
280 280
 						//this image exists. So if wasn't set before, now it is;
281 281
 						//or if it was already set, we have nothing to do
@@ -283,8 +283,8 @@  discard block
 block discarded – undo
283 283
 					}
284 284
 				}
285 285
 			}
286
-			catch ( EE_Error $e ) {
287
-				$payment_method->set_active( FALSE );
286
+			catch (EE_Error $e) {
287
+				$payment_method->set_active(FALSE);
288 288
 			}
289 289
 		}
290 290
 	}
@@ -298,29 +298,29 @@  discard block
 block discarded – undo
298 298
 	 * @param array $rows
299 299
 	 * @return EE_Payment_Method[]
300 300
 	 */
301
-	protected function _create_objects( $rows = array() ) {
302
-		EE_Registry::instance()->load_lib( 'Payment_Method_Manager' );
303
-		$payment_methods = parent::_create_objects( $rows );
301
+	protected function _create_objects($rows = array()) {
302
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
303
+		$payment_methods = parent::_create_objects($rows);
304 304
 		/* @var $payment_methods EE_Payment_Method[] */
305 305
 		$usable_payment_methods = array();
306
-		foreach ( $payment_methods as $key => $payment_method ) {
307
-			if ( EE_Payment_Method_Manager::instance()->payment_method_type_exists( $payment_method->type() ) ) {
308
-				$usable_payment_methods[ $key ] = $payment_method;
306
+		foreach ($payment_methods as $key => $payment_method) {
307
+			if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($payment_method->type())) {
308
+				$usable_payment_methods[$key] = $payment_method;
309 309
 				//some payment methods enqueue their scripts in EE_PMT_*::__construct
310 310
 				//which is kinda a no-no (just because it's being constructed doesn't mean we need to enqueue
311 311
 				//its scripts). but for backwards-compat we should continue to do that
312 312
 				$payment_method->type_obj();
313
-			} elseif( $payment_method->active() ) {				
313
+			} elseif ($payment_method->active()) {				
314 314
 				//only deactivate and notify the admin if the payment is active somewhere
315 315
 				$payment_method->deactivate();
316 316
 				$payment_method->save();
317 317
 				EE_Error::add_persistent_admin_notice(
318
-					'auto-deactivated-' . $payment_method->type(),
318
+					'auto-deactivated-'.$payment_method->type(),
319 319
 					sprintf(
320
-						__( 'The payment method %1$s was automatically deactivated because it appears its associated Event Espresso Addon was recently deactivated.%2$sIt can be reactivated on the %3$sPlugins admin page%4$s, then you can reactivate the payment method.', 'event_espresso' ),
320
+						__('The payment method %1$s was automatically deactivated because it appears its associated Event Espresso Addon was recently deactivated.%2$sIt can be reactivated on the %3$sPlugins admin page%4$s, then you can reactivate the payment method.', 'event_espresso'),
321 321
 						$payment_method->admin_name(),
322 322
 						'<br />',
323
-						'<a href="' . admin_url('plugins.php') . '">',
323
+						'<a href="'.admin_url('plugins.php').'">',
324 324
 						'</a>'
325 325
 					),
326 326
 					true
@@ -340,11 +340,11 @@  discard block
 block discarded – undo
340 340
 	 * @param string 	$scope @see EEM_Payment_Method::get_all_for_events
341 341
 	 * @return EE_Payment_Method[]
342 342
 	 */
343
-	public function get_all_for_transaction( $transaction, $scope ) {
343
+	public function get_all_for_transaction($transaction, $scope) {
344 344
 		//give addons a chance to override what payment methods are chosen based on the transaction
345 345
 		return apply_filters(
346 346
 			'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
347
-			$this->get_all_active( $scope ),
347
+			$this->get_all_active($scope),
348 348
 			$transaction,
349 349
 			$scope
350 350
 		);
@@ -360,16 +360,16 @@  discard block
 block discarded – undo
360 360
 	 * @param EE_Registration|int $registration_or_reg_id  Either the EE_Registration object or the id for the registration.
361 361
 	 * @return EE_Payment|null
362 362
 	 */
363
-	public function get_last_used_for_registration( $registration_or_reg_id ) {
364
-		$registration_id = EEM_Registration::instance()->ensure_is_ID( $registration_or_reg_id );
363
+	public function get_last_used_for_registration($registration_or_reg_id) {
364
+		$registration_id = EEM_Registration::instance()->ensure_is_ID($registration_or_reg_id);
365 365
 
366 366
 		$query_params = array(
367 367
 			0 => array(
368 368
 				'Payment.Registration.REG_ID' => $registration_id,
369 369
 			),
370
-			'order_by' => array( 'Payment.PAY_ID' => 'DESC' )
370
+			'order_by' => array('Payment.PAY_ID' => 'DESC')
371 371
 		);
372
-		return $this->get_one( $query_params );
372
+		return $this->get_one($query_params);
373 373
 	}
374 374
 
375 375
 }
Please login to merge, or discard this patch.
admin_pages/payments/Payments_Admin_Page.core.php 1 patch
Spacing   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (!defined('EVENT_ESPRESSO_VERSION') )
2
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
3 3
 	exit('NO direct script access allowed');
4 4
 
5 5
 /**
@@ -44,8 +44,8 @@  discard block
 block discarded – undo
44 44
 	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
45 45
 	 * @return \Payments_Admin_Page
46 46
 	 */
47
-	public function __construct( $routing = TRUE ) {
48
-		parent::__construct( $routing );
47
+	public function __construct($routing = TRUE) {
48
+		parent::__construct($routing);
49 49
 	}
50 50
 
51 51
 
@@ -130,19 +130,19 @@  discard block
 block discarded – undo
130 130
 	protected function _set_page_config() {
131 131
 		$payment_method_list_config = array(
132 132
 			'nav'           => array(
133
-				'label' => __( 'Payment Methods', 'event_espresso' ),
133
+				'label' => __('Payment Methods', 'event_espresso'),
134 134
 				'order' => 10
135 135
 			),
136 136
 			'metaboxes'     => $this->_default_espresso_metaboxes,
137 137
 			'help_tabs'     => array_merge(
138 138
 				array(
139 139
 					'payment_methods_overview_help_tab' => array(
140
-						'title'    => __( 'Payment Methods Overview', 'event_espresso' ),
140
+						'title'    => __('Payment Methods Overview', 'event_espresso'),
141 141
 						'filename' => 'payment_methods_overview'
142 142
 					)
143 143
 				),
144 144
 				$this->_add_payment_method_help_tabs() ),
145
-			'help_tour'     => array( 'Payment_Methods_Selection_Help_Tour' ),
145
+			'help_tour'     => array('Payment_Methods_Selection_Help_Tour'),
146 146
 			'require_nonce' => false
147 147
 		);
148 148
 
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 					)
161 161
 				),
162 162
 				//'help_tour' => array( 'Payment_Methods_Settings_Help_Tour' ),
163
-				'metaboxes' => array_merge( $this->_default_espresso_metaboxes, array( '_publish_post_box' ) ),
163
+				'metaboxes' => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
164 164
 				'require_nonce' => FALSE
165 165
 			),
166 166
 			'payment_log'=>array(
@@ -179,17 +179,17 @@  discard block
 block discarded – undo
179 179
 	/**
180 180
 	 * @return array
181 181
 	 */
182
-	protected function _add_payment_method_help_tabs(){
182
+	protected function _add_payment_method_help_tabs() {
183 183
 		EE_Registry::instance()->load_lib('Payment_Method_Manager');
184 184
 		$payment_method_types = EE_Payment_Method_Manager::instance()->payment_method_types();
185 185
 		$all_pmt_help_tabs_config = array();
186
-		foreach( $payment_method_types as $payment_method_type ){
187
-			if ( ! EE_Registry::instance()->CAP->current_user_can( $payment_method_type->cap_name(), 'specific_payment_method_type_access' ) ) {
186
+		foreach ($payment_method_types as $payment_method_type) {
187
+			if ( ! EE_Registry::instance()->CAP->current_user_can($payment_method_type->cap_name(), 'specific_payment_method_type_access')) {
188 188
 				continue;
189 189
 			}
190
-			foreach( $payment_method_type->help_tabs_config() as $help_tab_name => $config ){
191
-				$template_args = isset( $config[ 'template_args' ] ) ? $config[ 'template_args' ] : array();
192
-				$template_args[ 'admin_page_obj' ] = $this;
190
+			foreach ($payment_method_type->help_tabs_config() as $help_tab_name => $config) {
191
+				$template_args = isset($config['template_args']) ? $config['template_args'] : array();
192
+				$template_args['admin_page_obj'] = $this;
193 193
 				$all_pmt_help_tabs_config[$help_tab_name] = array(
194 194
 					'title'=>$config['title'],
195 195
 					'content'=>EEH_Template::display_template(
@@ -216,9 +216,9 @@  discard block
 block discarded – undo
216 216
 
217 217
 
218 218
 	public function load_scripts_styles() {
219
-		wp_enqueue_script( 'ee_admin_js' );
220
-		wp_enqueue_script( 'ee-text-links' );
221
-		wp_enqueue_script( 'espresso_payments', EE_PAYMENTS_ASSETS_URL . 'espresso_payments_admin.js', array( 'espresso-ui-theme', 'ee-datepicker' ), EVENT_ESPRESSO_VERSION, TRUE );
219
+		wp_enqueue_script('ee_admin_js');
220
+		wp_enqueue_script('ee-text-links');
221
+		wp_enqueue_script('espresso_payments', EE_PAYMENTS_ASSETS_URL.'espresso_payments_admin.js', array('espresso-ui-theme', 'ee-datepicker'), EVENT_ESPRESSO_VERSION, TRUE);
222 222
 	}
223 223
 
224 224
 
@@ -227,9 +227,9 @@  discard block
 block discarded – undo
227 227
 
228 228
 	public function load_scripts_styles_default() {
229 229
 		//styles
230
-		wp_register_style( 'espresso_payments', EE_PAYMENTS_ASSETS_URL . 'ee-payments.css', array(), EVENT_ESPRESSO_VERSION );
231
-		wp_enqueue_style( 'espresso_payments' );
232
-		wp_enqueue_style( 'ee-text-links' );
230
+		wp_register_style('espresso_payments', EE_PAYMENTS_ASSETS_URL.'ee-payments.css', array(), EVENT_ESPRESSO_VERSION);
231
+		wp_enqueue_style('espresso_payments');
232
+		wp_enqueue_style('ee-text-links');
233 233
 		//scripts
234 234
 	}
235 235
 
@@ -243,44 +243,44 @@  discard block
 block discarded – undo
243 243
 		 * to the loading process.  However, people MUST setup the details for the payment method so its safe to do a
244 244
 		 * recheck here.
245 245
 		 */
246
-		EE_Registry::instance()->load_lib( 'Payment_Method_Manager' );
246
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
247 247
 		EEM_Payment_Method::instance()->verify_button_urls();
248 248
 		//setup tabs, one for each payment method type
249 249
 		$tabs = array();
250 250
 		$payment_methods = array();
251
-		foreach( EE_Payment_Method_Manager::instance()->payment_method_types() as $pmt_obj ) {
251
+		foreach (EE_Payment_Method_Manager::instance()->payment_method_types() as $pmt_obj) {
252 252
 			// we don't want to show admin-only PMTs for now
253
-			if ( $pmt_obj instanceof EE_PMT_Admin_Only ) {
253
+			if ($pmt_obj instanceof EE_PMT_Admin_Only) {
254 254
 				continue;
255 255
 			}
256 256
 			//check access
257
-			if ( ! EE_Registry::instance()->CAP->current_user_can( $pmt_obj->cap_name(), 'specific_payment_method_type_access' ) ) {
257
+			if ( ! EE_Registry::instance()->CAP->current_user_can($pmt_obj->cap_name(), 'specific_payment_method_type_access')) {
258 258
 				continue;
259 259
 			}
260 260
 			//check for any active pms of that type
261
-			$payment_method = EEM_Payment_Method::instance()->get_one_of_type( $pmt_obj->system_name() );
262
-			if ( ! $payment_method instanceof EE_Payment_Method ) {
261
+			$payment_method = EEM_Payment_Method::instance()->get_one_of_type($pmt_obj->system_name());
262
+			if ( ! $payment_method instanceof EE_Payment_Method) {
263 263
 				$payment_method = EE_Payment_Method::new_instance(
264 264
 					array(
265
-						'PMD_slug'					=>sanitize_key( $pmt_obj->system_name() ),
265
+						'PMD_slug'					=>sanitize_key($pmt_obj->system_name()),
266 266
 						'PMD_type'					=>$pmt_obj->system_name(),
267 267
 						'PMD_name'				=>$pmt_obj->pretty_name(),
268 268
 						'PMD_admin_name'	=>$pmt_obj->pretty_name()
269 269
 					)
270 270
 				);
271 271
 			}
272
-			$payment_methods[ $payment_method->slug() ] = $payment_method;
272
+			$payment_methods[$payment_method->slug()] = $payment_method;
273 273
 		}
274
-		$payment_methods = apply_filters( 'FHEE__Payments_Admin_Page___payment_methods_list__payment_methods', $payment_methods );
275
-		foreach( $payment_methods as $payment_method ) {
276
-			if ( $payment_method instanceof EE_Payment_Method ) {
274
+		$payment_methods = apply_filters('FHEE__Payments_Admin_Page___payment_methods_list__payment_methods', $payment_methods);
275
+		foreach ($payment_methods as $payment_method) {
276
+			if ($payment_method instanceof EE_Payment_Method) {
277 277
 				add_meta_box(
278 278
 					//html id
279
-					'espresso_' . $payment_method->slug() . '_payment_settings',
279
+					'espresso_'.$payment_method->slug().'_payment_settings',
280 280
 					//title
281
-					sprintf( __( '%s Settings', 'event_espresso' ), $payment_method->admin_name() ),
281
+					sprintf(__('%s Settings', 'event_espresso'), $payment_method->admin_name()),
282 282
 					//callback
283
-					array( $this, 'payment_method_settings_meta_box' ),
283
+					array($this, 'payment_method_settings_meta_box'),
284 284
 					//post type
285 285
 					null,
286 286
 					//context
@@ -288,19 +288,19 @@  discard block
 block discarded – undo
288 288
 					//priority
289 289
 					'default',
290 290
 					//callback args
291
-					array( 'payment_method' => $payment_method )
291
+					array('payment_method' => $payment_method)
292 292
 				);
293 293
 				//setup for tabbed content
294
-				$tabs[ $payment_method->slug() ] = array(
294
+				$tabs[$payment_method->slug()] = array(
295 295
 					'label' => $payment_method->admin_name(),
296 296
 					'class' => $payment_method->active() ? 'gateway-active' : '',
297
-					'href'  => 'espresso_' . $payment_method->slug() . '_payment_settings',
298
-					'title' => __( 'Modify this Payment Method', 'event_espresso' ),
297
+					'href'  => 'espresso_'.$payment_method->slug().'_payment_settings',
298
+					'title' => __('Modify this Payment Method', 'event_espresso'),
299 299
 					'slug'  => $payment_method->slug()
300 300
 				);
301 301
 			}
302 302
 		}
303
-		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links( $tabs, 'payment_method_links', '|', $this->_get_active_payment_method_slug() );
303
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links($tabs, 'payment_method_links', '|', $this->_get_active_payment_method_slug());
304 304
 		$this->display_admin_page_with_sidebar();
305 305
 
306 306
 	}
@@ -311,20 +311,20 @@  discard block
 block discarded – undo
311 311
 	 *   _get_active_payment_method_slug
312 312
 	 * 	@return string
313 313
 	 */
314
-	protected function _get_active_payment_method_slug(){
314
+	protected function _get_active_payment_method_slug() {
315 315
 		$payment_method_slug = FALSE;
316 316
 		//decide which payment method tab to open first, as dictated by the request's 'payment_method'
317
-		if ( isset( $this->_req_data['payment_method'] )) {
317
+		if (isset($this->_req_data['payment_method'])) {
318 318
 			// if they provided the current payment method, use it
319
-			$payment_method_slug = sanitize_key( $this->_req_data['payment_method'] );
319
+			$payment_method_slug = sanitize_key($this->_req_data['payment_method']);
320 320
 		}
321
-		$payment_method = EEM_Payment_Method::instance()->get_one( array( array( 'PMD_slug' => $payment_method_slug )));
321
+		$payment_method = EEM_Payment_Method::instance()->get_one(array(array('PMD_slug' => $payment_method_slug)));
322 322
 		// if that didn't work or wasn't provided, find another way to select the current pm
323
-		if ( ! $this->_verify_payment_method( $payment_method )) {
323
+		if ( ! $this->_verify_payment_method($payment_method)) {
324 324
 			// like, looking for an active one
325
-			$payment_method = EEM_Payment_Method::instance()->get_one_active( 'CART' );
325
+			$payment_method = EEM_Payment_Method::instance()->get_one_active('CART');
326 326
 			// test that one as well
327
-			if ( $this->_verify_payment_method( $payment_method )) {
327
+			if ($this->_verify_payment_method($payment_method)) {
328 328
 				$payment_method_slug = $payment_method->slug();
329 329
 			} else {
330 330
 				$payment_method_slug = 'paypal_standard';
@@ -342,11 +342,11 @@  discard block
 block discarded – undo
342 342
 	 * @param \EE_Payment_Method $payment_method
343 343
 	 * @return boolean
344 344
 	 */
345
-	protected function _verify_payment_method( $payment_method ){
345
+	protected function _verify_payment_method($payment_method) {
346 346
 		if (
347 347
 			$payment_method instanceof EE_Payment_Method &&
348 348
 			$payment_method->type_obj() instanceof EE_PMT_Base &&
349
-			EE_Registry::instance()->CAP->current_user_can( $payment_method->type_obj()->cap_name(), 'specific_payment_method_type_access' )
349
+			EE_Registry::instance()->CAP->current_user_can($payment_method->type_obj()->cap_name(), 'specific_payment_method_type_access')
350 350
 		) {
351 351
 			return TRUE;
352 352
 		}
@@ -363,21 +363,21 @@  discard block
 block discarded – undo
363 363
 	 * @return string
364 364
 	 * @throws EE_Error
365 365
 	 */
366
-	public function payment_method_settings_meta_box( $post_obj_which_is_null, $metabox ){
367
-		$payment_method = isset( $metabox['args'], $metabox['args']['payment_method'] ) ? $metabox['args']['payment_method'] : NULL;
368
-		if ( ! $payment_method instanceof EE_Payment_Method ){
369
-			throw new EE_Error( sprintf( __( 'Payment method metabox setup incorrectly. No Payment method object was supplied', 'event_espresso' )));
366
+	public function payment_method_settings_meta_box($post_obj_which_is_null, $metabox) {
367
+		$payment_method = isset($metabox['args'], $metabox['args']['payment_method']) ? $metabox['args']['payment_method'] : NULL;
368
+		if ( ! $payment_method instanceof EE_Payment_Method) {
369
+			throw new EE_Error(sprintf(__('Payment method metabox setup incorrectly. No Payment method object was supplied', 'event_espresso')));
370 370
 		}
371 371
 		$payment_method_scopes = $payment_method->active();
372 372
 		// if the payment method really exists show its form, otherwise the activation template
373
-		if ( $payment_method->ID() && ! empty( $payment_method_scopes )) {
374
-				$form = $this->_generate_payment_method_settings_form( $payment_method );
375
-				if ( $form->form_data_present_in( $this->_req_data )) {
376
-					$form->receive_form_submission( $this->_req_data );
373
+		if ($payment_method->ID() && ! empty($payment_method_scopes)) {
374
+				$form = $this->_generate_payment_method_settings_form($payment_method);
375
+				if ($form->form_data_present_in($this->_req_data)) {
376
+					$form->receive_form_submission($this->_req_data);
377 377
 				}
378
-				echo $form->form_open() . $form->get_html_and_js() . $form->form_close();
378
+				echo $form->form_open().$form->get_html_and_js().$form->form_close();
379 379
 		} else {
380
-			echo $this->_activate_payment_method_button( $payment_method )->get_html_and_js();
380
+			echo $this->_activate_payment_method_button($payment_method)->get_html_and_js();
381 381
 		}
382 382
 	}
383 383
 
@@ -390,14 +390,14 @@  discard block
 block discarded – undo
390 390
 	 * @param \EE_Payment_Method $payment_method
391 391
 	 * @return \EE_Form_Section_Proper
392 392
 	 */
393
-	protected function _generate_payment_method_settings_form( EE_Payment_Method $payment_method ) {
394
-		if ( ! $payment_method instanceof EE_Payment_Method ){
393
+	protected function _generate_payment_method_settings_form(EE_Payment_Method $payment_method) {
394
+		if ( ! $payment_method instanceof EE_Payment_Method) {
395 395
 			return new EE_Form_Section_Proper();
396 396
 		}
397 397
 		return new EE_Form_Section_Proper(
398 398
 			array(
399
-				'name' 	=> $payment_method->slug() . '_settings_form',
400
-				'html_id' 	=> $payment_method->slug() . '_settings_form',
399
+				'name' 	=> $payment_method->slug().'_settings_form',
400
+				'html_id' 	=> $payment_method->slug().'_settings_form',
401 401
 				'action' 	=> EE_Admin_Page::add_query_args_and_nonce(
402 402
 					array(
403 403
 						'action' 						=> 'update_payment_method',
@@ -409,12 +409,12 @@  discard block
 block discarded – undo
409 409
 				'subsections' 			=> apply_filters(
410 410
 					'FHEE__Payments_Admin_Page___generate_payment_method_settings_form__form_subsections',
411 411
 					array(
412
-						'pci_dss_compliance_' . $payment_method->slug() 				=> $this->_pci_dss_compliance( $payment_method ),
413
-						'currency_support_' . $payment_method->slug()					=> $this->_currency_support( $payment_method ),
414
-						'payment_method_settings_' . $payment_method->slug() 	=> $this->_payment_method_settings( $payment_method ),
415
-						'update_' . $payment_method->slug()										=> $this->_update_payment_method_button( $payment_method ),
416
-						'deactivate_' . $payment_method->slug()								=> $this->_deactivate_payment_method_button( $payment_method ),
417
-						'fine_print_' . $payment_method->slug()									=> $this->_fine_print()
412
+						'pci_dss_compliance_'.$payment_method->slug() 				=> $this->_pci_dss_compliance($payment_method),
413
+						'currency_support_'.$payment_method->slug()					=> $this->_currency_support($payment_method),
414
+						'payment_method_settings_'.$payment_method->slug() 	=> $this->_payment_method_settings($payment_method),
415
+						'update_'.$payment_method->slug()										=> $this->_update_payment_method_button($payment_method),
416
+						'deactivate_'.$payment_method->slug()								=> $this->_deactivate_payment_method_button($payment_method),
417
+						'fine_print_'.$payment_method->slug()									=> $this->_fine_print()
418 418
 					),
419 419
 					$payment_method
420 420
 				)
@@ -431,19 +431,19 @@  discard block
 block discarded – undo
431 431
 	 * @param \EE_Payment_Method $payment_method
432 432
 	 * @return \EE_Form_Section_Proper
433 433
 	 */
434
-	protected function _pci_dss_compliance( EE_Payment_Method $payment_method ) {
435
-		if ( $payment_method->type_obj()->requires_https() ) {
434
+	protected function _pci_dss_compliance(EE_Payment_Method $payment_method) {
435
+		if ($payment_method->type_obj()->requires_https()) {
436 436
 			return new EE_Form_Section_HTML(
437 437
 				EEH_HTML::tr(
438 438
 					EEH_HTML::th(
439 439
 						EEH_HTML::label(
440
-							EEH_HTML::strong( __( 'IMPORTANT', 'event_espresso' ), '', 'important-notice' )
440
+							EEH_HTML::strong(__('IMPORTANT', 'event_espresso'), '', 'important-notice')
441 441
 						)
442
-					) .
442
+					).
443 443
 					EEH_HTML::td(
444
-						EEH_HTML::strong( __( 'You are responsible for your own website security and Payment Card Industry Data Security Standards (PCI DSS) compliance.', 'event_espresso' )) .
445
-						EEH_HTML::br() .
446
-						__( 'Learn more about ', 'event_espresso' ) . EEH_HTML::link( 'https://www.pcisecuritystandards.org/merchants/index.php', __( 'PCI DSS compliance', 'event_espresso' ))
444
+						EEH_HTML::strong(__('You are responsible for your own website security and Payment Card Industry Data Security Standards (PCI DSS) compliance.', 'event_espresso')).
445
+						EEH_HTML::br().
446
+						__('Learn more about ', 'event_espresso').EEH_HTML::link('https://www.pcisecuritystandards.org/merchants/index.php', __('PCI DSS compliance', 'event_espresso'))
447 447
 					)
448 448
 				)
449 449
 			);
@@ -461,19 +461,19 @@  discard block
 block discarded – undo
461 461
 	 * @param \EE_Payment_Method $payment_method
462 462
 	 * @return \EE_Form_Section_Proper
463 463
 	 */
464
-	protected function _currency_support( EE_Payment_Method $payment_method ) {
465
-		if ( ! $payment_method->usable_for_currency( EE_Config::instance()->currency->code )) {
464
+	protected function _currency_support(EE_Payment_Method $payment_method) {
465
+		if ( ! $payment_method->usable_for_currency(EE_Config::instance()->currency->code)) {
466 466
 			return new EE_Form_Section_HTML(
467 467
 				EEH_HTML::tr(
468 468
 					EEH_HTML::th(
469 469
 						EEH_HTML::label(
470
-							EEH_HTML::strong( __( 'IMPORTANT', 'event_espresso' ), '', 'important-notice' )
470
+							EEH_HTML::strong(__('IMPORTANT', 'event_espresso'), '', 'important-notice')
471 471
 						)
472
-					) .
472
+					).
473 473
 					EEH_HTML::td(
474 474
 						EEH_HTML::strong(
475 475
 							sprintf(
476
-								__( 'This payment method does not support the currency set on your site (%1$s). Please activate a different payment method or change your site\'s country and associated currency.', 'event_espresso'),
476
+								__('This payment method does not support the currency set on your site (%1$s). Please activate a different payment method or change your site\'s country and associated currency.', 'event_espresso'),
477 477
 								EE_Config::instance()->currency->code
478 478
 							)
479 479
 						)
@@ -493,9 +493,9 @@  discard block
 block discarded – undo
493 493
 	 * @param \EE_Payment_Method $payment_method
494 494
 	 * @return \EE_Form_Section_HTML
495 495
 	 */
496
-	protected function _payment_method_settings( EE_Payment_Method $payment_method ) {
496
+	protected function _payment_method_settings(EE_Payment_Method $payment_method) {
497 497
 		//modify the form so we only have/show fields that will be implemented for this version
498
-		return $this->_simplify_form( $payment_method->type_obj()->settings_form(), $payment_method->name() );
498
+		return $this->_simplify_form($payment_method->type_obj()->settings_form(), $payment_method->name());
499 499
 	}
500 500
 
501 501
 
@@ -508,8 +508,8 @@  discard block
 block discarded – undo
508 508
 	 * @return \EE_Payment_Method_Form
509 509
 	 * @throws \EE_Error
510 510
 	 */
511
-	protected function _simplify_form( $form_section, $payment_method_name = '' ){
512
-		if ( $form_section instanceof EE_Payment_Method_Form ) {
511
+	protected function _simplify_form($form_section, $payment_method_name = '') {
512
+		if ($form_section instanceof EE_Payment_Method_Form) {
513 513
 			$form_section->exclude(
514 514
 				array(
515 515
 					'PMD_type', //dont want them changing the type
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
 			);
521 521
 			return $form_section;
522 522
 		} else {
523
-			throw new EE_Error( sprintf( __( 'The EE_Payment_Method_Form for the "%1$s" payment method is missing or invalid.', 'event_espresso' ), $payment_method_name ));
523
+			throw new EE_Error(sprintf(__('The EE_Payment_Method_Form for the "%1$s" payment method is missing or invalid.', 'event_espresso'), $payment_method_name));
524 524
 		}
525 525
 	}
526 526
 
@@ -533,19 +533,19 @@  discard block
 block discarded – undo
533 533
 	 * @param \EE_Payment_Method $payment_method
534 534
 	 * @return \EE_Form_Section_HTML
535 535
 	 */
536
-	protected function _update_payment_method_button( EE_Payment_Method $payment_method ) {
536
+	protected function _update_payment_method_button(EE_Payment_Method $payment_method) {
537 537
 		$update_button = new EE_Submit_Input(
538 538
 			array(
539 539
 				'name' => 'submit',
540
-				'html_id' 		=> 'save_' . $payment_method->slug() . '_settings',
541
-				'default' 		=> sprintf( __( 'Update %s Payment Settings', 'event_espresso' ), $payment_method->admin_name() ),
540
+				'html_id' 		=> 'save_'.$payment_method->slug().'_settings',
541
+				'default' 		=> sprintf(__('Update %s Payment Settings', 'event_espresso'), $payment_method->admin_name()),
542 542
 				'html_label' => EEH_HTML::nbsp()
543 543
 			)
544 544
 		);
545 545
 		return new EE_Form_Section_HTML(
546
-			EEH_HTML::no_row( EEH_HTML::br(2) ) .
546
+			EEH_HTML::no_row(EEH_HTML::br(2)).
547 547
 			EEH_HTML::tr(
548
-				EEH_HTML::th( __( 'Update Settings', 'event_espresso') ) .
548
+				EEH_HTML::th(__('Update Settings', 'event_espresso')).
549 549
 				EEH_HTML::td(
550 550
 					$update_button->get_html_for_input()
551 551
 				)
@@ -562,11 +562,11 @@  discard block
 block discarded – undo
562 562
 	 * @param \EE_Payment_Method $payment_method
563 563
 	 * @return \EE_Form_Section_Proper
564 564
 	 */
565
-	protected function _deactivate_payment_method_button( EE_Payment_Method $payment_method ) {
566
-		$link_text_and_title = sprintf( __( 'Deactivate %1$s Payments?', 'event_espresso'), $payment_method->admin_name() );
565
+	protected function _deactivate_payment_method_button(EE_Payment_Method $payment_method) {
566
+		$link_text_and_title = sprintf(__('Deactivate %1$s Payments?', 'event_espresso'), $payment_method->admin_name());
567 567
 		return new EE_Form_Section_HTML(
568 568
 			EEH_HTML::tr(
569
-				EEH_HTML::th( __( 'Deactivate Payment Method', 'event_espresso') ) .
569
+				EEH_HTML::th(__('Deactivate Payment Method', 'event_espresso')).
570 570
 				EEH_HTML::td(
571 571
 					EEH_HTML::link(
572 572
 						EE_Admin_Page::add_query_args_and_nonce(
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
 						),
579 579
 						$link_text_and_title,
580 580
 						$link_text_and_title,
581
-						'deactivate_' . $payment_method->slug(),
581
+						'deactivate_'.$payment_method->slug(),
582 582
 						'espresso-button button-secondary'
583 583
 					)
584 584
 				)
@@ -594,12 +594,12 @@  discard block
 block discarded – undo
594 594
 	 * @param \EE_Payment_Method $payment_method
595 595
 	 * @return \EE_Form_Section_Proper
596 596
 	 */
597
-	protected function _activate_payment_method_button( EE_Payment_Method $payment_method ) {
598
-		$link_text_and_title = sprintf( __( 'Activate %1$s Payment Method?', 'event_espresso'), $payment_method->admin_name() );
597
+	protected function _activate_payment_method_button(EE_Payment_Method $payment_method) {
598
+		$link_text_and_title = sprintf(__('Activate %1$s Payment Method?', 'event_espresso'), $payment_method->admin_name());
599 599
 		return new EE_Form_Section_Proper(
600 600
 			array(
601
-				'name' 	=> 'activate_' . $payment_method->slug() . '_settings_form',
602
-				'html_id' 	=> 'activate_' . $payment_method->slug() . '_settings_form',
601
+				'name' 	=> 'activate_'.$payment_method->slug().'_settings_form',
602
+				'html_id' 	=> 'activate_'.$payment_method->slug().'_settings_form',
603 603
 				'action' 	=> '#',
604 604
 				'layout_strategy'		=> new EE_Admin_Two_Column_Layout(),
605 605
 				'subsections' 			=> apply_filters(
@@ -607,17 +607,17 @@  discard block
 block discarded – undo
607 607
 					array(
608 608
 						new EE_Form_Section_HTML(
609 609
 							EEH_HTML::tr(
610
-								EEH_HTML::td( $payment_method->type_obj()->introductory_html(),
610
+								EEH_HTML::td($payment_method->type_obj()->introductory_html(),
611 611
 									'',
612 612
 									'',
613 613
 									'',
614 614
 									'colspan="2"' 
615 615
 								)
616
-							) . 
616
+							). 
617 617
 							EEH_HTML::tr(
618 618
 								EEH_HTML::th(
619
-									EEH_HTML::label( __( 'Click to Activate ', 'event_espresso' ))
620
-								) .
619
+									EEH_HTML::label(__('Click to Activate ', 'event_espresso'))
620
+								).
621 621
 								EEH_HTML::td(
622 622
 									EEH_HTML::link(
623 623
 										EE_Admin_Page::add_query_args_and_nonce(
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
 										),
630 630
 										$link_text_and_title,
631 631
 										$link_text_and_title,
632
-										'activate_' . $payment_method->slug(),
632
+										'activate_'.$payment_method->slug(),
633 633
 										'espresso-button-green button-primary'
634 634
 									)
635 635
 								)
@@ -651,9 +651,9 @@  discard block
 block discarded – undo
651 651
 	protected function _fine_print() {
652 652
 		return new EE_Form_Section_HTML(
653 653
 			EEH_HTML::tr(
654
-				EEH_HTML::th() .
654
+				EEH_HTML::th().
655 655
 				EEH_HTML::td(
656
-					EEH_HTML::p( __( 'All fields marked with a * are required fields', 'event_espresso' ), '', 'grey-text' )
656
+					EEH_HTML::p(__('All fields marked with a * are required fields', 'event_espresso'), '', 'grey-text')
657 657
 				)
658 658
 			)
659 659
 		);
@@ -665,15 +665,15 @@  discard block
 block discarded – undo
665 665
 	 * Activates a payment method of that type. Mostly assuming there is only 1 of that type (or none so far)
666 666
 	 * @global WP_User $current_user
667 667
 	 */
668
-	protected function _activate_payment_method(){
669
-		if(isset($this->_req_data['payment_method_type'])){
668
+	protected function _activate_payment_method() {
669
+		if (isset($this->_req_data['payment_method_type'])) {
670 670
 			$payment_method_type = sanitize_text_field($this->_req_data['payment_method_type']);
671 671
 			//see if one exists
672
-			EE_Registry::instance()->load_lib( 'Payment_Method_Manager' );
673
-			$payment_method = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type( $payment_method_type );
672
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
673
+			$payment_method = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type($payment_method_type);
674 674
 
675
-			$this->_redirect_after_action(1, 'Payment Method', 'activated', array('action' => 'default','payment_method'=>$payment_method->slug()));
676
-		}else{
675
+			$this->_redirect_after_action(1, 'Payment Method', 'activated', array('action' => 'default', 'payment_method'=>$payment_method->slug()));
676
+		} else {
677 677
 			$this->_redirect_after_action(FALSE, 'Payment Method', 'activated', array('action' => 'default'));
678 678
 		}
679 679
 	}
@@ -681,14 +681,14 @@  discard block
 block discarded – undo
681 681
 	/**
682 682
 	 * Deactivates the payment method with the specified slug, and redirects.
683 683
 	 */
684
-	protected function _deactivate_payment_method(){
685
-		if(isset($this->_req_data['payment_method'])){
684
+	protected function _deactivate_payment_method() {
685
+		if (isset($this->_req_data['payment_method'])) {
686 686
 			$payment_method_slug = sanitize_key($this->_req_data['payment_method']);
687 687
 			//deactivate it
688 688
 			EE_Registry::instance()->load_lib('Payment_Method_Manager');
689
-			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method( $payment_method_slug );
690
-			$this->_redirect_after_action($count_updated, 'Payment Method', 'deactivated', array('action' => 'default','payment_method'=>$payment_method_slug));
691
-		}else{
689
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method($payment_method_slug);
690
+			$this->_redirect_after_action($count_updated, 'Payment Method', 'deactivated', array('action' => 'default', 'payment_method'=>$payment_method_slug));
691
+		} else {
692 692
 			$this->_redirect_after_action(FALSE, 'Payment Method', 'deactivated', array('action' => 'default'));
693 693
 		}
694 694
 	}
@@ -702,46 +702,46 @@  discard block
 block discarded – undo
702 702
 	 * subsequently called 'headers_sent_func' which is _payment_methods_list)
703 703
 	 * @return void
704 704
 	 */
705
-	protected function _update_payment_method(){
706
-		if( $_SERVER['REQUEST_METHOD'] == 'POST'){
705
+	protected function _update_payment_method() {
706
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
707 707
 			//ok let's find which gateway form to use based on the form input
708 708
 			EE_Registry::instance()->load_lib('Payment_Method_Manager');
709 709
 			/** @var $correct_pmt_form_to_use EE_Payment_Method_Form */
710 710
 			$correct_pmt_form_to_use = NULL;
711 711
 			$payment_method = NULL;
712
-			foreach( EEM_Payment_Method::instance()->get_all() as $payment_method){
712
+			foreach (EEM_Payment_Method::instance()->get_all() as $payment_method) {
713 713
 				//get the form and simplify it, like what we do when we display it
714
-				$pmt_form = $this->_generate_payment_method_settings_form( $payment_method );
715
-				if($pmt_form->form_data_present_in($this->_req_data)){
714
+				$pmt_form = $this->_generate_payment_method_settings_form($payment_method);
715
+				if ($pmt_form->form_data_present_in($this->_req_data)) {
716 716
 					$correct_pmt_form_to_use = $pmt_form;
717 717
 					break;
718 718
 				}
719 719
 			}
720 720
 			//if we couldn't find the correct payment method type...
721
-			if( ! $correct_pmt_form_to_use ){
721
+			if ( ! $correct_pmt_form_to_use) {
722 722
 				EE_Error::add_error(__("We could not find which payment method type your form submission related to. Please contact support", 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
723 723
 				$this->_redirect_after_action(FALSE, 'Payment Method', 'activated', array('action' => 'default'));
724 724
 			}
725 725
 			$correct_pmt_form_to_use->receive_form_submission($this->_req_data);
726
-			if($correct_pmt_form_to_use->is_valid()){
727
-				$subsection_name = 'payment_method_settings_' . $payment_method->slug();
728
-				$payment_settings_subform = $correct_pmt_form_to_use->get_subsection( $subsection_name );
729
-				if( ! $payment_settings_subform instanceof EE_Payment_Method_Form ) {
726
+			if ($correct_pmt_form_to_use->is_valid()) {
727
+				$subsection_name = 'payment_method_settings_'.$payment_method->slug();
728
+				$payment_settings_subform = $correct_pmt_form_to_use->get_subsection($subsection_name);
729
+				if ( ! $payment_settings_subform instanceof EE_Payment_Method_Form) {
730 730
 					throw new EE_Error( 
731 731
 						sprintf(
732
-							__( 'The payment method could not be saved because the form sections were misnamed. We expected to find %1$s, but did not.','event_espresso' ),
732
+							__('The payment method could not be saved because the form sections were misnamed. We expected to find %1$s, but did not.', 'event_espresso'),
733 733
 							$subsection_name
734 734
 						)
735 735
 					);
736 736
 				}
737 737
 				$payment_settings_subform->save();
738 738
 				/** @var $pm EE_Payment_Method */
739
-				$this->_redirect_after_action(TRUE, 'Payment Method', 'updated', array('action' => 'default','payment_method'=>$payment_method->slug()));
740
-			}else{
739
+				$this->_redirect_after_action(TRUE, 'Payment Method', 'updated', array('action' => 'default', 'payment_method'=>$payment_method->slug()));
740
+			} else {
741 741
 				EE_Error::add_error(
742 742
 					sprintf(
743 743
 						__('Payment method of type %s was not saved because there were validation errors. They have been marked in the form', 'event_espresso'),
744
-						$payment_method instanceof EE_PMT_Base ? $payment_method->pretty_name() : __( '"(unknown)"', 'event_espresso' )
744
+						$payment_method instanceof EE_PMT_Base ? $payment_method->pretty_name() : __('"(unknown)"', 'event_espresso')
745 745
 					),
746 746
 					__FILE__,
747 747
 					__FUNCTION__,
@@ -758,11 +758,11 @@  discard block
 block discarded – undo
758 758
 	protected function _payment_settings() {
759 759
 
760 760
 		$this->_template_args['values'] = $this->_yes_no_values;
761
-		$this->_template_args['show_pending_payment_options'] = isset( EE_Registry::instance()->CFG->registration->show_pending_payment_options ) ? absint( EE_Registry::instance()->CFG->registration->show_pending_payment_options ) : FALSE;
761
+		$this->_template_args['show_pending_payment_options'] = isset(EE_Registry::instance()->CFG->registration->show_pending_payment_options) ? absint(EE_Registry::instance()->CFG->registration->show_pending_payment_options) : FALSE;
762 762
 
763
-		$this->_set_add_edit_form_tags( 'update_payment_settings' );
764
-		$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
765
-		$this->_template_args['admin_page_content'] = EEH_Template::display_template( EE_PAYMENTS_TEMPLATE_PATH . 'payment_settings.template.php', $this->_template_args, TRUE );
763
+		$this->_set_add_edit_form_tags('update_payment_settings');
764
+		$this->_set_publish_post_box_vars(NULL, FALSE, FALSE, NULL, FALSE);
765
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(EE_PAYMENTS_TEMPLATE_PATH.'payment_settings.template.php', $this->_template_args, TRUE);
766 766
 		$this->display_admin_page_with_sidebar();
767 767
 
768 768
 	}
@@ -776,8 +776,8 @@  discard block
 block discarded – undo
776 776
 	*		@return array
777 777
 	*/
778 778
 	protected function _update_payment_settings() {
779
-		EE_Registry::instance()->CFG->registration->show_pending_payment_options = isset( $this->_req_data['show_pending_payment_options'] ) ? $this->_req_data['show_pending_payment_options'] : FALSE;
780
-		EE_Registry::instance()->CFG = apply_filters( 'FHEE__Payments_Admin_Page___update_payment_settings__CFG', EE_Registry::instance()->CFG );
779
+		EE_Registry::instance()->CFG->registration->show_pending_payment_options = isset($this->_req_data['show_pending_payment_options']) ? $this->_req_data['show_pending_payment_options'] : FALSE;
780
+		EE_Registry::instance()->CFG = apply_filters('FHEE__Payments_Admin_Page___update_payment_settings__CFG', EE_Registry::instance()->CFG);
781 781
 
782 782
 //		 $superform = new EE_Form_Section_Proper(
783 783
 //		 	array(
@@ -797,9 +797,9 @@  discard block
 block discarded – undo
797 797
 //		 	$this->_redirect_after_action( 0, 'settings', 'updated', array( 'action' => 'payment_settings' ) );
798 798
 //		 }
799 799
 
800
-		$what = __('Payment Settings','event_espresso');
801
-		$success = $this->_update_espresso_configuration( $what, EE_Registry::instance()->CFG, __FILE__, __FUNCTION__, __LINE__ );
802
-		$this->_redirect_after_action( $success, $what, __('updated','event_espresso'), array( 'action' => 'payment_settings' ) );
800
+		$what = __('Payment Settings', 'event_espresso');
801
+		$success = $this->_update_espresso_configuration($what, EE_Registry::instance()->CFG, __FILE__, __FUNCTION__, __LINE__);
802
+		$this->_redirect_after_action($success, $what, __('updated', 'event_espresso'), array('action' => 'payment_settings'));
803 803
 
804 804
 	}
805 805
 	protected function _payment_log_overview_list_table() {
@@ -825,18 +825,18 @@  discard block
 block discarded – undo
825 825
 	 * @param bool $count
826 826
 	 * @return array
827 827
 	 */
828
-	public function get_payment_logs($per_page = 50, $current_page = 0, $count = false){
829
-		EE_Registry::instance()->load_model( 'Change_Log' );
828
+	public function get_payment_logs($per_page = 50, $current_page = 0, $count = false) {
829
+		EE_Registry::instance()->load_model('Change_Log');
830 830
 		//we may need to do multiple queries (joining differently), so we actually wan tan array of query params
831
-		$query_params =  array(array('LOG_type'=>  EEM_Change_Log::type_gateway));
831
+		$query_params = array(array('LOG_type'=>  EEM_Change_Log::type_gateway));
832 832
 		//check if they've selected a specific payment method
833
-		if( isset($this->_req_data['_payment_method']) && $this->_req_data['_payment_method'] !== 'all'){
833
+		if (isset($this->_req_data['_payment_method']) && $this->_req_data['_payment_method'] !== 'all') {
834 834
 			$query_params[0]['OR*pm_or_pay_pm'] = array('Payment.Payment_Method.PMD_ID'=>$this->_req_data['_payment_method'],
835 835
 				'Payment_Method.PMD_ID'=>$this->_req_data['_payment_method']);
836 836
 		}
837 837
 		//take into account search
838
-		if(isset($this->_req_data['s']) && $this->_req_data['s']){
839
-			$similarity_string = array('LIKE','%'.str_replace("","%",$this->_req_data['s']) .'%');
838
+		if (isset($this->_req_data['s']) && $this->_req_data['s']) {
839
+			$similarity_string = array('LIKE', '%'.str_replace("", "%", $this->_req_data['s']).'%');
840 840
 			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_fname'] = $similarity_string;
841 841
 			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_lname'] = $similarity_string;
842 842
 			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_email'] = $similarity_string;
@@ -851,48 +851,48 @@  discard block
 block discarded – undo
851 851
 			$query_params[0]['OR*s']['LOG_message'] = $similarity_string;
852 852
 
853 853
 		}
854
-		if(isset( $this->_req_data['payment-filter-start-date'] ) && isset( $this->_req_data['payment-filter-end-date'] )){
854
+		if (isset($this->_req_data['payment-filter-start-date']) && isset($this->_req_data['payment-filter-end-date'])) {
855 855
 			//add date
856
-			$start_date =wp_strip_all_tags( $this->_req_data['payment-filter-start-date'] );
857
-			$end_date = wp_strip_all_tags( $this->_req_data['payment-filter-end-date'] );
856
+			$start_date = wp_strip_all_tags($this->_req_data['payment-filter-start-date']);
857
+			$end_date = wp_strip_all_tags($this->_req_data['payment-filter-end-date']);
858 858
 			//make sure our timestamps start and end right at the boundaries for each day
859
-			$start_date = date( 'Y-m-d', strtotime( $start_date ) ) . ' 00:00:00';
860
-			$end_date = date( 'Y-m-d', strtotime( $end_date ) ) . ' 23:59:59';
859
+			$start_date = date('Y-m-d', strtotime($start_date)).' 00:00:00';
860
+			$end_date = date('Y-m-d', strtotime($end_date)).' 23:59:59';
861 861
 
862 862
 			//convert to timestamps
863
-			$start_date = strtotime( $start_date );
864
-			$end_date = strtotime( $end_date );
863
+			$start_date = strtotime($start_date);
864
+			$end_date = strtotime($end_date);
865 865
 
866 866
 			//makes sure start date is the lowest value and vice versa
867
-			$start_date = min( $start_date, $end_date );
868
-			$end_date = max( $start_date, $end_date );
867
+			$start_date = min($start_date, $end_date);
868
+			$end_date = max($start_date, $end_date);
869 869
 
870 870
 			//convert for query
871
-			$start_date = EEM_Change_Log::instance()->convert_datetime_for_query( 'LOG_time', date( 'Y-m-d H:i:s', $start_date ), 'Y-m-d H:i:s' );
872
-			$end_date = EEM_Change_Log::instance()->convert_datetime_for_query( 'LOG_time', date( 'Y-m-d H:i:s', $end_date ), 'Y-m-d H:i:s' );
871
+			$start_date = EEM_Change_Log::instance()->convert_datetime_for_query('LOG_time', date('Y-m-d H:i:s', $start_date), 'Y-m-d H:i:s');
872
+			$end_date = EEM_Change_Log::instance()->convert_datetime_for_query('LOG_time', date('Y-m-d H:i:s', $end_date), 'Y-m-d H:i:s');
873 873
 
874
-			$query_params[0]['LOG_time'] = array('BETWEEN',array($start_date,$end_date));
874
+			$query_params[0]['LOG_time'] = array('BETWEEN', array($start_date, $end_date));
875 875
 
876 876
 		}
877
-		if($count){
877
+		if ($count) {
878 878
 			return EEM_Change_Log::instance()->count($query_params);
879 879
 		}
880
-		if(isset($this->_req_data['order'])){
881
-			$sort = ( isset( $this->_req_data['order'] ) && ! empty( $this->_req_data['order'] )) ? $this->_req_data['order'] : 'DESC';
880
+		if (isset($this->_req_data['order'])) {
881
+			$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'DESC';
882 882
 			$query_params['order_by'] = array('LOG_time' => $sort);
883
-		}else{
883
+		} else {
884 884
 				$query_params['order_by'] = array('LOG_time' => 'DESC');
885 885
 		}
886
-		$offset = ($current_page-1)*$per_page;
886
+		$offset = ($current_page - 1) * $per_page;
887 887
 
888
-		if( ! isset($this->_req_data['download_results'])){
889
-			$query_params['limit'] = array( $offset, $per_page );
888
+		if ( ! isset($this->_req_data['download_results'])) {
889
+			$query_params['limit'] = array($offset, $per_page);
890 890
 		}
891 891
 
892 892
 
893 893
 
894 894
 		//now they've requested to instead just download the file instead of viewing it.
895
-		if(isset($this->_req_data['download_results'])){
895
+		if (isset($this->_req_data['download_results'])) {
896 896
 			$wpdb_results = EEM_Change_Log::instance()->get_all_efficiently($query_params);
897 897
 			header('Content-Disposition: attachment');
898 898
 			header("Content-Disposition: attachment; filename=ee_payment_logs_for_".sanitize_key(site_url()));
@@ -914,36 +914,36 @@  discard block
 block discarded – undo
914 914
 	 * @param EE_Change_Log $logB
915 915
 	 * @return int
916 916
 	 */
917
-	protected function _sort_logs_again($logA,$logB){
917
+	protected function _sort_logs_again($logA, $logB) {
918 918
 		$timeA = $logA->get_raw('LOG_time');
919 919
 		$timeB = $logB->get_raw('LOG_time');
920
-		if($timeA == $timeB){
920
+		if ($timeA == $timeB) {
921 921
 			return 0;
922 922
 		}
923 923
 		$comparison = $timeA < $timeB ? -1 : 1;
924
-		if(strtoupper($this->_sort_logs_again_direction) == 'DESC'){
924
+		if (strtoupper($this->_sort_logs_again_direction) == 'DESC') {
925 925
 			return $comparison * -1;
926
-		}else{
926
+		} else {
927 927
 			return $comparison;
928 928
 		}
929 929
 	}
930 930
 
931 931
 	protected function _payment_log_details() {
932
-		EE_Registry::instance()->load_model( 'Change_Log' );
932
+		EE_Registry::instance()->load_model('Change_Log');
933 933
 		/** @var $payment_log EE_Change_Log */
934 934
 		$payment_log = EEM_Change_Log::instance()->get_one_by_ID($this->_req_data['ID']);
935 935
 		$payment_method = NULL;
936 936
 		$transaction = NULL;
937
-		if( $payment_log instanceof EE_Change_Log ){
938
-			if( $payment_log->object() instanceof EE_Payment ){
937
+		if ($payment_log instanceof EE_Change_Log) {
938
+			if ($payment_log->object() instanceof EE_Payment) {
939 939
 				$payment_method = $payment_log->object()->payment_method();
940 940
 				$transaction = $payment_log->object()->transaction();
941
-			}elseif($payment_log->object() instanceof EE_Payment_Method){
941
+			}elseif ($payment_log->object() instanceof EE_Payment_Method) {
942 942
 				$payment_method = $payment_log->object();
943 943
 			}
944 944
 		}
945 945
 		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
946
-			EE_PAYMENTS_TEMPLATE_PATH . 'payment_log_details.template.php',
946
+			EE_PAYMENTS_TEMPLATE_PATH.'payment_log_details.template.php',
947 947
 			array(
948 948
 				'payment_log'=>$payment_log,
949 949
 				'payment_method'=>$payment_method,
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 2 patches
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -358,13 +358,13 @@  discard block
 block discarded – undo
358 358
 
359 359
 
360 360
 
361
-    /**
362
-     * get event start date.  Provide either the date format, or NULL to re-use the
363
-     * last-used format, or '' to use the default date format
364
-     *
365
-     * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366
-     * @return        mixed        string on success, FALSE on fail
367
-     */
361
+	/**
362
+	 * get event start date.  Provide either the date format, or NULL to re-use the
363
+	 * last-used format, or '' to use the default date format
364
+	 *
365
+	 * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366
+	 * @return        mixed        string on success, FALSE on fail
367
+	 */
368 368
 	public function start_date( $dt_frmt = '' ) {
369 369
 		return $this->_show_datetime( 'D', 'start', $dt_frmt );
370 370
 	}
@@ -381,13 +381,13 @@  discard block
 block discarded – undo
381 381
 
382 382
 
383 383
 
384
-    /**
385
-     * get end date. Provide either the date format, or NULL to re-use the
386
-     * last-used format, or '' to use the default date format
387
-     *
388
-     * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389
-     * @return        mixed        string on success, FALSE on fail
390
-     */
384
+	/**
385
+	 * get end date. Provide either the date format, or NULL to re-use the
386
+	 * last-used format, or '' to use the default date format
387
+	 *
388
+	 * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389
+	 * @return        mixed        string on success, FALSE on fail
390
+	 */
391 391
 	public function end_date( $dt_frmt = '' ) {
392 392
 		return $this->_show_datetime( 'D', 'end', $dt_frmt );
393 393
 	}
@@ -509,23 +509,23 @@  discard block
 block discarded – undo
509 509
 	/**
510 510
 	 * This returns a range representation of the date and times.
511 511
 	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
512
-     * Also, the return value is localized.
513
-     *
514
-     * @param string $dt_format
512
+	 * Also, the return value is localized.
513
+	 *
514
+	 * @param string $dt_format
515 515
 	 * @param string $tm_format
516 516
 	 * @param string $conjunction used between two different dates or times.
517
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
518
-     * @param string $separator   used between the date and time formats.
519
-     *                            ex: Dec 1, 2016{$separator}2pm
517
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
518
+	 * @param string $separator   used between the date and time formats.
519
+	 *                            ex: Dec 1, 2016{$separator}2pm
520 520
 	 * @return string
521 521
 	 * @throws \EE_Error
522 522
 	 */
523 523
 	public function date_and_time_range(
524
-	    $dt_format = '',
525
-        $tm_format = '',
526
-        $conjunction = ' - ' ,
527
-        $separator = ' '
528
-    ) {
524
+		$dt_format = '',
525
+		$tm_format = '',
526
+		$conjunction = ' - ' ,
527
+		$separator = ' '
528
+	) {
529 529
 		$dt_format = ! empty( $dt_format ) ? $dt_format : $this->_dt_frmt;
530 530
 		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
531 531
 		$full_format = $dt_format . $separator . $tm_format;
@@ -539,14 +539,14 @@  discard block
 block discarded – undo
539 539
 			//start and end date are the same but times are different
540 540
 			case ( $this->start_date() === $this->end_date() ) :
541 541
 				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
542
-				          . $conjunction
543
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
542
+						  . $conjunction
543
+						  . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
544 544
 				break;
545 545
 			//all other conditions
546 546
 			default :
547 547
 				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
548
-				          . $conjunction
549
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
548
+						  . $conjunction
549
+						  . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
550 550
 				break;
551 551
 		}
552 552
 		return $output;
@@ -630,13 +630,13 @@  discard block
 block discarded – undo
630 630
 
631 631
 
632 632
 	/**
633
-     *        get end date and time
634
-     *
635
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
636
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
637
-     * @return    mixed                string on success, FALSE on fail
638
-     */
639
-    public function end_date_and_time($dt_frmt = '', $tm_format = '') {
633
+	 *        get end date and time
634
+	 *
635
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
636
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
637
+	 * @return    mixed                string on success, FALSE on fail
638
+	 */
639
+	public function end_date_and_time($dt_frmt = '', $tm_format = '') {
640 640
 		return $this->_show_datetime( '', 'end', $dt_frmt, $tm_format );
641 641
 	}
642 642
 
Please login to merge, or discard this patch.
Spacing   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -74,9 +74,9 @@  discard block
 block discarded – undo
74 74
 	 *                             		    date_format and the second value is the time format
75 75
 	 * @return EE_Datetime
76 76
 	 */
77
-	public static function new_instance( $props_n_values = array(), $timezone = null, $date_formats = array() ) {
78
-		$has_object = parent::_check_for_object( $props_n_values, __CLASS__, $timezone, $date_formats );
79
-		return $has_object ? $has_object : new self( $props_n_values, false, $timezone, $date_formats );
77
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array()) {
78
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
79
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
80 80
 	}
81 81
 
82 82
 
@@ -87,8 +87,8 @@  discard block
 block discarded – undo
87 87
 	 *                          		the website will be used.
88 88
 	 * @return EE_Datetime
89 89
 	 */
90
-	public static function new_instance_from_db( $props_n_values = array(), $timezone = null ) {
91
-		return new self( $props_n_values, TRUE, $timezone );
90
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null) {
91
+		return new self($props_n_values, TRUE, $timezone);
92 92
 	}
93 93
 
94 94
 
@@ -96,8 +96,8 @@  discard block
 block discarded – undo
96 96
 	/**
97 97
 	 * @param $name
98 98
 	 */
99
-	public function set_name( $name ) {
100
-		$this->set( 'DTT_name', $name );
99
+	public function set_name($name) {
100
+		$this->set('DTT_name', $name);
101 101
 	}
102 102
 
103 103
 
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 	/**
106 106
 	 * @param $description
107 107
 	 */
108
-	public function set_description( $description ) {
109
-		$this->set( 'DTT_description', $description );
108
+	public function set_description($description) {
109
+		$this->set('DTT_description', $description);
110 110
 	}
111 111
 
112 112
 
@@ -118,8 +118,8 @@  discard block
 block discarded – undo
118 118
 	 *
119 119
 	 * @param        string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
120 120
 	 */
121
-	public function set_start_date( $date ) {
122
-		$this->_set_date_for( $date, 'DTT_EVT_start' );
121
+	public function set_start_date($date) {
122
+		$this->_set_date_for($date, 'DTT_EVT_start');
123 123
 	}
124 124
 
125 125
 
@@ -131,8 +131,8 @@  discard block
 block discarded – undo
131 131
 	 *
132 132
 	 * @param        string $time a string representation of the event time ex:  9am  or  7:30 PM
133 133
 	 */
134
-	public function set_start_time( $time ) {
135
-		$this->_set_time_for( $time, 'DTT_EVT_start' );
134
+	public function set_start_time($time) {
135
+		$this->_set_time_for($time, 'DTT_EVT_start');
136 136
 	}
137 137
 
138 138
 
@@ -144,8 +144,8 @@  discard block
 block discarded – undo
144 144
 	 *
145 145
 	 * @param        string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
146 146
 	 */
147
-	public function set_end_date( $date ) {
148
-		$this->_set_date_for( $date, 'DTT_EVT_end' );
147
+	public function set_end_date($date) {
148
+		$this->_set_date_for($date, 'DTT_EVT_end');
149 149
 	}
150 150
 
151 151
 
@@ -157,8 +157,8 @@  discard block
 block discarded – undo
157 157
 	 *
158 158
 	 * @param        string $time a string representation of the event time ex:  9am  or  7:30 PM
159 159
 	 */
160
-	public function set_end_time( $time ) {
161
-		$this->_set_time_for( $time, 'DTT_EVT_end' );
160
+	public function set_end_time($time) {
161
+		$this->_set_time_for($time, 'DTT_EVT_end');
162 162
 	}
163 163
 
164 164
 
@@ -170,8 +170,8 @@  discard block
 block discarded – undo
170 170
 	 *
171 171
 	 * @param        int $reg_limit
172 172
 	 */
173
-	public function set_reg_limit( $reg_limit ) {
174
-		$this->set( 'DTT_reg_limit', $reg_limit );
173
+	public function set_reg_limit($reg_limit) {
174
+		$this->set('DTT_reg_limit', $reg_limit);
175 175
 	}
176 176
 
177 177
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 	 * @return        mixed        int on success, FALSE on fail
184 184
 	 */
185 185
 	public function sold() {
186
-		return $this->get_raw( 'DTT_sold' );
186
+		return $this->get_raw('DTT_sold');
187 187
 	}
188 188
 
189 189
 
@@ -193,10 +193,10 @@  discard block
 block discarded – undo
193 193
 	 *
194 194
 	 * @param        int $sold
195 195
 	 */
196
-	public function set_sold( $sold ) {
196
+	public function set_sold($sold) {
197 197
 		// sold can not go below zero
198
-		$sold = max( 0, $sold );
199
-		$this->set( 'DTT_sold', $sold );
198
+		$sold = max(0, $sold);
199
+		$this->set('DTT_sold', $sold);
200 200
 	}
201 201
 
202 202
 
@@ -205,11 +205,11 @@  discard block
 block discarded – undo
205 205
 	 * increments sold by amount passed by $qty
206 206
 	 * @param int $qty
207 207
 	 */
208
-	public function increase_sold( $qty = 1 ) {
208
+	public function increase_sold($qty = 1) {
209 209
 		$sold = $this->sold() + $qty;
210 210
 		// remove ticket reservation
211
-		$this->decrease_reserved( $qty );
212
-		$this->set_sold( $sold );
211
+		$this->decrease_reserved($qty);
212
+		$this->set_sold($sold);
213 213
 	}
214 214
 
215 215
 
@@ -218,9 +218,9 @@  discard block
 block discarded – undo
218 218
 	 * decrements (subtracts) sold amount passed by $qty
219 219
 	 * @param int $qty
220 220
 	 */
221
-	public function decrease_sold( $qty = 1 ) {
221
+	public function decrease_sold($qty = 1) {
222 222
 		$sold = $this->sold() - $qty;
223
-		$this->set_sold( $sold );
223
+		$this->set_sold($sold);
224 224
 	}
225 225
 
226 226
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 	 * @return int
232 232
 	 */
233 233
 	public function reserved() {
234
-		return $this->get_raw( 'DTT_reserved' );
234
+		return $this->get_raw('DTT_reserved');
235 235
 	}
236 236
 
237 237
 
@@ -241,10 +241,10 @@  discard block
 block discarded – undo
241 241
 	 *
242 242
 	 * @param int $reserved
243 243
 	 */
244
-	public function set_reserved( $reserved ) {
244
+	public function set_reserved($reserved) {
245 245
 		// reserved can not go below zero
246
-		$reserved = max( 0, (int) $reserved );
247
-		$this->set( 'DTT_reserved', $reserved );
246
+		$reserved = max(0, (int) $reserved);
247
+		$this->set('DTT_reserved', $reserved);
248 248
 	}
249 249
 
250 250
 
@@ -255,9 +255,9 @@  discard block
 block discarded – undo
255 255
 	 * @param int $qty
256 256
 	 * @return boolean
257 257
 	 */
258
-	public function increase_reserved( $qty = 1 ) {
259
-		$reserved = $this->reserved() + absint( $qty );
260
-		return $this->set_reserved( $reserved );
258
+	public function increase_reserved($qty = 1) {
259
+		$reserved = $this->reserved() + absint($qty);
260
+		return $this->set_reserved($reserved);
261 261
 	}
262 262
 
263 263
 
@@ -268,9 +268,9 @@  discard block
 block discarded – undo
268 268
 	 * @param int $qty
269 269
 	 * @return boolean
270 270
 	 */
271
-	public function decrease_reserved( $qty = 1 ) {
272
-		$reserved = $this->reserved() - absint( $qty );
273
-		return $this->set_reserved( $reserved );
271
+	public function decrease_reserved($qty = 1) {
272
+		$reserved = $this->reserved() - absint($qty);
273
+		return $this->set_reserved($reserved);
274 274
 	}
275 275
 
276 276
 
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
 	 * @return string
292 292
 	 */
293 293
 	public function name() {
294
-		return $this->get( 'DTT_name' );
294
+		return $this->get('DTT_name');
295 295
 	}
296 296
 
297 297
 
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	 * @return string
302 302
 	 */
303 303
 	public function description() {
304
-		return $this->get( 'DTT_description' );
304
+		return $this->get('DTT_description');
305 305
 	}
306 306
 
307 307
 
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
 	 * @return boolean          TRUE if is primary, FALSE if not.
312 312
 	 */
313 313
 	public function is_primary() {
314
-		return $this->get( 'DTT_is_primary' );
314
+		return $this->get('DTT_is_primary');
315 315
 	}
316 316
 
317 317
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
 	 * @return int         The order of the datetime for this event.
322 322
 	 */
323 323
 	public function order() {
324
-		return $this->get( 'DTT_order' );
324
+		return $this->get('DTT_order');
325 325
 	}
326 326
 
327 327
 
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 	 * @return int
332 332
 	 */
333 333
 	public function parent() {
334
-		return $this->get( 'DTT_parent' );
334
+		return $this->get('DTT_parent');
335 335
 	}
336 336
 
337 337
 
@@ -347,10 +347,10 @@  discard block
 block discarded – undo
347 347
 	 * @param    bool   $echo         - whether we echo or return (note echoing uses "pretty" formats, otherwise we use the standard formats)
348 348
 	 * @return    string|bool  string on success, FALSE on fail
349 349
 	 */
350
-	private function _show_datetime( $date_or_time = NULL, $start_or_end = 'start', $dt_frmt = '', $tm_frmt = '', $echo = FALSE ) {
350
+	private function _show_datetime($date_or_time = NULL, $start_or_end = 'start', $dt_frmt = '', $tm_frmt = '', $echo = FALSE) {
351 351
 		$field_name = "DTT_EVT_{$start_or_end}";
352
-		$dtt = $this->_get_datetime( $field_name, $dt_frmt, $tm_frmt, $date_or_time, $echo );
353
-		if ( ! $echo ) {
352
+		$dtt = $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, $date_or_time, $echo);
353
+		if ( ! $echo) {
354 354
 			return $dtt;
355 355
 		}
356 356
 		return '';
@@ -365,8 +365,8 @@  discard block
 block discarded – undo
365 365
      * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
366 366
      * @return        mixed        string on success, FALSE on fail
367 367
      */
368
-	public function start_date( $dt_frmt = '' ) {
369
-		return $this->_show_datetime( 'D', 'start', $dt_frmt );
368
+	public function start_date($dt_frmt = '') {
369
+		return $this->_show_datetime('D', 'start', $dt_frmt);
370 370
 	}
371 371
 
372 372
 
@@ -375,8 +375,8 @@  discard block
 block discarded – undo
375 375
 	 * Echoes start_date()
376 376
 	 * @param string $dt_frmt
377 377
 	 */
378
-	public function e_start_date( $dt_frmt = '' ) {
379
-		$this->_show_datetime( 'D', 'start', $dt_frmt, NULL, TRUE );
378
+	public function e_start_date($dt_frmt = '') {
379
+		$this->_show_datetime('D', 'start', $dt_frmt, NULL, TRUE);
380 380
 	}
381 381
 
382 382
 
@@ -388,8 +388,8 @@  discard block
 block discarded – undo
388 388
      * @param string $dt_frmt - string representation of date format defaults to 'F j, Y'
389 389
      * @return        mixed        string on success, FALSE on fail
390 390
      */
391
-	public function end_date( $dt_frmt = '' ) {
392
-		return $this->_show_datetime( 'D', 'end', $dt_frmt );
391
+	public function end_date($dt_frmt = '') {
392
+		return $this->_show_datetime('D', 'end', $dt_frmt);
393 393
 	}
394 394
 
395 395
 
@@ -398,8 +398,8 @@  discard block
 block discarded – undo
398 398
 	 * Echoes the end date. See end_date()
399 399
 	 * @param string $dt_frmt
400 400
 	 */
401
-	public function e_end_date( $dt_frmt = '' ) {
402
-		$this->_show_datetime( 'D', 'end', $dt_frmt, NULL, TRUE );
401
+	public function e_end_date($dt_frmt = '') {
402
+		$this->_show_datetime('D', 'end', $dt_frmt, NULL, TRUE);
403 403
 	}
404 404
 
405 405
 
@@ -414,11 +414,11 @@  discard block
 block discarded – undo
414 414
 	 * @return mixed        string on success, FALSE on fail
415 415
 	 * @throws \EE_Error
416 416
 	 */
417
-	public function date_range( $dt_frmt = '', $conjunction = ' - ' ) {
418
-		$dt_frmt = ! empty( $dt_frmt ) ? $dt_frmt : $this->_dt_frmt;
419
-		$start = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_start', $dt_frmt ) );
420
-		$end = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_end', $dt_frmt ) );
421
-		return $start !== $end ? $start . $conjunction . $end : $start;
417
+	public function date_range($dt_frmt = '', $conjunction = ' - ') {
418
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
419
+		$start = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt));
420
+		$end = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt));
421
+		return $start !== $end ? $start.$conjunction.$end : $start;
422 422
 	}
423 423
 
424 424
 
@@ -428,8 +428,8 @@  discard block
 block discarded – undo
428 428
 	 * @param string $conjunction
429 429
 	 * @throws \EE_Error
430 430
 	 */
431
-	public function e_date_range( $dt_frmt = '', $conjunction = ' - ' ) {
432
-		echo $this->date_range( $dt_frmt, $conjunction );
431
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ') {
432
+		echo $this->date_range($dt_frmt, $conjunction);
433 433
 	}
434 434
 
435 435
 
@@ -440,8 +440,8 @@  discard block
 block discarded – undo
440 440
 	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
441 441
 	 * @return mixed        string on success, FALSE on fail
442 442
 	 */
443
-	public function start_time( $tm_format = '' ) {
444
-		return $this->_show_datetime( 'T', 'start', NULL, $tm_format );
443
+	public function start_time($tm_format = '') {
444
+		return $this->_show_datetime('T', 'start', NULL, $tm_format);
445 445
 	}
446 446
 
447 447
 
@@ -449,8 +449,8 @@  discard block
 block discarded – undo
449 449
 	/**
450 450
 	 * @param string $tm_format
451 451
 	 */
452
-	public function e_start_time( $tm_format = '' ) {
453
-		$this->_show_datetime( 'T', 'start', NULL, $tm_format, TRUE );
452
+	public function e_start_time($tm_format = '') {
453
+		$this->_show_datetime('T', 'start', NULL, $tm_format, TRUE);
454 454
 	}
455 455
 
456 456
 
@@ -461,8 +461,8 @@  discard block
 block discarded – undo
461 461
 	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
462 462
 	 * @return mixed        string on success, FALSE on fail
463 463
 	 */
464
-	public function end_time( $tm_format = '' ) {
465
-		return $this->_show_datetime( 'T', 'end', NULL, $tm_format );
464
+	public function end_time($tm_format = '') {
465
+		return $this->_show_datetime('T', 'end', NULL, $tm_format);
466 466
 	}
467 467
 
468 468
 
@@ -470,8 +470,8 @@  discard block
 block discarded – undo
470 470
 	/**
471 471
 	 * @param string $tm_format
472 472
 	 */
473
-	public function e_end_time( $tm_format = '' ) {
474
-		$this->_show_datetime( 'T', 'end', NULL, $tm_format, TRUE );
473
+	public function e_end_time($tm_format = '') {
474
+		$this->_show_datetime('T', 'end', NULL, $tm_format, TRUE);
475 475
 	}
476 476
 
477 477
 
@@ -486,11 +486,11 @@  discard block
 block discarded – undo
486 486
 	 * @return mixed              string on success, FALSE on fail
487 487
 	 * @throws \EE_Error
488 488
 	 */
489
-	public function time_range( $tm_format = '', $conjunction = ' - ' ) {
490
-		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
491
-		$start = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_start', $tm_format ) );
492
-		$end = str_replace( ' ', '&nbsp;', $this->get_i18n_datetime( 'DTT_EVT_end',  $tm_format ) );
493
-		return $start !== $end ? $start . $conjunction . $end : $start;
489
+	public function time_range($tm_format = '', $conjunction = ' - ') {
490
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
491
+		$start = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_start', $tm_format));
492
+		$end = str_replace(' ', '&nbsp;', $this->get_i18n_datetime('DTT_EVT_end', $tm_format));
493
+		return $start !== $end ? $start.$conjunction.$end : $start;
494 494
 	}
495 495
 
496 496
 
@@ -500,8 +500,8 @@  discard block
 block discarded – undo
500 500
 	 * @param string $conjunction
501 501
 	 * @throws \EE_Error
502 502
 	 */
503
-	public function e_time_range( $tm_format = '', $conjunction = ' - ' ) {
504
-		echo $this->time_range( $tm_format, $conjunction );
503
+	public function e_time_range($tm_format = '', $conjunction = ' - ') {
504
+		echo $this->time_range($tm_format, $conjunction);
505 505
 	}
506 506
 
507 507
 
@@ -523,30 +523,30 @@  discard block
 block discarded – undo
523 523
 	public function date_and_time_range(
524 524
 	    $dt_format = '',
525 525
         $tm_format = '',
526
-        $conjunction = ' - ' ,
526
+        $conjunction = ' - ',
527 527
         $separator = ' '
528 528
     ) {
529
-		$dt_format = ! empty( $dt_format ) ? $dt_format : $this->_dt_frmt;
530
-		$tm_format = ! empty( $tm_format ) ? $tm_format : $this->_tm_frmt;
531
-		$full_format = $dt_format . $separator . $tm_format;
529
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
530
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
531
+		$full_format = $dt_format.$separator.$tm_format;
532 532
 
533 533
 		//the range output depends on various conditions
534
-		switch ( true ) {
534
+		switch (true) {
535 535
 			//start date timestamp and end date timestamp are the same.
536
-			case ( $this->get_raw( 'DTT_EVT_start' ) === $this->get_raw( 'DTT_EVT_end' ) ) :
537
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format );
536
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')) :
537
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
538 538
 				break;
539 539
 			//start and end date are the same but times are different
540
-			case ( $this->start_date() === $this->end_date() ) :
541
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
540
+			case ($this->start_date() === $this->end_date()) :
541
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
542 542
 				          . $conjunction
543
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $tm_format );
543
+				          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
544 544
 				break;
545 545
 			//all other conditions
546 546
 			default :
547
-				$output = $this->get_i18n_datetime( 'DTT_EVT_start', $full_format )
547
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
548 548
 				          . $conjunction
549
-				          . $this->get_i18n_datetime( 'DTT_EVT_end', $full_format );
549
+				          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
550 550
 				break;
551 551
 		}
552 552
 		return $output;
@@ -564,8 +564,8 @@  discard block
 block discarded – undo
564 564
 	 * @return void
565 565
 	 * @throws \EE_Error
566 566
 	 */
567
-	public function e_date_and_time_range( $dt_format = '', $tm_format = '', $conjunction = ' - ' ) {
568
-		echo $this->date_and_time_range( $dt_format, $tm_format, $conjunction );
567
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ') {
568
+		echo $this->date_and_time_range($dt_format, $tm_format, $conjunction);
569 569
 	}
570 570
 
571 571
 
@@ -577,8 +577,8 @@  discard block
 block discarded – undo
577 577
 	 * @param 	string 	$tm_format - string representation of time format defaults to 'g:i a'
578 578
 	 * @return 	mixed 	string on success, FALSE on fail
579 579
 	 */
580
-	public function start_date_and_time( $dt_format = '', $tm_format = '' ) {
581
-		return $this->_show_datetime( '', 'start', $dt_format, $tm_format );
580
+	public function start_date_and_time($dt_format = '', $tm_format = '') {
581
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
582 582
 	}
583 583
 
584 584
 
@@ -587,8 +587,8 @@  discard block
 block discarded – undo
587 587
 	 * @param string $dt_frmt
588 588
 	 * @param string $tm_format
589 589
 	 */
590
-	public function e_start_date_and_time( $dt_frmt = '', $tm_format = '' ) {
591
-		$this->_show_datetime( '', 'start', $dt_frmt, $tm_format, TRUE );
590
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '') {
591
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, TRUE);
592 592
 	}
593 593
 
594 594
 
@@ -602,11 +602,11 @@  discard block
 block discarded – undo
602 602
 	 * @param bool   $round_up
603 603
 	 * @return float|int|mixed
604 604
 	 */
605
-	public function length( $units = 'seconds', $round_up = FALSE ) {
606
-		$start = $this->get_raw( 'DTT_EVT_start' );
607
-		$end = $this->get_raw( 'DTT_EVT_end' );
605
+	public function length($units = 'seconds', $round_up = FALSE) {
606
+		$start = $this->get_raw('DTT_EVT_start');
607
+		$end = $this->get_raw('DTT_EVT_end');
608 608
 		$length_in_units = $end - $start;
609
-		switch ( $units ) {
609
+		switch ($units) {
610 610
 			//NOTE: We purposefully don't use "break;" in order to chain the divisions
611 611
 			/** @noinspection PhpMissingBreakStatementInspection */
612 612
 			case 'days':
@@ -619,10 +619,10 @@  discard block
 block discarded – undo
619 619
 				$length_in_units /= 60;
620 620
 			case 'seconds':
621 621
 			default:
622
-				$length_in_units = ceil( $length_in_units );
622
+				$length_in_units = ceil($length_in_units);
623 623
 		}
624
-		if ( $round_up ) {
625
-			$length_in_units = max( $length_in_units, 1 );
624
+		if ($round_up) {
625
+			$length_in_units = max($length_in_units, 1);
626 626
 		}
627 627
 		return $length_in_units;
628 628
 	}
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
      * @return    mixed                string on success, FALSE on fail
638 638
      */
639 639
     public function end_date_and_time($dt_frmt = '', $tm_format = '') {
640
-		return $this->_show_datetime( '', 'end', $dt_frmt, $tm_format );
640
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
641 641
 	}
642 642
 
643 643
 
@@ -646,8 +646,8 @@  discard block
 block discarded – undo
646 646
 	 * @param string $dt_frmt
647 647
 	 * @param string $tm_format
648 648
 	 */
649
-	public function e_end_date_and_time( $dt_frmt = '', $tm_format = '' ) {
650
-		$this->_show_datetime( '', 'end', $dt_frmt, $tm_format, TRUE );
649
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '') {
650
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, TRUE);
651 651
 	}
652 652
 
653 653
 
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
 	 * @return        int
659 659
 	 */
660 660
 	public function start() {
661
-		return $this->get_raw( 'DTT_EVT_start' );
661
+		return $this->get_raw('DTT_EVT_start');
662 662
 	}
663 663
 
664 664
 
@@ -669,7 +669,7 @@  discard block
 block discarded – undo
669 669
 	 * @return        int
670 670
 	 */
671 671
 	public function end() {
672
-		return $this->get_raw( 'DTT_EVT_end' );
672
+		return $this->get_raw('DTT_EVT_end');
673 673
 	}
674 674
 
675 675
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
 	 * @return        mixed        int on success, FALSE on fail
681 681
 	 */
682 682
 	public function reg_limit() {
683
-		return $this->get_raw( 'DTT_reg_limit' );
683
+		return $this->get_raw('DTT_reg_limit');
684 684
 	}
685 685
 
686 686
 
@@ -708,15 +708,15 @@  discard block
 block discarded – undo
708 708
 	 * 																	the spaces remaining for this particular datetime, hence the flag.
709 709
 	 * @return 	int
710 710
 	 */
711
-	public function spaces_remaining( $consider_tickets = FALSE ) {
711
+	public function spaces_remaining($consider_tickets = FALSE) {
712 712
 		// tickets remaining available for purchase
713 713
 		//no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
714 714
 		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
715
-		if ( ! $consider_tickets ) {
715
+		if ( ! $consider_tickets) {
716 716
 			return $dtt_remaining;
717 717
 		}
718 718
 		$tickets_remaining = $this->tickets_remaining();
719
-		return min( $dtt_remaining, $tickets_remaining );
719
+		return min($dtt_remaining, $tickets_remaining);
720 720
 	}
721 721
 
722 722
 
@@ -727,19 +727,19 @@  discard block
 block discarded – undo
727 727
 	 * @param array $query_params like EEM_Base::get_all's
728 728
 	 * @return int
729 729
 	 */
730
-	public function tickets_remaining( $query_params = array() ) {
730
+	public function tickets_remaining($query_params = array()) {
731 731
 		$sum = 0;
732
-		$tickets = $this->tickets( $query_params );
733
-		if ( ! empty( $tickets ) ) {
734
-			foreach ( $tickets as $ticket ) {
735
-				if ( $ticket instanceof EE_Ticket ) {
732
+		$tickets = $this->tickets($query_params);
733
+		if ( ! empty($tickets)) {
734
+			foreach ($tickets as $ticket) {
735
+				if ($ticket instanceof EE_Ticket) {
736 736
 					// get the actual amount of tickets that can be sold
737
-					$qty = $ticket->qty( 'saleable' );
738
-					if ( $qty === EE_INF ) {
737
+					$qty = $ticket->qty('saleable');
738
+					if ($qty === EE_INF) {
739 739
 						return EE_INF;
740 740
 					}
741 741
 					// no negative ticket quantities plz
742
-					if ( $qty > 0 ) {
742
+					if ($qty > 0) {
743 743
 						$sum += $qty;
744 744
 					}
745 745
 				}
@@ -756,8 +756,8 @@  discard block
 block discarded – undo
756 756
 	 * @param array $query_params like EEM_Base::get_all's
757 757
 	 * @return int
758 758
 	 */
759
-	public function sum_tickets_initially_available( $query_params = array() ) {
760
-		return $this->sum_related( 'Ticket', $query_params, 'TKT_qty' );
759
+	public function sum_tickets_initially_available($query_params = array()) {
760
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
761 761
 	}
762 762
 
763 763
 
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
 	 * @return int
770 770
 	 */
771 771
 	public function total_tickets_available_at_this_datetime() {
772
-		return $this->spaces_remaining( true );
772
+		return $this->spaces_remaining(true);
773 773
 	}
774 774
 
775 775
 
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
 	 * @return boolean
781 781
 	 */
782 782
 	public function is_upcoming() {
783
-		return ( $this->get_raw( 'DTT_EVT_start' ) > time() );
783
+		return ($this->get_raw('DTT_EVT_start') > time());
784 784
 	}
785 785
 
786 786
 
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
 	 * @return boolean
791 791
 	 */
792 792
 	public function is_active() {
793
-		return ( $this->get_raw( 'DTT_EVT_start' ) < time() && $this->get_raw( 'DTT_EVT_end' ) > time() );
793
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
794 794
 	}
795 795
 
796 796
 
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
 	 * @return boolean
801 801
 	 */
802 802
 	public function is_expired() {
803
-		return ( $this->get_raw( 'DTT_EVT_end' ) < time() );
803
+		return ($this->get_raw('DTT_EVT_end') < time());
804 804
 	}
805 805
 
806 806
 
@@ -811,16 +811,16 @@  discard block
 block discarded – undo
811 811
 	 */
812 812
 	public function get_active_status() {
813 813
 		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
814
-		if ( $total_tickets_for_this_dtt !== FALSE && $total_tickets_for_this_dtt < 1 ) {
814
+		if ($total_tickets_for_this_dtt !== FALSE && $total_tickets_for_this_dtt < 1) {
815 815
 			return EE_Datetime::sold_out;
816 816
 		}
817
-		if ( $this->is_expired() ) {
817
+		if ($this->is_expired()) {
818 818
 			return EE_Datetime::expired;
819 819
 		}
820
-		if ( $this->is_upcoming() ) {
820
+		if ($this->is_upcoming()) {
821 821
 			return EE_Datetime::upcoming;
822 822
 		}
823
-		if ( $this->is_active() ) {
823
+		if ($this->is_active()) {
824 824
 			return EE_Datetime::active;
825 825
 		}
826 826
 		return NULL;
@@ -834,24 +834,24 @@  discard block
 block discarded – undo
834 834
 	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
835 835
 	 * @return string
836 836
 	 */
837
-	public function get_dtt_display_name( $use_dtt_name = FALSE ) {
838
-		if ( $use_dtt_name ) {
837
+	public function get_dtt_display_name($use_dtt_name = FALSE) {
838
+		if ($use_dtt_name) {
839 839
 			$dtt_name = $this->name();
840
-			if ( !empty( $dtt_name ) ) {
840
+			if ( ! empty($dtt_name)) {
841 841
 				return $dtt_name;
842 842
 			}
843 843
 		}
844 844
 		//first condition is to see if the months are different
845
-		if ( date( 'm', $this->get_raw( 'DTT_EVT_start' ) ) != date( 'm', $this->get_raw( 'DTT_EVT_end' ) ) ) {
846
-			$display_date = $this->start_date( 'M j\, Y g:i a' ) . ' - ' . $this->end_date( 'M j\, Y g:i a' );
845
+		if (date('m', $this->get_raw('DTT_EVT_start')) != date('m', $this->get_raw('DTT_EVT_end'))) {
846
+			$display_date = $this->start_date('M j\, Y g:i a').' - '.$this->end_date('M j\, Y g:i a');
847 847
 			//next condition is if its the same month but different day
848 848
 		}
849 849
 		else {
850
-			if ( date( 'm', $this->get_raw( 'DTT_EVT_start' ) ) == date( 'm', $this->get_raw( 'DTT_EVT_end' ) ) && date( 'd', $this->get_raw( 'DTT_EVT_start' ) ) != date( 'd', $this->get_raw( 'DTT_EVT_end' ) ) ) {
851
-				$display_date = $this->start_date( 'M j\, g:i a' ) . ' - ' . $this->end_date( 'M j\, g:i a Y' );
850
+			if (date('m', $this->get_raw('DTT_EVT_start')) == date('m', $this->get_raw('DTT_EVT_end')) && date('d', $this->get_raw('DTT_EVT_start')) != date('d', $this->get_raw('DTT_EVT_end'))) {
851
+				$display_date = $this->start_date('M j\, g:i a').' - '.$this->end_date('M j\, g:i a Y');
852 852
 			}
853 853
 			else {
854
-				$display_date = $this->start_date( 'F j\, Y' ) . ' @ ' . $this->start_date( 'g:i a' ) . ' - ' . $this->end_date( 'g:i a' );
854
+				$display_date = $this->start_date('F j\, Y').' @ '.$this->start_date('g:i a').' - '.$this->end_date('g:i a');
855 855
 			}
856 856
 		}
857 857
 		return $display_date;
@@ -865,8 +865,8 @@  discard block
 block discarded – undo
865 865
 *@param array $query_params see EEM_Base::get_all()
866 866
 	 * @return EE_Ticket[]
867 867
 	 */
868
-	public function tickets( $query_params = array() ) {
869
-		return $this->get_many_related( 'Ticket', $query_params );
868
+	public function tickets($query_params = array()) {
869
+		return $this->get_many_related('Ticket', $query_params);
870 870
 	}
871 871
 
872 872
 
@@ -876,21 +876,21 @@  discard block
 block discarded – undo
876 876
 	 * @param array $query_params like EEM_Base::get_all's
877 877
 	 * @return EE_Ticket[]
878 878
 	 */
879
-	public function ticket_types_available_for_purchase( $query_params = array() ) {
879
+	public function ticket_types_available_for_purchase($query_params = array()) {
880 880
 		// first check if datetime is valid
881
-		if ( ! ( $this->is_upcoming() || $this->is_active() ) || $this->sold_out() ) {
881
+		if ( ! ($this->is_upcoming() || $this->is_active()) || $this->sold_out()) {
882 882
 			return array();
883 883
 		}
884
-		if ( empty( $query_params ) ) {
884
+		if (empty($query_params)) {
885 885
 			$query_params = array(
886 886
 				array(
887
-					'TKT_start_date' => array( '<=', EEM_Ticket::instance()->current_time_for_query( 'TKT_start_date' ) ),
888
-					'TKT_end_date'   => array( '>=', EEM_Ticket::instance()->current_time_for_query( 'TKT_end_date' ) ),
887
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
888
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
889 889
 					'TKT_deleted'    => false
890 890
 				)
891 891
 			);
892 892
 		}
893
-		return $this->tickets( $query_params );
893
+		return $this->tickets($query_params);
894 894
 	}
895 895
 
896 896
 
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
 	 * @return EE_Event
901 901
 	 */
902 902
 	public function event() {
903
-		return $this->get_first_related( 'Event' );
903
+		return $this->get_first_related('Event');
904 904
 	}
905 905
 
906 906
 
@@ -912,13 +912,13 @@  discard block
 block discarded – undo
912 912
 	 */
913 913
 	public function update_sold() {
914 914
 		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
915
-			array( array(
915
+			array(array(
916 916
 				'STS_ID' 					=> EEM_Registration::status_id_approved,
917 917
 				'REG_deleted' 				=> 0,
918 918
 				'Ticket.Datetime.DTT_ID' 	=> $this->ID(),
919
-			) )
919
+			))
920 920
 		);
921
-		$this->set( 'DTT_sold', $count_regs_for_this_datetime );
921
+		$this->set('DTT_sold', $count_regs_for_this_datetime);
922 922
 		$this->save();
923 923
 		return $count_regs_for_this_datetime;
924 924
 	}
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +2647 added lines, -2647 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2652 +25,2652 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
-     * access to it.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_timezone;
48
-
49
-
50
-
51
-    /**
52
-     * date format
53
-     * pattern or format for displaying dates
54
-     *
55
-     * @var string $_dt_frmt
56
-     */
57
-    protected $_dt_frmt;
58
-
59
-
60
-
61
-    /**
62
-     * time format
63
-     * pattern or format for displaying time
64
-     *
65
-     * @var string $_tm_frmt
66
-     */
67
-    protected $_tm_frmt;
68
-
69
-
70
-
71
-    /**
72
-     * This property is for holding a cached array of object properties indexed by property name as the key.
73
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
74
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
-     *
77
-     * @var array
78
-     */
79
-    protected $_cached_properties = array();
80
-
81
-    /**
82
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
83
-     * single
84
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
-     * all others have an array)
87
-     *
88
-     * @var array
89
-     */
90
-    protected $_model_relations = array();
91
-
92
-    /**
93
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_fields = array();
99
-
100
-    /**
101
-     * @var boolean indicating whether or not this model object is intended to ever be saved
102
-     * For example, we might create model objects intended to only be used for the duration
103
-     * of this request and to be thrown away, and if they were accidentally saved
104
-     * it would be a bug.
105
-     */
106
-    protected $_allow_persist = true;
107
-
108
-
109
-
110
-    /**
111
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
112
-     * play nice
113
-     *
114
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
115
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
116
-     *                                                         TXN_amount, QST_name, etc) and values are their values
117
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
118
-     *                                                         corresponding db model or not.
119
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
120
-     *                                                         be in when instantiating a EE_Base_Class object.
121
-     * @param array   $date_formats                            An array of date formats to set on construct where first
122
-     *                                                         value is the date_format and second value is the time
123
-     *                                                         format.
124
-     * @throws EE_Error
125
-     */
126
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
127
-    {
128
-        $className = get_class($this);
129
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
-        $model = $this->get_model();
131
-        $model_fields = $model->field_settings(false);
132
-        // ensure $fieldValues is an array
133
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
134
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
135
-        // verify client code has not passed any invalid field names
136
-        foreach ($fieldValues as $field_name => $field_value) {
137
-            if ( ! isset($model_fields[$field_name])) {
138
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
139
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
140
-            }
141
-        }
142
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
143
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
144
-        if ( ! empty($date_formats) && is_array($date_formats)) {
145
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
146
-        } else {
147
-            //set default formats for date and time
148
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
149
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
150
-        }
151
-        //if db model is instantiating
152
-        if ($bydb) {
153
-            //client code has indicated these field values are from the database
154
-            foreach ($model_fields as $fieldName => $field) {
155
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
156
-            }
157
-        } else {
158
-            //we're constructing a brand
159
-            //new instance of the model object. Generally, this means we'll need to do more field validation
160
-            foreach ($model_fields as $fieldName => $field) {
161
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
162
-            }
163
-        }
164
-        //remember what values were passed to this constructor
165
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
166
-        //remember in entity mapper
167
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
168
-            $model->add_to_entity_map($this);
169
-        }
170
-        //setup all the relations
171
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
172
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
173
-                $this->_model_relations[$relation_name] = null;
174
-            } else {
175
-                $this->_model_relations[$relation_name] = array();
176
-            }
177
-        }
178
-        /**
179
-         * Action done at the end of each model object construction
180
-         *
181
-         * @param EE_Base_Class $this the model object just created
182
-         */
183
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
190
-     *
191
-     * @return boolean
192
-     */
193
-    public function allow_persist()
194
-    {
195
-        return $this->_allow_persist;
196
-    }
197
-
198
-
199
-
200
-    /**
201
-     * Sets whether or not this model object should be allowed to be saved to the DB.
202
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
203
-     * you got new information that somehow made you change your mind.
204
-     *
205
-     * @param boolean $allow_persist
206
-     * @return boolean
207
-     */
208
-    public function set_allow_persist($allow_persist)
209
-    {
210
-        return $this->_allow_persist = $allow_persist;
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * Gets the field's original value when this object was constructed during this request.
217
-     * This can be helpful when determining if a model object has changed or not
218
-     *
219
-     * @param string $field_name
220
-     * @return mixed|null
221
-     * @throws \EE_Error
222
-     */
223
-    public function get_original($field_name)
224
-    {
225
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
226
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
227
-        ) {
228
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
229
-        } else {
230
-            return null;
231
-        }
232
-    }
233
-
234
-
235
-
236
-    /**
237
-     * @param EE_Base_Class $obj
238
-     * @return string
239
-     */
240
-    public function get_class($obj)
241
-    {
242
-        return get_class($obj);
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * Overrides parent because parent expects old models.
249
-     * This also doesn't do any validation, and won't work for serialized arrays
250
-     *
251
-     * @param    string $field_name
252
-     * @param    mixed  $field_value
253
-     * @param bool      $use_default
254
-     * @throws \EE_Error
255
-     */
256
-    public function set($field_name, $field_value, $use_default = false)
257
-    {
258
-        $field_obj = $this->get_model()->field_settings_for($field_name);
259
-        if ($field_obj instanceof EE_Model_Field_Base) {
260
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
261
-            if ($field_obj instanceof EE_Datetime_Field) {
262
-                $field_obj->set_timezone($this->_timezone);
263
-                $field_obj->set_date_format($this->_dt_frmt);
264
-                $field_obj->set_time_format($this->_tm_frmt);
265
-            }
266
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
267
-            //should the value be null?
268
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
269
-                $this->_fields[$field_name] = $field_obj->get_default_value();
270
-                /**
271
-                 * To save having to refactor all the models, if a default value is used for a
272
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
273
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
274
-                 * object.
275
-                 *
276
-                 * @since 4.6.10+
277
-                 */
278
-                if (
279
-                    $field_obj instanceof EE_Datetime_Field
280
-                    && $this->_fields[$field_name] !== null
281
-                    && ! $this->_fields[$field_name] instanceof DateTime
282
-                ) {
283
-                    empty($this->_fields[$field_name])
284
-                        ? $this->set($field_name, time())
285
-                        : $this->set($field_name, $this->_fields[$field_name]);
286
-                }
287
-            } else {
288
-                $this->_fields[$field_name] = $holder_of_value;
289
-            }
290
-            //if we're not in the constructor...
291
-            //now check if what we set was a primary key
292
-            if (
293
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
294
-                $this->_props_n_values_provided_in_constructor
295
-                && $field_value
296
-                && $field_name === self::_get_primary_key_name(get_class($this))
297
-            ) {
298
-                //if so, we want all this object's fields to be filled either with
299
-                //what we've explicitly set on this model
300
-                //or what we have in the db
301
-                // echo "setting primary key!";
302
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
303
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
304
-                foreach ($fields_on_model as $field_obj) {
305
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
306
-                         && $field_obj->get_name() !== $field_name
307
-                    ) {
308
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
309
-                    }
310
-                }
311
-                //oh this model object has an ID? well make sure its in the entity mapper
312
-                $this->get_model()->add_to_entity_map($this);
313
-            }
314
-            //let's unset any cache for this field_name from the $_cached_properties property.
315
-            $this->_clear_cached_property($field_name);
316
-        } else {
317
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
318
-                "event_espresso"), $field_name));
319
-        }
320
-    }
321
-
322
-
323
-
324
-    /**
325
-     * This sets the field value on the db column if it exists for the given $column_name or
326
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
327
-     *
328
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
329
-     * @param string $field_name  Must be the exact column name.
330
-     * @param mixed  $field_value The value to set.
331
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
332
-     * @throws \EE_Error
333
-     */
334
-    public function set_field_or_extra_meta($field_name, $field_value)
335
-    {
336
-        if ($this->get_model()->has_field($field_name)) {
337
-            $this->set($field_name, $field_value);
338
-            return true;
339
-        } else {
340
-            //ensure this object is saved first so that extra meta can be properly related.
341
-            $this->save();
342
-            return $this->update_extra_meta($field_name, $field_value);
343
-        }
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * This retrieves the value of the db column set on this class or if that's not present
350
-     * it will attempt to retrieve from extra_meta if found.
351
-     * Example Usage:
352
-     * Via EE_Message child class:
353
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
354
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
355
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
356
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
357
-     * value for those extra fields dynamically via the EE_message object.
358
-     *
359
-     * @param  string $field_name expecting the fully qualified field name.
360
-     * @return mixed|null  value for the field if found.  null if not found.
361
-     * @throws \EE_Error
362
-     */
363
-    public function get_field_or_extra_meta($field_name)
364
-    {
365
-        if ($this->get_model()->has_field($field_name)) {
366
-            $column_value = $this->get($field_name);
367
-        } else {
368
-            //This isn't a column in the main table, let's see if it is in the extra meta.
369
-            $column_value = $this->get_extra_meta($field_name, true, null);
370
-        }
371
-        return $column_value;
372
-    }
373
-
374
-
375
-
376
-    /**
377
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
378
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
379
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
380
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
381
-     *
382
-     * @access public
383
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
384
-     * @return void
385
-     * @throws \EE_Error
386
-     */
387
-    public function set_timezone($timezone = '')
388
-    {
389
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
390
-        //make sure we clear all cached properties because they won't be relevant now
391
-        $this->_clear_cached_properties();
392
-        //make sure we update field settings and the date for all EE_Datetime_Fields
393
-        $model_fields = $this->get_model()->field_settings(false);
394
-        foreach ($model_fields as $field_name => $field_obj) {
395
-            if ($field_obj instanceof EE_Datetime_Field) {
396
-                $field_obj->set_timezone($this->_timezone);
397
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
398
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
399
-                }
400
-            }
401
-        }
402
-    }
403
-
404
-
405
-
406
-    /**
407
-     * This just returns whatever is set for the current timezone.
408
-     *
409
-     * @access public
410
-     * @return string timezone string
411
-     */
412
-    public function get_timezone()
413
-    {
414
-        return $this->_timezone;
415
-    }
416
-
417
-
418
-
419
-    /**
420
-     * This sets the internal date format to what is sent in to be used as the new default for the class
421
-     * internally instead of wp set date format options
422
-     *
423
-     * @since 4.6
424
-     * @param string $format should be a format recognizable by PHP date() functions.
425
-     */
426
-    public function set_date_format($format)
427
-    {
428
-        $this->_dt_frmt = $format;
429
-        //clear cached_properties because they won't be relevant now.
430
-        $this->_clear_cached_properties();
431
-    }
432
-
433
-
434
-
435
-    /**
436
-     * This sets the internal time format string to what is sent in to be used as the new default for the
437
-     * class internally instead of wp set time format options.
438
-     *
439
-     * @since 4.6
440
-     * @param string $format should be a format recognizable by PHP date() functions.
441
-     */
442
-    public function set_time_format($format)
443
-    {
444
-        $this->_tm_frmt = $format;
445
-        //clear cached_properties because they won't be relevant now.
446
-        $this->_clear_cached_properties();
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * This returns the current internal set format for the date and time formats.
453
-     *
454
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
455
-     *                             where the first value is the date format and the second value is the time format.
456
-     * @return mixed string|array
457
-     */
458
-    public function get_format($full = true)
459
-    {
460
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
461
-    }
462
-
463
-
464
-
465
-    /**
466
-     * cache
467
-     * stores the passed model object on the current model object.
468
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
469
-     *
470
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
471
-     *                                       'Registration' associated with this model object
472
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
473
-     *                                       that could be a payment or a registration)
474
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
475
-     *                                       items which will be stored in an array on this object
476
-     * @throws EE_Error
477
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
478
-     *                  related thing, no array)
479
-     */
480
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
481
-    {
482
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
483
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
484
-            return false;
485
-        }
486
-        // also get "how" the object is related, or throw an error
487
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
488
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
489
-                $relationName, get_class($this)));
490
-        }
491
-        // how many things are related ?
492
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
493
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
494
-            // so for these model objects just set it to be cached
495
-            $this->_model_relations[$relationName] = $object_to_cache;
496
-            $return = true;
497
-        } else {
498
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
499
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
500
-            if ( ! is_array($this->_model_relations[$relationName])) {
501
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
502
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
503
-                    ? array($this->_model_relations[$relationName]) : array();
504
-            }
505
-            // first check for a cache_id which is normally empty
506
-            if ( ! empty($cache_id)) {
507
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
508
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
509
-                $return = $cache_id;
510
-            } elseif ($object_to_cache->ID()) {
511
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
512
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
513
-                $return = $object_to_cache->ID();
514
-            } else {
515
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
516
-                $this->_model_relations[$relationName][] = $object_to_cache;
517
-                // move the internal pointer to the end of the array
518
-                end($this->_model_relations[$relationName]);
519
-                // and grab the key so that we can return it
520
-                $return = key($this->_model_relations[$relationName]);
521
-            }
522
-        }
523
-        return $return;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * For adding an item to the cached_properties property.
530
-     *
531
-     * @access protected
532
-     * @param string      $fieldname the property item the corresponding value is for.
533
-     * @param mixed       $value     The value we are caching.
534
-     * @param string|null $cache_type
535
-     * @return void
536
-     * @throws \EE_Error
537
-     */
538
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
539
-    {
540
-        //first make sure this property exists
541
-        $this->get_model()->field_settings_for($fieldname);
542
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
543
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
544
-    }
545
-
546
-
547
-
548
-    /**
549
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
550
-     * This also SETS the cache if we return the actual property!
551
-     *
552
-     * @param string $fieldname        the name of the property we're trying to retrieve
553
-     * @param bool   $pretty
554
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
555
-     *                                 (in cases where the same property may be used for different outputs
556
-     *                                 - i.e. datetime, money etc.)
557
-     *                                 It can also accept certain pre-defined "schema" strings
558
-     *                                 to define how to output the property.
559
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
560
-     * @return mixed                   whatever the value for the property is we're retrieving
561
-     * @throws \EE_Error
562
-     */
563
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
564
-    {
565
-        //verify the field exists
566
-        $this->get_model()->field_settings_for($fieldname);
567
-        $cache_type = $pretty ? 'pretty' : 'standard';
568
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
569
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
570
-            return $this->_cached_properties[$fieldname][$cache_type];
571
-        }
572
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
573
-        if ($field_obj instanceof EE_Model_Field_Base) {
574
-            // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
575
-            if ($field_obj instanceof EE_Datetime_Field) {
576
-                $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
577
-            }
578
-            if ( ! isset($this->_fields[$fieldname])) {
579
-                $this->_fields[$fieldname] = null;
580
-            }
581
-            $value = $pretty
582
-                ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
583
-                : $field_obj->prepare_for_get($this->_fields[$fieldname]);
584
-            $this->_set_cached_property($fieldname, $value, $cache_type);
585
-            return $value;
586
-        }
587
-        return null;
588
-    }
589
-
590
-
591
-
592
-    /**
593
-     * set timezone, formats, and output for EE_Datetime_Field objects
594
-     *
595
-     * @param \EE_Datetime_Field $datetime_field
596
-     * @param bool               $pretty
597
-     * @param null $date_or_time
598
-     * @return void
599
-     * @throws \EE_Error
600
-     */
601
-    protected function _prepare_datetime_field(
602
-        EE_Datetime_Field $datetime_field,
603
-        $pretty = false,
604
-        $date_or_time = null
605
-    ) {
606
-        $datetime_field->set_timezone($this->_timezone);
607
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
608
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
609
-        //set the output returned
610
-        switch ($date_or_time) {
611
-            case 'D' :
612
-                $datetime_field->set_date_time_output('date');
613
-                break;
614
-            case 'T' :
615
-                $datetime_field->set_date_time_output('time');
616
-                break;
617
-            default :
618
-                $datetime_field->set_date_time_output();
619
-        }
620
-    }
621
-
622
-
623
-
624
-    /**
625
-     * This just takes care of clearing out the cached_properties
626
-     *
627
-     * @return void
628
-     */
629
-    protected function _clear_cached_properties()
630
-    {
631
-        $this->_cached_properties = array();
632
-    }
633
-
634
-
635
-
636
-    /**
637
-     * This just clears out ONE property if it exists in the cache
638
-     *
639
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
640
-     * @return void
641
-     */
642
-    protected function _clear_cached_property($property_name)
643
-    {
644
-        if (isset($this->_cached_properties[$property_name])) {
645
-            unset($this->_cached_properties[$property_name]);
646
-        }
647
-    }
648
-
649
-
650
-
651
-    /**
652
-     * Ensures that this related thing is a model object.
653
-     *
654
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
655
-     * @param string $model_name   name of the related thing, eg 'Attendee',
656
-     * @return EE_Base_Class
657
-     * @throws \EE_Error
658
-     */
659
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
660
-    {
661
-        $other_model_instance = self::_get_model_instance_with_name(
662
-            self::_get_model_classname($model_name),
663
-            $this->_timezone
664
-        );
665
-        return $other_model_instance->ensure_is_obj($object_or_id);
666
-    }
667
-
668
-
669
-
670
-    /**
671
-     * Forgets the cached model of the given relation Name. So the next time we request it,
672
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
673
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
674
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
675
-     *
676
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
677
-     *                                                     Eg 'Registration'
678
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
679
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
680
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
681
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
682
-     *                                                     this is HasMany or HABTM.
683
-     * @throws EE_Error
684
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
685
-     *                       relation from all
686
-     */
687
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
688
-    {
689
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
690
-        $index_in_cache = '';
691
-        if ( ! $relationship_to_model) {
692
-            throw new EE_Error(
693
-                sprintf(
694
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
695
-                    $relationName,
696
-                    get_class($this)
697
-                )
698
-            );
699
-        }
700
-        if ($clear_all) {
701
-            $obj_removed = true;
702
-            $this->_model_relations[$relationName] = null;
703
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
704
-            $obj_removed = $this->_model_relations[$relationName];
705
-            $this->_model_relations[$relationName] = null;
706
-        } else {
707
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
708
-                && $object_to_remove_or_index_into_array->ID()
709
-            ) {
710
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
711
-                if (is_array($this->_model_relations[$relationName])
712
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
713
-                ) {
714
-                    $index_found_at = null;
715
-                    //find this object in the array even though it has a different key
716
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
717
-                        if (
718
-                            $obj instanceof EE_Base_Class
719
-                            && (
720
-                                $obj == $object_to_remove_or_index_into_array
721
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
722
-                            )
723
-                        ) {
724
-                            $index_found_at = $index;
725
-                            break;
726
-                        }
727
-                    }
728
-                    if ($index_found_at) {
729
-                        $index_in_cache = $index_found_at;
730
-                    } else {
731
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
732
-                        //if it wasn't in it to begin with. So we're done
733
-                        return $object_to_remove_or_index_into_array;
734
-                    }
735
-                }
736
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
737
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
738
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
739
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
740
-                        $index_in_cache = $index;
741
-                    }
742
-                }
743
-            } else {
744
-                $index_in_cache = $object_to_remove_or_index_into_array;
745
-            }
746
-            //supposedly we've found it. But it could just be that the client code
747
-            //provided a bad index/object
748
-            if (
749
-            isset(
750
-                $this->_model_relations[$relationName],
751
-                $this->_model_relations[$relationName][$index_in_cache]
752
-            )
753
-            ) {
754
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
755
-                unset($this->_model_relations[$relationName][$index_in_cache]);
756
-            } else {
757
-                //that thing was never cached anyways.
758
-                $obj_removed = null;
759
-            }
760
-        }
761
-        return $obj_removed;
762
-    }
763
-
764
-
765
-
766
-    /**
767
-     * update_cache_after_object_save
768
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
769
-     * obtained after being saved to the db
770
-     *
771
-     * @param string         $relationName       - the type of object that is cached
772
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
773
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
774
-     * @return boolean TRUE on success, FALSE on fail
775
-     * @throws \EE_Error
776
-     */
777
-    public function update_cache_after_object_save(
778
-        $relationName,
779
-        EE_Base_Class $newly_saved_object,
780
-        $current_cache_id = ''
781
-    ) {
782
-        // verify that incoming object is of the correct type
783
-        $obj_class = 'EE_' . $relationName;
784
-        if ($newly_saved_object instanceof $obj_class) {
785
-            /* @type EE_Base_Class $newly_saved_object */
786
-            // now get the type of relation
787
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
788
-            // if this is a 1:1 relationship
789
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
790
-                // then just replace the cached object with the newly saved object
791
-                $this->_model_relations[$relationName] = $newly_saved_object;
792
-                return true;
793
-                // or if it's some kind of sordid feral polyamorous relationship...
794
-            } elseif (is_array($this->_model_relations[$relationName])
795
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
796
-            ) {
797
-                // then remove the current cached item
798
-                unset($this->_model_relations[$relationName][$current_cache_id]);
799
-                // and cache the newly saved object using it's new ID
800
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
801
-                return true;
802
-            }
803
-        }
804
-        return false;
805
-    }
806
-
807
-
808
-
809
-    /**
810
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
811
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
812
-     *
813
-     * @param string $relationName
814
-     * @return EE_Base_Class
815
-     */
816
-    public function get_one_from_cache($relationName)
817
-    {
818
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
819
-            : null;
820
-        if (is_array($cached_array_or_object)) {
821
-            return array_shift($cached_array_or_object);
822
-        } else {
823
-            return $cached_array_or_object;
824
-        }
825
-    }
826
-
827
-
828
-
829
-    /**
830
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
831
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
832
-     *
833
-     * @param string $relationName
834
-     * @throws \EE_Error
835
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
836
-     */
837
-    public function get_all_from_cache($relationName)
838
-    {
839
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
840
-        // if the result is not an array, but exists, make it an array
841
-        $objects = is_array($objects) ? $objects : array($objects);
842
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
843
-        //basically, if this model object was stored in the session, and these cached model objects
844
-        //already have IDs, let's make sure they're in their model's entity mapper
845
-        //otherwise we will have duplicates next time we call
846
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
847
-        $model = EE_Registry::instance()->load_model($relationName);
848
-        foreach ($objects as $model_object) {
849
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
850
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
851
-                if ($model_object->ID()) {
852
-                    $model->add_to_entity_map($model_object);
853
-                }
854
-            } else {
855
-                throw new EE_Error(
856
-                    sprintf(
857
-                        __(
858
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
859
-                            'event_espresso'
860
-                        ),
861
-                        $relationName,
862
-                        gettype($model_object)
863
-                    )
864
-                );
865
-            }
866
-        }
867
-        return $objects;
868
-    }
869
-
870
-
871
-
872
-    /**
873
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
874
-     * matching the given query conditions.
875
-     *
876
-     * @param null  $field_to_order_by  What field is being used as the reference point.
877
-     * @param int   $limit              How many objects to return.
878
-     * @param array $query_params       Any additional conditions on the query.
879
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
880
-     *                                  you can indicate just the columns you want returned
881
-     * @return array|EE_Base_Class[]
882
-     * @throws \EE_Error
883
-     */
884
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
885
-    {
886
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
887
-            ? $this->get_model()->get_primary_key_field()->get_name()
888
-            : $field_to_order_by;
889
-        $current_value = ! empty($field) ? $this->get($field) : null;
890
-        if (empty($field) || empty($current_value)) {
891
-            return array();
892
-        }
893
-        return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
894
-    }
895
-
896
-
897
-
898
-    /**
899
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
900
-     * matching the given query conditions.
901
-     *
902
-     * @param null  $field_to_order_by  What field is being used as the reference point.
903
-     * @param int   $limit              How many objects to return.
904
-     * @param array $query_params       Any additional conditions on the query.
905
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
906
-     *                                  you can indicate just the columns you want returned
907
-     * @return array|EE_Base_Class[]
908
-     * @throws \EE_Error
909
-     */
910
-    public function previous_x(
911
-        $field_to_order_by = null,
912
-        $limit = 1,
913
-        $query_params = array(),
914
-        $columns_to_select = null
915
-    ) {
916
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
917
-            ? $this->get_model()->get_primary_key_field()->get_name()
918
-            : $field_to_order_by;
919
-        $current_value = ! empty($field) ? $this->get($field) : null;
920
-        if (empty($field) || empty($current_value)) {
921
-            return array();
922
-        }
923
-        return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
924
-    }
925
-
926
-
927
-
928
-    /**
929
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
930
-     * matching the given query conditions.
931
-     *
932
-     * @param null  $field_to_order_by  What field is being used as the reference point.
933
-     * @param array $query_params       Any additional conditions on the query.
934
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
935
-     *                                  you can indicate just the columns you want returned
936
-     * @return array|EE_Base_Class
937
-     * @throws \EE_Error
938
-     */
939
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
940
-    {
941
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
942
-            ? $this->get_model()->get_primary_key_field()->get_name()
943
-            : $field_to_order_by;
944
-        $current_value = ! empty($field) ? $this->get($field) : null;
945
-        if (empty($field) || empty($current_value)) {
946
-            return array();
947
-        }
948
-        return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
949
-    }
950
-
951
-
952
-
953
-    /**
954
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
955
-     * matching the given query conditions.
956
-     *
957
-     * @param null  $field_to_order_by  What field is being used as the reference point.
958
-     * @param array $query_params       Any additional conditions on the query.
959
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
960
-     *                                  you can indicate just the column you want returned
961
-     * @return array|EE_Base_Class
962
-     * @throws \EE_Error
963
-     */
964
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
965
-    {
966
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
967
-            ? $this->get_model()->get_primary_key_field()->get_name()
968
-            : $field_to_order_by;
969
-        $current_value = ! empty($field) ? $this->get($field) : null;
970
-        if (empty($field) || empty($current_value)) {
971
-            return array();
972
-        }
973
-        return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
974
-    }
975
-
976
-
977
-
978
-    /**
979
-     * Overrides parent because parent expects old models.
980
-     * This also doesn't do any validation, and won't work for serialized arrays
981
-     *
982
-     * @param string $field_name
983
-     * @param mixed  $field_value_from_db
984
-     * @throws \EE_Error
985
-     */
986
-    public function set_from_db($field_name, $field_value_from_db)
987
-    {
988
-        $field_obj = $this->get_model()->field_settings_for($field_name);
989
-        if ($field_obj instanceof EE_Model_Field_Base) {
990
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
991
-            //eg, a CPT model object could have an entry in the posts table, but no
992
-            //entry in the meta table. Meaning that all its columns in the meta table
993
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
994
-            if ($field_value_from_db === null) {
995
-                if ($field_obj->is_nullable()) {
996
-                    //if the field allows nulls, then let it be null
997
-                    $field_value = null;
998
-                } else {
999
-                    $field_value = $field_obj->get_default_value();
1000
-                }
1001
-            } else {
1002
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1003
-            }
1004
-            $this->_fields[$field_name] = $field_value;
1005
-            $this->_clear_cached_property($field_name);
1006
-        }
1007
-    }
1008
-
1009
-
1010
-
1011
-    /**
1012
-     * verifies that the specified field is of the correct type
1013
-     *
1014
-     * @param string $field_name
1015
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1016
-     *                                (in cases where the same property may be used for different outputs
1017
-     *                                - i.e. datetime, money etc.)
1018
-     * @return mixed
1019
-     * @throws \EE_Error
1020
-     */
1021
-    public function get($field_name, $extra_cache_ref = null)
1022
-    {
1023
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * This method simply returns the RAW unprocessed value for the given property in this class
1030
-     *
1031
-     * @param  string $field_name A valid fieldname
1032
-     * @return mixed              Whatever the raw value stored on the property is.
1033
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1034
-     */
1035
-    public function get_raw($field_name)
1036
-    {
1037
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1038
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1039
-            ? $this->_fields[$field_name]->format('U')
1040
-            : $this->_fields[$field_name];
1041
-    }
1042
-
1043
-
1044
-
1045
-    /**
1046
-     * This is used to return the internal DateTime object used for a field that is a
1047
-     * EE_Datetime_Field.
1048
-     *
1049
-     * @param string $field_name               The field name retrieving the DateTime object.
1050
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1051
-     * @throws \EE_Error
1052
-     *                                         an error is set and false returned.  If the field IS an
1053
-     *                                         EE_Datetime_Field and but the field value is null, then
1054
-     *                                         just null is returned (because that indicates that likely
1055
-     *                                         this field is nullable).
1056
-     */
1057
-    public function get_DateTime_object($field_name)
1058
-    {
1059
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1060
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1061
-            EE_Error::add_error(
1062
-                sprintf(
1063
-                    __(
1064
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1065
-                        'event_espresso'
1066
-                    ),
1067
-                    $field_name
1068
-                ),
1069
-                __FILE__,
1070
-                __FUNCTION__,
1071
-                __LINE__
1072
-            );
1073
-            return false;
1074
-        }
1075
-        return $this->_fields[$field_name];
1076
-    }
1077
-
1078
-
1079
-
1080
-    /**
1081
-     * To be used in template to immediately echo out the value, and format it for output.
1082
-     * Eg, should call stripslashes and whatnot before echoing
1083
-     *
1084
-     * @param string $field_name      the name of the field as it appears in the DB
1085
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1086
-     *                                (in cases where the same property may be used for different outputs
1087
-     *                                - i.e. datetime, money etc.)
1088
-     * @return void
1089
-     * @throws \EE_Error
1090
-     */
1091
-    public function e($field_name, $extra_cache_ref = null)
1092
-    {
1093
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1100
-     * can be easily used as the value of form input.
1101
-     *
1102
-     * @param string $field_name
1103
-     * @return void
1104
-     * @throws \EE_Error
1105
-     */
1106
-    public function f($field_name)
1107
-    {
1108
-        $this->e($field_name, 'form_input');
1109
-    }
1110
-
1111
-
1112
-
1113
-    /**
1114
-     * @param string $field_name
1115
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1116
-     *                                (in cases where the same property may be used for different outputs
1117
-     *                                - i.e. datetime, money etc.)
1118
-     * @return mixed
1119
-     * @throws \EE_Error
1120
-     */
1121
-    public function get_pretty($field_name, $extra_cache_ref = null)
1122
-    {
1123
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1124
-    }
1125
-
1126
-
1127
-
1128
-    /**
1129
-     * This simply returns the datetime for the given field name
1130
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1131
-     * (and the equivalent e_date, e_time, e_datetime).
1132
-     *
1133
-     * @access   protected
1134
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1135
-     * @param string   $dt_frmt      valid datetime format used for date
1136
-     *                               (if '' then we just use the default on the field,
1137
-     *                               if NULL we use the last-used format)
1138
-     * @param string   $tm_frmt      Same as above except this is for time format
1139
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1140
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1141
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1142
-     *                               if field is not a valid dtt field, or void if echoing
1143
-     * @throws \EE_Error
1144
-     */
1145
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1146
-    {
1147
-        // clear cached property
1148
-        $this->_clear_cached_property($field_name);
1149
-        //reset format properties because they are used in get()
1150
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1151
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1152
-        if ($echo) {
1153
-            $this->e($field_name, $date_or_time);
1154
-            return '';
1155
-        }
1156
-        return $this->get($field_name, $date_or_time);
1157
-    }
1158
-
1159
-
1160
-
1161
-    /**
1162
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1163
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1164
-     * other echoes the pretty value for dtt)
1165
-     *
1166
-     * @param  string $field_name name of model object datetime field holding the value
1167
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1168
-     * @return string            datetime value formatted
1169
-     * @throws \EE_Error
1170
-     */
1171
-    public function get_date($field_name, $format = '')
1172
-    {
1173
-        return $this->_get_datetime($field_name, $format, null, 'D');
1174
-    }
1175
-
1176
-
1177
-
1178
-    /**
1179
-     * @param      $field_name
1180
-     * @param string $format
1181
-     * @throws \EE_Error
1182
-     */
1183
-    public function e_date($field_name, $format = '')
1184
-    {
1185
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1186
-    }
1187
-
1188
-
1189
-
1190
-    /**
1191
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1192
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1193
-     * other echoes the pretty value for dtt)
1194
-     *
1195
-     * @param  string $field_name name of model object datetime field holding the value
1196
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1197
-     * @return string             datetime value formatted
1198
-     * @throws \EE_Error
1199
-     */
1200
-    public function get_time($field_name, $format = '')
1201
-    {
1202
-        return $this->_get_datetime($field_name, null, $format, 'T');
1203
-    }
1204
-
1205
-
1206
-
1207
-    /**
1208
-     * @param      $field_name
1209
-     * @param string $format
1210
-     * @throws \EE_Error
1211
-     */
1212
-    public function e_time($field_name, $format = '')
1213
-    {
1214
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1215
-    }
1216
-
1217
-
1218
-
1219
-    /**
1220
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1221
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1222
-     * other echoes the pretty value for dtt)
1223
-     *
1224
-     * @param  string $field_name name of model object datetime field holding the value
1225
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1226
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1227
-     * @return string             datetime value formatted
1228
-     * @throws \EE_Error
1229
-     */
1230
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1231
-    {
1232
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1233
-    }
1234
-
1235
-
1236
-
1237
-    /**
1238
-     * @param string $field_name
1239
-     * @param string $dt_frmt
1240
-     * @param string $tm_frmt
1241
-     * @throws \EE_Error
1242
-     */
1243
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1244
-    {
1245
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1246
-    }
1247
-
1248
-
1249
-
1250
-    /**
1251
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1252
-     *
1253
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1254
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1255
-     *                           on the object will be used.
1256
-     * @return string Date and time string in set locale or false if no field exists for the given
1257
-     * @throws \EE_Error
1258
-     *                           field name.
1259
-     */
1260
-    public function get_i18n_datetime($field_name, $format = '')
1261
-    {
1262
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1263
-        return date_i18n(
1264
-            $format,
1265
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1266
-        );
1267
-    }
1268
-
1269
-
1270
-
1271
-    /**
1272
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1273
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1274
-     * thrown.
1275
-     *
1276
-     * @param  string $field_name The field name being checked
1277
-     * @throws EE_Error
1278
-     * @return EE_Datetime_Field
1279
-     */
1280
-    protected function _get_dtt_field_settings($field_name)
1281
-    {
1282
-        $field = $this->get_model()->field_settings_for($field_name);
1283
-        //check if field is dtt
1284
-        if ($field instanceof EE_Datetime_Field) {
1285
-            return $field;
1286
-        } else {
1287
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1288
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1289
-        }
1290
-    }
1291
-
1292
-
1293
-
1294
-
1295
-    /**
1296
-     * NOTE ABOUT BELOW:
1297
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1298
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1299
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1300
-     * method and make sure you send the entire datetime value for setting.
1301
-     */
1302
-    /**
1303
-     * sets the time on a datetime property
1304
-     *
1305
-     * @access protected
1306
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1307
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1308
-     * @throws \EE_Error
1309
-     */
1310
-    protected function _set_time_for($time, $fieldname)
1311
-    {
1312
-        $this->_set_date_time('T', $time, $fieldname);
1313
-    }
1314
-
1315
-
1316
-
1317
-    /**
1318
-     * sets the date on a datetime property
1319
-     *
1320
-     * @access protected
1321
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1322
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1323
-     * @throws \EE_Error
1324
-     */
1325
-    protected function _set_date_for($date, $fieldname)
1326
-    {
1327
-        $this->_set_date_time('D', $date, $fieldname);
1328
-    }
1329
-
1330
-
1331
-
1332
-    /**
1333
-     * This takes care of setting a date or time independently on a given model object property. This method also
1334
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1335
-     *
1336
-     * @access protected
1337
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1338
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1339
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1340
-     *                                        EE_Datetime_Field property)
1341
-     * @throws \EE_Error
1342
-     */
1343
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1344
-    {
1345
-        $field = $this->_get_dtt_field_settings($fieldname);
1346
-        $field->set_timezone($this->_timezone);
1347
-        $field->set_date_format($this->_dt_frmt);
1348
-        $field->set_time_format($this->_tm_frmt);
1349
-        switch ($what) {
1350
-            case 'T' :
1351
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1352
-                    $datetime_value,
1353
-                    $this->_fields[$fieldname]
1354
-                );
1355
-                break;
1356
-            case 'D' :
1357
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1358
-                    $datetime_value,
1359
-                    $this->_fields[$fieldname]
1360
-                );
1361
-                break;
1362
-            case 'B' :
1363
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1364
-                break;
1365
-        }
1366
-        $this->_clear_cached_property($fieldname);
1367
-    }
1368
-
1369
-
1370
-
1371
-    /**
1372
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1373
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1374
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1375
-     * that could lead to some unexpected results!
1376
-     *
1377
-     * @access public
1378
-     * @param string               $field_name This is the name of the field on the object that contains the date/time
1379
-     *                                         value being returned.
1380
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1381
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1382
-     * @param string               $prepend    You can include something to prepend on the timestamp
1383
-     * @param string               $append     You can include something to append on the timestamp
1384
-     * @throws EE_Error
1385
-     * @return string timestamp
1386
-     */
1387
-    public function display_in_my_timezone(
1388
-        $field_name,
1389
-        $callback = 'get_datetime',
1390
-        $args = null,
1391
-        $prepend = '',
1392
-        $append = ''
1393
-    ) {
1394
-        $timezone = EEH_DTT_Helper::get_timezone();
1395
-        if ($timezone === $this->_timezone) {
1396
-            return '';
1397
-        }
1398
-        $original_timezone = $this->_timezone;
1399
-        $this->set_timezone($timezone);
1400
-        $fn = (array)$field_name;
1401
-        $args = array_merge($fn, (array)$args);
1402
-        if ( ! method_exists($this, $callback)) {
1403
-            throw new EE_Error(
1404
-                sprintf(
1405
-                    __(
1406
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1407
-                        'event_espresso'
1408
-                    ),
1409
-                    $callback
1410
-                )
1411
-            );
1412
-        }
1413
-        $args = (array)$args;
1414
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1415
-        $this->set_timezone($original_timezone);
1416
-        return $return;
1417
-    }
1418
-
1419
-
1420
-
1421
-    /**
1422
-     * Deletes this model object.
1423
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1424
-     * override
1425
-     * `EE_Base_Class::_delete` NOT this class.
1426
-     *
1427
-     * @return boolean | int
1428
-     * @throws \EE_Error
1429
-     */
1430
-    public function delete()
1431
-    {
1432
-        /**
1433
-         * Called just before the `EE_Base_Class::_delete` method call.
1434
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1435
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1436
-         * soft deletes (trash) the object and does not permanently delete it.
1437
-         *
1438
-         * @param EE_Base_Class $model_object about to be 'deleted'
1439
-         */
1440
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1441
-        $result = $this->_delete();
1442
-        /**
1443
-         * Called just after the `EE_Base_Class::_delete` method call.
1444
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1445
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1446
-         * soft deletes (trash) the object and does not permanently delete it.
1447
-         *
1448
-         * @param EE_Base_Class $model_object that was just 'deleted'
1449
-         * @param boolean       $result
1450
-         */
1451
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1452
-        return $result;
1453
-    }
1454
-
1455
-
1456
-
1457
-    /**
1458
-     * Calls the specific delete method for the instantiated class.
1459
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1460
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1461
-     * `EE_Base_Class::delete`
1462
-     *
1463
-     * @return bool|int
1464
-     * @throws \EE_Error
1465
-     */
1466
-    protected function _delete()
1467
-    {
1468
-        return $this->delete_permanently();
1469
-    }
1470
-
1471
-
1472
-
1473
-    /**
1474
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1475
-     * error)
1476
-     *
1477
-     * @return bool | int
1478
-     * @throws \EE_Error
1479
-     */
1480
-    public function delete_permanently()
1481
-    {
1482
-        /**
1483
-         * Called just before HARD deleting a model object
1484
-         *
1485
-         * @param EE_Base_Class $model_object about to be 'deleted'
1486
-         */
1487
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1488
-        $model = $this->get_model();
1489
-        $result = $model->delete_permanently_by_ID($this->ID());
1490
-        $this->refresh_cache_of_related_objects();
1491
-        /**
1492
-         * Called just after HARD deleting a model object
1493
-         *
1494
-         * @param EE_Base_Class $model_object that was just 'deleted'
1495
-         * @param boolean       $result
1496
-         */
1497
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1498
-        return $result;
1499
-    }
1500
-
1501
-
1502
-
1503
-    /**
1504
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1505
-     * related model objects
1506
-     *
1507
-     * @throws \EE_Error
1508
-     */
1509
-    public function refresh_cache_of_related_objects()
1510
-    {
1511
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1512
-            if ( ! empty($this->_model_relations[$relation_name])) {
1513
-                $related_objects = $this->_model_relations[$relation_name];
1514
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1515
-                    //this relation only stores a single model object, not an array
1516
-                    //but let's make it consistent
1517
-                    $related_objects = array($related_objects);
1518
-                }
1519
-                foreach ($related_objects as $related_object) {
1520
-                    //only refresh their cache if they're in memory
1521
-                    if ($related_object instanceof EE_Base_Class) {
1522
-                        $related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1523
-                    }
1524
-                }
1525
-            }
1526
-        }
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     *        Saves this object to the database. An array may be supplied to set some values on this
1533
-     * object just before saving.
1534
-     *
1535
-     * @access public
1536
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1537
-     *                                 if provided during the save() method (often client code will change the fields'
1538
-     *                                 values before calling save)
1539
-     * @throws \EE_Error
1540
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1541
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1542
-     */
1543
-    public function save($set_cols_n_values = array())
1544
-    {
1545
-        /**
1546
-         * Filters the fields we're about to save on the model object
1547
-         *
1548
-         * @param array         $set_cols_n_values
1549
-         * @param EE_Base_Class $model_object
1550
-         */
1551
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1552
-            $this);
1553
-        //set attributes as provided in $set_cols_n_values
1554
-        foreach ($set_cols_n_values as $column => $value) {
1555
-            $this->set($column, $value);
1556
-        }
1557
-        /**
1558
-         * Saving a model object.
1559
-         * Before we perform a save, this action is fired.
1560
-         *
1561
-         * @param EE_Base_Class $model_object the model object about to be saved.
1562
-         */
1563
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1564
-        if ( ! $this->allow_persist()) {
1565
-            return 0;
1566
-        }
1567
-        //now get current attribute values
1568
-        $save_cols_n_values = $this->_fields;
1569
-        //if the object already has an ID, update it. Otherwise, insert it
1570
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1571
-        $old_assumption_concerning_value_preparation = $this->get_model()
1572
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1573
-        $this->get_model()->assume_values_already_prepared_by_model_object(true);
1574
-        //does this model have an autoincrement PK?
1575
-        if ($this->get_model()->has_primary_key_field()) {
1576
-            if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1577
-                //ok check if it's set, if so: update; if not, insert
1578
-                if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1579
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1580
-                } else {
1581
-                    unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1582
-                    $results = $this->get_model()->insert($save_cols_n_values);
1583
-                    if ($results) {
1584
-                        //if successful, set the primary key
1585
-                        //but don't use the normal SET method, because it will check if
1586
-                        //an item with the same ID exists in the mapper & db, then
1587
-                        //will find it in the db (because we just added it) and THAT object
1588
-                        //will get added to the mapper before we can add this one!
1589
-                        //but if we just avoid using the SET method, all that headache can be avoided
1590
-                        $pk_field_name = self::_get_primary_key_name(get_class($this));
1591
-                        $this->_fields[$pk_field_name] = $results;
1592
-                        $this->_clear_cached_property($pk_field_name);
1593
-                        $this->get_model()->add_to_entity_map($this);
1594
-                        $this->_update_cached_related_model_objs_fks();
1595
-                    }
1596
-                }
1597
-            } else {//PK is NOT auto-increment
1598
-                //so check if one like it already exists in the db
1599
-                if ($this->get_model()->exists_by_ID($this->ID())) {
1600
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1601
-                        throw new EE_Error(
1602
-                            sprintf(
1603
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1604
-                                    'event_espresso'),
1605
-                                get_class($this),
1606
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1607
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1608
-                                '<br />'
1609
-                            )
1610
-                        );
1611
-                    }
1612
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1613
-                } else {
1614
-                    $results = $this->get_model()->insert($save_cols_n_values);
1615
-                    $this->_update_cached_related_model_objs_fks();
1616
-                }
1617
-            }
1618
-        } else {//there is NO primary key
1619
-            $already_in_db = false;
1620
-            foreach ($this->get_model()->unique_indexes() as $index) {
1621
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1622
-                if ($this->get_model()->exists(array($uniqueness_where_params))) {
1623
-                    $already_in_db = true;
1624
-                }
1625
-            }
1626
-            if ($already_in_db) {
1627
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1628
-                    $this->get_model()->get_combined_primary_key_fields());
1629
-                $results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1630
-            } else {
1631
-                $results = $this->get_model()->insert($save_cols_n_values);
1632
-            }
1633
-        }
1634
-        //restore the old assumption about values being prepared by the model object
1635
-        $this->get_model()
1636
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1637
-        /**
1638
-         * After saving the model object this action is called
1639
-         *
1640
-         * @param EE_Base_Class $model_object which was just saved
1641
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1642
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1643
-         */
1644
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1645
-        return $results;
1646
-    }
1647
-
1648
-
1649
-
1650
-    /**
1651
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1652
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1653
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1654
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1655
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1656
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1657
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1658
-     *
1659
-     * @return void
1660
-     * @throws \EE_Error
1661
-     */
1662
-    protected function _update_cached_related_model_objs_fks()
1663
-    {
1664
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1665
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1666
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1667
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1668
-                        $this->get_model()->get_this_model_name()
1669
-                    );
1670
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1671
-                    if ($related_model_obj_in_cache->ID()) {
1672
-                        $related_model_obj_in_cache->save();
1673
-                    }
1674
-                }
1675
-            }
1676
-        }
1677
-    }
1678
-
1679
-
1680
-
1681
-    /**
1682
-     * Saves this model object and its NEW cached relations to the database.
1683
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1684
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1685
-     * because otherwise, there's a potential for infinite looping of saving
1686
-     * Saves the cached related model objects, and ensures the relation between them
1687
-     * and this object and properly setup
1688
-     *
1689
-     * @return int ID of new model object on save; 0 on failure+
1690
-     * @throws \EE_Error
1691
-     */
1692
-    public function save_new_cached_related_model_objs()
1693
-    {
1694
-        //make sure this has been saved
1695
-        if ( ! $this->ID()) {
1696
-            $id = $this->save();
1697
-        } else {
1698
-            $id = $this->ID();
1699
-        }
1700
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1701
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1702
-            if ($this->_model_relations[$relationName]) {
1703
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1704
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1705
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1706
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1707
-                    //but ONLY if it DOES NOT exist in the DB
1708
-                    /* @var $related_model_obj EE_Base_Class */
1709
-                    $related_model_obj = $this->_model_relations[$relationName];
1710
-                    //					if( ! $related_model_obj->ID()){
1711
-                    $this->_add_relation_to($related_model_obj, $relationName);
1712
-                    $related_model_obj->save_new_cached_related_model_objs();
1713
-                    //					}
1714
-                } else {
1715
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1716
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1717
-                        //but ONLY if it DOES NOT exist in the DB
1718
-                        //						if( ! $related_model_obj->ID()){
1719
-                        $this->_add_relation_to($related_model_obj, $relationName);
1720
-                        $related_model_obj->save_new_cached_related_model_objs();
1721
-                        //						}
1722
-                    }
1723
-                }
1724
-            }
1725
-        }
1726
-        return $id;
1727
-    }
1728
-
1729
-
1730
-
1731
-    /**
1732
-     * for getting a model while instantiated.
1733
-     *
1734
-     * @return \EEM_Base | \EEM_CPT_Base
1735
-     */
1736
-    public function get_model()
1737
-    {
1738
-        $modelName = self::_get_model_classname(get_class($this));
1739
-        return self::_get_model_instance_with_name($modelName, $this->_timezone);
1740
-    }
1741
-
1742
-
1743
-
1744
-    /**
1745
-     * @param $props_n_values
1746
-     * @param $classname
1747
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1748
-     * @throws \EE_Error
1749
-     */
1750
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1751
-    {
1752
-        //TODO: will not work for Term_Relationships because they have no PK!
1753
-        $primary_id_ref = self::_get_primary_key_name($classname);
1754
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1755
-            $id = $props_n_values[$primary_id_ref];
1756
-            return self::_get_model($classname)->get_from_entity_map($id);
1757
-        }
1758
-        return false;
1759
-    }
1760
-
1761
-
1762
-
1763
-    /**
1764
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1765
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1766
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1767
-     * we return false.
1768
-     *
1769
-     * @param  array  $props_n_values   incoming array of properties and their values
1770
-     * @param  string $classname        the classname of the child class
1771
-     * @param null    $timezone
1772
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1773
-     *                                  date_format and the second value is the time format
1774
-     * @return mixed (EE_Base_Class|bool)
1775
-     * @throws \EE_Error
1776
-     */
1777
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1778
-    {
1779
-        $existing = null;
1780
-        if (self::_get_model($classname)->has_primary_key_field()) {
1781
-            $primary_id_ref = self::_get_primary_key_name($classname);
1782
-            if (array_key_exists($primary_id_ref, $props_n_values)
1783
-                && ! empty($props_n_values[$primary_id_ref])
1784
-            ) {
1785
-                $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1786
-                    $props_n_values[$primary_id_ref]
1787
-                );
1788
-            }
1789
-        } elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1790
-            //no primary key on this model, but there's still a matching item in the DB
1791
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1792
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1793
-            );
1794
-        }
1795
-        if ($existing) {
1796
-            //set date formats if present before setting values
1797
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1798
-                $existing->set_date_format($date_formats[0]);
1799
-                $existing->set_time_format($date_formats[1]);
1800
-            } else {
1801
-                //set default formats for date and time
1802
-                $existing->set_date_format(get_option('date_format'));
1803
-                $existing->set_time_format(get_option('time_format'));
1804
-            }
1805
-            foreach ($props_n_values as $property => $field_value) {
1806
-                $existing->set($property, $field_value);
1807
-            }
1808
-            return $existing;
1809
-        } else {
1810
-            return false;
1811
-        }
1812
-    }
1813
-
1814
-
1815
-
1816
-    /**
1817
-     * Gets the EEM_*_Model for this class
1818
-     *
1819
-     * @access public now, as this is more convenient
1820
-     * @param      $classname
1821
-     * @param null $timezone
1822
-     * @throws EE_Error
1823
-     * @return EEM_Base
1824
-     */
1825
-    protected static function _get_model($classname, $timezone = null)
1826
-    {
1827
-        //find model for this class
1828
-        if ( ! $classname) {
1829
-            throw new EE_Error(
1830
-                sprintf(
1831
-                    __(
1832
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1833
-                        "event_espresso"
1834
-                    ),
1835
-                    $classname
1836
-                )
1837
-            );
1838
-        }
1839
-        $modelName = self::_get_model_classname($classname);
1840
-        return self::_get_model_instance_with_name($modelName, $timezone);
1841
-    }
1842
-
1843
-
1844
-
1845
-    /**
1846
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1847
-     *
1848
-     * @param string $model_classname
1849
-     * @param null   $timezone
1850
-     * @return EEM_Base
1851
-     */
1852
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1853
-    {
1854
-        $model_classname = str_replace('EEM_', '', $model_classname);
1855
-        $model = EE_Registry::instance()->load_model($model_classname);
1856
-        $model->set_timezone($timezone);
1857
-        return $model;
1858
-    }
1859
-
1860
-
1861
-
1862
-    /**
1863
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1864
-     * Also works if a model class's classname is provided (eg EE_Registration).
1865
-     *
1866
-     * @param null $model_name
1867
-     * @return string like EEM_Attendee
1868
-     */
1869
-    private static function _get_model_classname($model_name = null)
1870
-    {
1871
-        if (strpos($model_name, "EE_") === 0) {
1872
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1873
-        } else {
1874
-            $model_classname = "EEM_" . $model_name;
1875
-        }
1876
-        return $model_classname;
1877
-    }
1878
-
1879
-
1880
-
1881
-    /**
1882
-     * returns the name of the primary key attribute
1883
-     *
1884
-     * @param null $classname
1885
-     * @throws EE_Error
1886
-     * @return string
1887
-     */
1888
-    protected static function _get_primary_key_name($classname = null)
1889
-    {
1890
-        if ( ! $classname) {
1891
-            throw new EE_Error(
1892
-                sprintf(
1893
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1894
-                    $classname
1895
-                )
1896
-            );
1897
-        }
1898
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
1899
-    }
1900
-
1901
-
1902
-
1903
-    /**
1904
-     * Gets the value of the primary key.
1905
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
1906
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1907
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1908
-     *
1909
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1910
-     * @throws \EE_Error
1911
-     */
1912
-    public function ID()
1913
-    {
1914
-        //now that we know the name of the variable, use a variable variable to get its value and return its
1915
-        if ($this->get_model()->has_primary_key_field()) {
1916
-            return $this->_fields[self::_get_primary_key_name(get_class($this))];
1917
-        } else {
1918
-            return $this->get_model()->get_index_primary_key_string($this->_fields);
1919
-        }
1920
-    }
1921
-
1922
-
1923
-
1924
-    /**
1925
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1926
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1927
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1928
-     *
1929
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1930
-     * @param string $relationName                     eg 'Events','Question',etc.
1931
-     *                                                 an attendee to a group, you also want to specify which role they
1932
-     *                                                 will have in that group. So you would use this parameter to
1933
-     *                                                 specify array('role-column-name'=>'role-id')
1934
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1935
-     *                                                 allow you to further constrict the relation to being added.
1936
-     *                                                 However, keep in mind that the columns (keys) given must match a
1937
-     *                                                 column on the JOIN table and currently only the HABTM models
1938
-     *                                                 accept these additional conditions.  Also remember that if an
1939
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
1940
-     *                                                 NEW row is created in the join table.
1941
-     * @param null   $cache_id
1942
-     * @throws EE_Error
1943
-     * @return EE_Base_Class the object the relation was added to
1944
-     */
1945
-    public function _add_relation_to(
1946
-        $otherObjectModelObjectOrID,
1947
-        $relationName,
1948
-        $extra_join_model_fields_n_values = array(),
1949
-        $cache_id = null
1950
-    ) {
1951
-        //if this thing exists in the DB, save the relation to the DB
1952
-        if ($this->ID()) {
1953
-            $otherObject = $this->get_model()
1954
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
1955
-                                    $extra_join_model_fields_n_values);
1956
-            //clear cache so future get_many_related and get_first_related() return new results.
1957
-            $this->clear_cache($relationName, $otherObject, true);
1958
-            if ($otherObject instanceof EE_Base_Class) {
1959
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1960
-            }
1961
-        } else {
1962
-            //this thing doesn't exist in the DB,  so just cache it
1963
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1964
-                throw new EE_Error(sprintf(
1965
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
1966
-                        'event_espresso'),
1967
-                    $otherObjectModelObjectOrID,
1968
-                    get_class($this)
1969
-                ));
1970
-            } else {
1971
-                $otherObject = $otherObjectModelObjectOrID;
1972
-            }
1973
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1974
-        }
1975
-        if ($otherObject instanceof EE_Base_Class) {
1976
-            //fix the reciprocal relation too
1977
-            if ($otherObject->ID()) {
1978
-                //its saved so assumed relations exist in the DB, so we can just
1979
-                //clear the cache so future queries use the updated info in the DB
1980
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
1981
-            } else {
1982
-                //it's not saved, so it caches relations like this
1983
-                $otherObject->cache($this->get_model()->get_this_model_name(), $this);
1984
-            }
1985
-        }
1986
-        return $otherObject;
1987
-    }
1988
-
1989
-
1990
-
1991
-    /**
1992
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
1993
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
1994
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
1995
-     * from the cache
1996
-     *
1997
-     * @param mixed  $otherObjectModelObjectOrID
1998
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
1999
-     *                to the DB yet
2000
-     * @param string $relationName
2001
-     * @param array  $where_query
2002
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2003
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2004
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2005
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2006
-     *                created in the join table.
2007
-     * @return EE_Base_Class the relation was removed from
2008
-     * @throws \EE_Error
2009
-     */
2010
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2011
-    {
2012
-        if ($this->ID()) {
2013
-            //if this exists in the DB, save the relation change to the DB too
2014
-            $otherObject = $this->get_model()
2015
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2016
-                                    $where_query);
2017
-            $this->clear_cache($relationName, $otherObject);
2018
-        } else {
2019
-            //this doesn't exist in the DB, just remove it from the cache
2020
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2021
-        }
2022
-        if ($otherObject instanceof EE_Base_Class) {
2023
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2024
-        }
2025
-        return $otherObject;
2026
-    }
2027
-
2028
-
2029
-
2030
-    /**
2031
-     * Removes ALL the related things for the $relationName.
2032
-     *
2033
-     * @param string $relationName
2034
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2035
-     * @return EE_Base_Class
2036
-     * @throws \EE_Error
2037
-     */
2038
-    public function _remove_relations($relationName, $where_query_params = array())
2039
-    {
2040
-        if ($this->ID()) {
2041
-            //if this exists in the DB, save the relation change to the DB too
2042
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2043
-            $this->clear_cache($relationName, null, true);
2044
-        } else {
2045
-            //this doesn't exist in the DB, just remove it from the cache
2046
-            $otherObjects = $this->clear_cache($relationName, null, true);
2047
-        }
2048
-        if (is_array($otherObjects)) {
2049
-            foreach ($otherObjects as $otherObject) {
2050
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2051
-            }
2052
-        }
2053
-        return $otherObjects;
2054
-    }
2055
-
2056
-
2057
-
2058
-    /**
2059
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2060
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2061
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2062
-     * because we want to get even deleted items etc.
2063
-     *
2064
-     * @param string $relationName key in the model's _model_relations array
2065
-     * @param array  $query_params like EEM_Base::get_all
2066
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2067
-     * @throws \EE_Error
2068
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2069
-     *                             you want IDs
2070
-     */
2071
-    public function get_many_related($relationName, $query_params = array())
2072
-    {
2073
-        if ($this->ID()) {
2074
-            //this exists in the DB, so get the related things from either the cache or the DB
2075
-            //if there are query parameters, forget about caching the related model objects.
2076
-            if ($query_params) {
2077
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2078
-            } else {
2079
-                //did we already cache the result of this query?
2080
-                $cached_results = $this->get_all_from_cache($relationName);
2081
-                if ( ! $cached_results) {
2082
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2083
-                    //if no query parameters were passed, then we got all the related model objects
2084
-                    //for that relation. We can cache them then.
2085
-                    foreach ($related_model_objects as $related_model_object) {
2086
-                        $this->cache($relationName, $related_model_object);
2087
-                    }
2088
-                } else {
2089
-                    $related_model_objects = $cached_results;
2090
-                }
2091
-            }
2092
-        } else {
2093
-            //this doesn't exist in the DB, so just get the related things from the cache
2094
-            $related_model_objects = $this->get_all_from_cache($relationName);
2095
-        }
2096
-        return $related_model_objects;
2097
-    }
2098
-
2099
-
2100
-
2101
-    /**
2102
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2103
-     * unless otherwise specified in the $query_params
2104
-     *
2105
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2106
-     * @param array  $query_params   like EEM_Base::get_all's
2107
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2108
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2109
-     *                               that by the setting $distinct to TRUE;
2110
-     * @return int
2111
-     */
2112
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2113
-    {
2114
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2115
-    }
2116
-
2117
-
2118
-
2119
-    /**
2120
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2121
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2122
-     *
2123
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2124
-     * @param array  $query_params  like EEM_Base::get_all's
2125
-     * @param string $field_to_sum  name of field to count by.
2126
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2127
-     *                              change it)
2128
-     * @return int
2129
-     */
2130
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2131
-    {
2132
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2133
-    }
2134
-
2135
-
2136
-
2137
-    /**
2138
-     * Gets the first (ie, one) related model object of the specified type.
2139
-     *
2140
-     * @param string $relationName key in the model's _model_relations array
2141
-     * @param array  $query_params like EEM_Base::get_all
2142
-     * @return EE_Base_Class (not an array, a single object)
2143
-     * @throws \EE_Error
2144
-     */
2145
-    public function get_first_related($relationName, $query_params = array())
2146
-    {
2147
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2148
-            //if they've provided some query parameters, don't bother trying to cache the result
2149
-            //also make sure we're not caching the result of get_first_related
2150
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2151
-            if ($query_params
2152
-                || ! $this->get_model()->related_settings_for($relationName)
2153
-                     instanceof
2154
-                     EE_Belongs_To_Relation
2155
-            ) {
2156
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2157
-            } else {
2158
-                //first, check if we've already cached the result of this query
2159
-                $cached_result = $this->get_one_from_cache($relationName);
2160
-                if ( ! $cached_result) {
2161
-                    $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2162
-                    $this->cache($relationName, $related_model_object);
2163
-                } else {
2164
-                    $related_model_object = $cached_result;
2165
-                }
2166
-            }
2167
-        } else {
2168
-            $related_model_object = null;
2169
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2170
-            if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2171
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2172
-            }
2173
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2174
-            if ( ! $related_model_object) {
2175
-                $related_model_object = $this->get_one_from_cache($relationName);
2176
-            }
2177
-        }
2178
-        return $related_model_object;
2179
-    }
2180
-
2181
-
2182
-
2183
-    /**
2184
-     * Does a delete on all related objects of type $relationName and removes
2185
-     * the current model object's relation to them. If they can't be deleted (because
2186
-     * of blocking related model objects) does nothing. If the related model objects are
2187
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2188
-     * If this model object doesn't exist yet in the DB, just removes its related things
2189
-     *
2190
-     * @param string $relationName
2191
-     * @param array  $query_params like EEM_Base::get_all's
2192
-     * @return int how many deleted
2193
-     * @throws \EE_Error
2194
-     */
2195
-    public function delete_related($relationName, $query_params = array())
2196
-    {
2197
-        if ($this->ID()) {
2198
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2199
-        } else {
2200
-            $count = count($this->get_all_from_cache($relationName));
2201
-            $this->clear_cache($relationName, null, true);
2202
-        }
2203
-        return $count;
2204
-    }
2205
-
2206
-
2207
-
2208
-    /**
2209
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2210
-     * the current model object's relation to them. If they can't be deleted (because
2211
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2212
-     * If the related thing isn't a soft-deletable model object, this function is identical
2213
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2214
-     *
2215
-     * @param string $relationName
2216
-     * @param array  $query_params like EEM_Base::get_all's
2217
-     * @return int how many deleted (including those soft deleted)
2218
-     * @throws \EE_Error
2219
-     */
2220
-    public function delete_related_permanently($relationName, $query_params = array())
2221
-    {
2222
-        if ($this->ID()) {
2223
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2224
-        } else {
2225
-            $count = count($this->get_all_from_cache($relationName));
2226
-        }
2227
-        $this->clear_cache($relationName, null, true);
2228
-        return $count;
2229
-    }
2230
-
2231
-
2232
-
2233
-    /**
2234
-     * is_set
2235
-     * Just a simple utility function children can use for checking if property exists
2236
-     *
2237
-     * @access  public
2238
-     * @param  string $field_name property to check
2239
-     * @return bool                              TRUE if existing,FALSE if not.
2240
-     */
2241
-    public function is_set($field_name)
2242
-    {
2243
-        return isset($this->_fields[$field_name]);
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2250
-     * EE_Error exception if they don't
2251
-     *
2252
-     * @param  mixed (string|array) $properties properties to check
2253
-     * @throws EE_Error
2254
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2255
-     */
2256
-    protected function _property_exists($properties)
2257
-    {
2258
-        foreach ((array)$properties as $property_name) {
2259
-            //first make sure this property exists
2260
-            if ( ! $this->_fields[$property_name]) {
2261
-                throw new EE_Error(
2262
-                    sprintf(
2263
-                        __(
2264
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2265
-                            'event_espresso'
2266
-                        ),
2267
-                        $property_name
2268
-                    )
2269
-                );
2270
-            }
2271
-        }
2272
-        return true;
2273
-    }
2274
-
2275
-
2276
-
2277
-    /**
2278
-     * This simply returns an array of model fields for this object
2279
-     *
2280
-     * @return array
2281
-     * @throws \EE_Error
2282
-     */
2283
-    public function model_field_array()
2284
-    {
2285
-        $fields = $this->get_model()->field_settings(false);
2286
-        $properties = array();
2287
-        //remove prepended underscore
2288
-        foreach ($fields as $field_name => $settings) {
2289
-            $properties[$field_name] = $this->get($field_name);
2290
-        }
2291
-        return $properties;
2292
-    }
2293
-
2294
-
2295
-
2296
-    /**
2297
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2298
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2299
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2300
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2301
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2302
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2303
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2304
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2305
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2306
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2307
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2308
-     *        return $previousReturnValue.$returnString;
2309
-     * }
2310
-     * require('EE_Answer.class.php');
2311
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2312
-     * echo $answer->my_callback('monkeys',100);
2313
-     * //will output "you called my_callback! and passed args:monkeys,100"
2314
-     *
2315
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2316
-     * @param array  $args       array of original arguments passed to the function
2317
-     * @throws EE_Error
2318
-     * @return mixed whatever the plugin which calls add_filter decides
2319
-     */
2320
-    public function __call($methodName, $args)
2321
-    {
2322
-        $className = get_class($this);
2323
-        $tagName = "FHEE__{$className}__{$methodName}";
2324
-        if ( ! has_filter($tagName)) {
2325
-            throw new EE_Error(
2326
-                sprintf(
2327
-                    __(
2328
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2329
-                        "event_espresso"
2330
-                    ),
2331
-                    $methodName,
2332
-                    $className,
2333
-                    $tagName
2334
-                )
2335
-            );
2336
-        }
2337
-        return apply_filters($tagName, null, $this, $args);
2338
-    }
2339
-
2340
-
2341
-
2342
-    /**
2343
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2344
-     * A $previous_value can be specified in case there are many meta rows with the same key
2345
-     *
2346
-     * @param string $meta_key
2347
-     * @param string $meta_value
2348
-     * @param string $previous_value
2349
-     * @return int records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2350
-     * @throws \EE_Error
2351
-     * NOTE: if the values haven't changed, returns 0
2352
-     */
2353
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2354
-    {
2355
-        $query_params = array(
2356
-            array(
2357
-                'EXM_key'  => $meta_key,
2358
-                'OBJ_ID'   => $this->ID(),
2359
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2360
-            ),
2361
-        );
2362
-        if ($previous_value !== null) {
2363
-            $query_params[0]['EXM_value'] = $meta_value;
2364
-        }
2365
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2366
-        if ( ! $existing_rows_like_that) {
2367
-            return $this->add_extra_meta($meta_key, $meta_value);
2368
-        } else {
2369
-            foreach ($existing_rows_like_that as $existing_row) {
2370
-                $existing_row->save(array('EXM_value' => $meta_value));
2371
-            }
2372
-            return count($existing_rows_like_that);
2373
-        }
2374
-    }
2375
-
2376
-
2377
-
2378
-    /**
2379
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2380
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2381
-     * extra meta row was entered, false if not
2382
-     *
2383
-     * @param string  $meta_key
2384
-     * @param string  $meta_value
2385
-     * @param boolean $unique
2386
-     * @return boolean
2387
-     * @throws \EE_Error
2388
-     */
2389
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2390
-    {
2391
-        if ($unique) {
2392
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2393
-                array(
2394
-                    array(
2395
-                        'EXM_key'  => $meta_key,
2396
-                        'OBJ_ID'   => $this->ID(),
2397
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2398
-                    ),
2399
-                )
2400
-            );
2401
-            if ($existing_extra_meta) {
2402
-                return false;
2403
-            }
2404
-        }
2405
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2406
-            array(
2407
-                'EXM_key'   => $meta_key,
2408
-                'EXM_value' => $meta_value,
2409
-                'OBJ_ID'    => $this->ID(),
2410
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2411
-            )
2412
-        );
2413
-        $new_extra_meta->save();
2414
-        return true;
2415
-    }
2416
-
2417
-
2418
-
2419
-    /**
2420
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2421
-     * is specified, only deletes extra meta records with that value.
2422
-     *
2423
-     * @param string $meta_key
2424
-     * @param string $meta_value
2425
-     * @return int number of extra meta rows deleted
2426
-     * @throws \EE_Error
2427
-     */
2428
-    public function delete_extra_meta($meta_key, $meta_value = null)
2429
-    {
2430
-        $query_params = array(
2431
-            array(
2432
-                'EXM_key'  => $meta_key,
2433
-                'OBJ_ID'   => $this->ID(),
2434
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2435
-            ),
2436
-        );
2437
-        if ($meta_value !== null) {
2438
-            $query_params[0]['EXM_value'] = $meta_value;
2439
-        }
2440
-        return EEM_Extra_Meta::instance()->delete($query_params);
2441
-    }
2442
-
2443
-
2444
-
2445
-    /**
2446
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2447
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2448
-     * You can specify $default is case you haven't found the extra meta
2449
-     *
2450
-     * @param string  $meta_key
2451
-     * @param boolean $single
2452
-     * @param mixed   $default if we don't find anything, what should we return?
2453
-     * @return mixed single value if $single; array if ! $single
2454
-     * @throws \EE_Error
2455
-     */
2456
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2457
-    {
2458
-        if ($single) {
2459
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2460
-            if ($result instanceof EE_Extra_Meta) {
2461
-                return $result->value();
2462
-            } else {
2463
-                return $default;
2464
-            }
2465
-        } else {
2466
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2467
-            if ($results) {
2468
-                $values = array();
2469
-                foreach ($results as $result) {
2470
-                    if ($result instanceof EE_Extra_Meta) {
2471
-                        $values[$result->ID()] = $result->value();
2472
-                    }
2473
-                }
2474
-                return $values;
2475
-            } else {
2476
-                return $default;
2477
-            }
2478
-        }
2479
-    }
2480
-
2481
-
2482
-
2483
-    /**
2484
-     * Returns a simple array of all the extra meta associated with this model object.
2485
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2486
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2487
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2488
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2489
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2490
-     * finally the extra meta's value as each sub-value. (eg
2491
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2492
-     *
2493
-     * @param boolean $one_of_each_key
2494
-     * @return array
2495
-     * @throws \EE_Error
2496
-     */
2497
-    public function all_extra_meta_array($one_of_each_key = true)
2498
-    {
2499
-        $return_array = array();
2500
-        if ($one_of_each_key) {
2501
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2502
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2503
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2504
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2505
-                }
2506
-            }
2507
-        } else {
2508
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2509
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2510
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2511
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2512
-                        $return_array[$extra_meta_obj->key()] = array();
2513
-                    }
2514
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2515
-                }
2516
-            }
2517
-        }
2518
-        return $return_array;
2519
-    }
2520
-
2521
-
2522
-
2523
-    /**
2524
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2525
-     *
2526
-     * @return string
2527
-     * @throws \EE_Error
2528
-     */
2529
-    public function name()
2530
-    {
2531
-        //find a field that's not a text field
2532
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2533
-        if ($field_we_can_use) {
2534
-            return $this->get($field_we_can_use->get_name());
2535
-        } else {
2536
-            $first_few_properties = $this->model_field_array();
2537
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2538
-            $name_parts = array();
2539
-            foreach ($first_few_properties as $name => $value) {
2540
-                $name_parts[] = "$name:$value";
2541
-            }
2542
-            return implode(",", $name_parts);
2543
-        }
2544
-    }
2545
-
2546
-
2547
-
2548
-    /**
2549
-     * in_entity_map
2550
-     * Checks if this model object has been proven to already be in the entity map
2551
-     *
2552
-     * @return boolean
2553
-     * @throws \EE_Error
2554
-     */
2555
-    public function in_entity_map()
2556
-    {
2557
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2558
-            //well, if we looked, did we find it in the entity map?
2559
-            return true;
2560
-        } else {
2561
-            return false;
2562
-        }
2563
-    }
2564
-
2565
-
2566
-
2567
-    /**
2568
-     * refresh_from_db
2569
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2570
-     *
2571
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2572
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2573
-     */
2574
-    public function refresh_from_db()
2575
-    {
2576
-        if ($this->ID() && $this->in_entity_map()) {
2577
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2578
-        } else {
2579
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2580
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2581
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2582
-            //absolutely nothing in it for this ID
2583
-            if (WP_DEBUG) {
2584
-                throw new EE_Error(
2585
-                    sprintf(
2586
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2587
-                            'event_espresso'),
2588
-                        $this->ID(),
2589
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2590
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2591
-                    )
2592
-                );
2593
-            }
2594
-        }
2595
-    }
2596
-
2597
-
2598
-
2599
-    /**
2600
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2601
-     * (probably a bad assumption they have made, oh well)
2602
-     *
2603
-     * @return string
2604
-     */
2605
-    public function __toString()
2606
-    {
2607
-        try {
2608
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2609
-        } catch (Exception $e) {
2610
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2611
-            return '';
2612
-        }
2613
-    }
2614
-
2615
-
2616
-
2617
-    /**
2618
-     * Clear related model objects if they're already in the DB, because otherwise when we
2619
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2620
-     * This means if we have made changes to those related model objects, and want to unserialize
2621
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2622
-     * Instead, those related model objects should be directly serialized and stored.
2623
-     * Eg, the following won't work:
2624
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2625
-     * $att = $reg->attendee();
2626
-     * $att->set( 'ATT_fname', 'Dirk' );
2627
-     * update_option( 'my_option', serialize( $reg ) );
2628
-     * //END REQUEST
2629
-     * //START NEXT REQUEST
2630
-     * $reg = get_option( 'my_option' );
2631
-     * $reg->attendee()->save();
2632
-     * And would need to be replace with:
2633
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2634
-     * $att = $reg->attendee();
2635
-     * $att->set( 'ATT_fname', 'Dirk' );
2636
-     * update_option( 'my_option', serialize( $reg ) );
2637
-     * //END REQUEST
2638
-     * //START NEXT REQUEST
2639
-     * $att = get_option( 'my_option' );
2640
-     * $att->save();
2641
-     *
2642
-     * @return array
2643
-     * @throws \EE_Error
2644
-     */
2645
-    public function __sleep()
2646
-    {
2647
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2648
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2649
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2650
-                if (
2651
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2652
-                    && $this->get_one_from_cache($relation_name)->ID()
2653
-                ) {
2654
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2655
-                }
2656
-            }
2657
-        }
2658
-        $this->_props_n_values_provided_in_constructor = array();
2659
-        return array_keys(get_object_vars($this));
2660
-    }
2661
-
2662
-
2663
-
2664
-    /**
2665
-     * restore _props_n_values_provided_in_constructor
2666
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2667
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2668
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2669
-     */
2670
-    public function __wakeup()
2671
-    {
2672
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2673
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
+	 * access to it.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_timezone;
48
+
49
+
50
+
51
+	/**
52
+	 * date format
53
+	 * pattern or format for displaying dates
54
+	 *
55
+	 * @var string $_dt_frmt
56
+	 */
57
+	protected $_dt_frmt;
58
+
59
+
60
+
61
+	/**
62
+	 * time format
63
+	 * pattern or format for displaying time
64
+	 *
65
+	 * @var string $_tm_frmt
66
+	 */
67
+	protected $_tm_frmt;
68
+
69
+
70
+
71
+	/**
72
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
73
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
74
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected $_cached_properties = array();
80
+
81
+	/**
82
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
83
+	 * single
84
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
+	 * all others have an array)
87
+	 *
88
+	 * @var array
89
+	 */
90
+	protected $_model_relations = array();
91
+
92
+	/**
93
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_fields = array();
99
+
100
+	/**
101
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
102
+	 * For example, we might create model objects intended to only be used for the duration
103
+	 * of this request and to be thrown away, and if they were accidentally saved
104
+	 * it would be a bug.
105
+	 */
106
+	protected $_allow_persist = true;
107
+
108
+
109
+
110
+	/**
111
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
112
+	 * play nice
113
+	 *
114
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
115
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
116
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
117
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
118
+	 *                                                         corresponding db model or not.
119
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
120
+	 *                                                         be in when instantiating a EE_Base_Class object.
121
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
122
+	 *                                                         value is the date_format and second value is the time
123
+	 *                                                         format.
124
+	 * @throws EE_Error
125
+	 */
126
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
127
+	{
128
+		$className = get_class($this);
129
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
+		$model = $this->get_model();
131
+		$model_fields = $model->field_settings(false);
132
+		// ensure $fieldValues is an array
133
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
134
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
135
+		// verify client code has not passed any invalid field names
136
+		foreach ($fieldValues as $field_name => $field_value) {
137
+			if ( ! isset($model_fields[$field_name])) {
138
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
139
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
140
+			}
141
+		}
142
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
143
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
144
+		if ( ! empty($date_formats) && is_array($date_formats)) {
145
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
146
+		} else {
147
+			//set default formats for date and time
148
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
149
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
150
+		}
151
+		//if db model is instantiating
152
+		if ($bydb) {
153
+			//client code has indicated these field values are from the database
154
+			foreach ($model_fields as $fieldName => $field) {
155
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
156
+			}
157
+		} else {
158
+			//we're constructing a brand
159
+			//new instance of the model object. Generally, this means we'll need to do more field validation
160
+			foreach ($model_fields as $fieldName => $field) {
161
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
162
+			}
163
+		}
164
+		//remember what values were passed to this constructor
165
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
166
+		//remember in entity mapper
167
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
168
+			$model->add_to_entity_map($this);
169
+		}
170
+		//setup all the relations
171
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
172
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
173
+				$this->_model_relations[$relation_name] = null;
174
+			} else {
175
+				$this->_model_relations[$relation_name] = array();
176
+			}
177
+		}
178
+		/**
179
+		 * Action done at the end of each model object construction
180
+		 *
181
+		 * @param EE_Base_Class $this the model object just created
182
+		 */
183
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
190
+	 *
191
+	 * @return boolean
192
+	 */
193
+	public function allow_persist()
194
+	{
195
+		return $this->_allow_persist;
196
+	}
197
+
198
+
199
+
200
+	/**
201
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
202
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
203
+	 * you got new information that somehow made you change your mind.
204
+	 *
205
+	 * @param boolean $allow_persist
206
+	 * @return boolean
207
+	 */
208
+	public function set_allow_persist($allow_persist)
209
+	{
210
+		return $this->_allow_persist = $allow_persist;
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * Gets the field's original value when this object was constructed during this request.
217
+	 * This can be helpful when determining if a model object has changed or not
218
+	 *
219
+	 * @param string $field_name
220
+	 * @return mixed|null
221
+	 * @throws \EE_Error
222
+	 */
223
+	public function get_original($field_name)
224
+	{
225
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
226
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
227
+		) {
228
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
229
+		} else {
230
+			return null;
231
+		}
232
+	}
233
+
234
+
235
+
236
+	/**
237
+	 * @param EE_Base_Class $obj
238
+	 * @return string
239
+	 */
240
+	public function get_class($obj)
241
+	{
242
+		return get_class($obj);
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * Overrides parent because parent expects old models.
249
+	 * This also doesn't do any validation, and won't work for serialized arrays
250
+	 *
251
+	 * @param    string $field_name
252
+	 * @param    mixed  $field_value
253
+	 * @param bool      $use_default
254
+	 * @throws \EE_Error
255
+	 */
256
+	public function set($field_name, $field_value, $use_default = false)
257
+	{
258
+		$field_obj = $this->get_model()->field_settings_for($field_name);
259
+		if ($field_obj instanceof EE_Model_Field_Base) {
260
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
261
+			if ($field_obj instanceof EE_Datetime_Field) {
262
+				$field_obj->set_timezone($this->_timezone);
263
+				$field_obj->set_date_format($this->_dt_frmt);
264
+				$field_obj->set_time_format($this->_tm_frmt);
265
+			}
266
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
267
+			//should the value be null?
268
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
269
+				$this->_fields[$field_name] = $field_obj->get_default_value();
270
+				/**
271
+				 * To save having to refactor all the models, if a default value is used for a
272
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
273
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
274
+				 * object.
275
+				 *
276
+				 * @since 4.6.10+
277
+				 */
278
+				if (
279
+					$field_obj instanceof EE_Datetime_Field
280
+					&& $this->_fields[$field_name] !== null
281
+					&& ! $this->_fields[$field_name] instanceof DateTime
282
+				) {
283
+					empty($this->_fields[$field_name])
284
+						? $this->set($field_name, time())
285
+						: $this->set($field_name, $this->_fields[$field_name]);
286
+				}
287
+			} else {
288
+				$this->_fields[$field_name] = $holder_of_value;
289
+			}
290
+			//if we're not in the constructor...
291
+			//now check if what we set was a primary key
292
+			if (
293
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
294
+				$this->_props_n_values_provided_in_constructor
295
+				&& $field_value
296
+				&& $field_name === self::_get_primary_key_name(get_class($this))
297
+			) {
298
+				//if so, we want all this object's fields to be filled either with
299
+				//what we've explicitly set on this model
300
+				//or what we have in the db
301
+				// echo "setting primary key!";
302
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
303
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
304
+				foreach ($fields_on_model as $field_obj) {
305
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
306
+						 && $field_obj->get_name() !== $field_name
307
+					) {
308
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
309
+					}
310
+				}
311
+				//oh this model object has an ID? well make sure its in the entity mapper
312
+				$this->get_model()->add_to_entity_map($this);
313
+			}
314
+			//let's unset any cache for this field_name from the $_cached_properties property.
315
+			$this->_clear_cached_property($field_name);
316
+		} else {
317
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
318
+				"event_espresso"), $field_name));
319
+		}
320
+	}
321
+
322
+
323
+
324
+	/**
325
+	 * This sets the field value on the db column if it exists for the given $column_name or
326
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
327
+	 *
328
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
329
+	 * @param string $field_name  Must be the exact column name.
330
+	 * @param mixed  $field_value The value to set.
331
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
332
+	 * @throws \EE_Error
333
+	 */
334
+	public function set_field_or_extra_meta($field_name, $field_value)
335
+	{
336
+		if ($this->get_model()->has_field($field_name)) {
337
+			$this->set($field_name, $field_value);
338
+			return true;
339
+		} else {
340
+			//ensure this object is saved first so that extra meta can be properly related.
341
+			$this->save();
342
+			return $this->update_extra_meta($field_name, $field_value);
343
+		}
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * This retrieves the value of the db column set on this class or if that's not present
350
+	 * it will attempt to retrieve from extra_meta if found.
351
+	 * Example Usage:
352
+	 * Via EE_Message child class:
353
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
354
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
355
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
356
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
357
+	 * value for those extra fields dynamically via the EE_message object.
358
+	 *
359
+	 * @param  string $field_name expecting the fully qualified field name.
360
+	 * @return mixed|null  value for the field if found.  null if not found.
361
+	 * @throws \EE_Error
362
+	 */
363
+	public function get_field_or_extra_meta($field_name)
364
+	{
365
+		if ($this->get_model()->has_field($field_name)) {
366
+			$column_value = $this->get($field_name);
367
+		} else {
368
+			//This isn't a column in the main table, let's see if it is in the extra meta.
369
+			$column_value = $this->get_extra_meta($field_name, true, null);
370
+		}
371
+		return $column_value;
372
+	}
373
+
374
+
375
+
376
+	/**
377
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
378
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
379
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
380
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
381
+	 *
382
+	 * @access public
383
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
384
+	 * @return void
385
+	 * @throws \EE_Error
386
+	 */
387
+	public function set_timezone($timezone = '')
388
+	{
389
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
390
+		//make sure we clear all cached properties because they won't be relevant now
391
+		$this->_clear_cached_properties();
392
+		//make sure we update field settings and the date for all EE_Datetime_Fields
393
+		$model_fields = $this->get_model()->field_settings(false);
394
+		foreach ($model_fields as $field_name => $field_obj) {
395
+			if ($field_obj instanceof EE_Datetime_Field) {
396
+				$field_obj->set_timezone($this->_timezone);
397
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
398
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
399
+				}
400
+			}
401
+		}
402
+	}
403
+
404
+
405
+
406
+	/**
407
+	 * This just returns whatever is set for the current timezone.
408
+	 *
409
+	 * @access public
410
+	 * @return string timezone string
411
+	 */
412
+	public function get_timezone()
413
+	{
414
+		return $this->_timezone;
415
+	}
416
+
417
+
418
+
419
+	/**
420
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
421
+	 * internally instead of wp set date format options
422
+	 *
423
+	 * @since 4.6
424
+	 * @param string $format should be a format recognizable by PHP date() functions.
425
+	 */
426
+	public function set_date_format($format)
427
+	{
428
+		$this->_dt_frmt = $format;
429
+		//clear cached_properties because they won't be relevant now.
430
+		$this->_clear_cached_properties();
431
+	}
432
+
433
+
434
+
435
+	/**
436
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
437
+	 * class internally instead of wp set time format options.
438
+	 *
439
+	 * @since 4.6
440
+	 * @param string $format should be a format recognizable by PHP date() functions.
441
+	 */
442
+	public function set_time_format($format)
443
+	{
444
+		$this->_tm_frmt = $format;
445
+		//clear cached_properties because they won't be relevant now.
446
+		$this->_clear_cached_properties();
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * This returns the current internal set format for the date and time formats.
453
+	 *
454
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
455
+	 *                             where the first value is the date format and the second value is the time format.
456
+	 * @return mixed string|array
457
+	 */
458
+	public function get_format($full = true)
459
+	{
460
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
461
+	}
462
+
463
+
464
+
465
+	/**
466
+	 * cache
467
+	 * stores the passed model object on the current model object.
468
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
469
+	 *
470
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
471
+	 *                                       'Registration' associated with this model object
472
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
473
+	 *                                       that could be a payment or a registration)
474
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
475
+	 *                                       items which will be stored in an array on this object
476
+	 * @throws EE_Error
477
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
478
+	 *                  related thing, no array)
479
+	 */
480
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
481
+	{
482
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
483
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
484
+			return false;
485
+		}
486
+		// also get "how" the object is related, or throw an error
487
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
488
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
489
+				$relationName, get_class($this)));
490
+		}
491
+		// how many things are related ?
492
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
493
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
494
+			// so for these model objects just set it to be cached
495
+			$this->_model_relations[$relationName] = $object_to_cache;
496
+			$return = true;
497
+		} else {
498
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
499
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
500
+			if ( ! is_array($this->_model_relations[$relationName])) {
501
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
502
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
503
+					? array($this->_model_relations[$relationName]) : array();
504
+			}
505
+			// first check for a cache_id which is normally empty
506
+			if ( ! empty($cache_id)) {
507
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
508
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
509
+				$return = $cache_id;
510
+			} elseif ($object_to_cache->ID()) {
511
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
512
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
513
+				$return = $object_to_cache->ID();
514
+			} else {
515
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
516
+				$this->_model_relations[$relationName][] = $object_to_cache;
517
+				// move the internal pointer to the end of the array
518
+				end($this->_model_relations[$relationName]);
519
+				// and grab the key so that we can return it
520
+				$return = key($this->_model_relations[$relationName]);
521
+			}
522
+		}
523
+		return $return;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * For adding an item to the cached_properties property.
530
+	 *
531
+	 * @access protected
532
+	 * @param string      $fieldname the property item the corresponding value is for.
533
+	 * @param mixed       $value     The value we are caching.
534
+	 * @param string|null $cache_type
535
+	 * @return void
536
+	 * @throws \EE_Error
537
+	 */
538
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
539
+	{
540
+		//first make sure this property exists
541
+		$this->get_model()->field_settings_for($fieldname);
542
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
543
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
544
+	}
545
+
546
+
547
+
548
+	/**
549
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
550
+	 * This also SETS the cache if we return the actual property!
551
+	 *
552
+	 * @param string $fieldname        the name of the property we're trying to retrieve
553
+	 * @param bool   $pretty
554
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
555
+	 *                                 (in cases where the same property may be used for different outputs
556
+	 *                                 - i.e. datetime, money etc.)
557
+	 *                                 It can also accept certain pre-defined "schema" strings
558
+	 *                                 to define how to output the property.
559
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
560
+	 * @return mixed                   whatever the value for the property is we're retrieving
561
+	 * @throws \EE_Error
562
+	 */
563
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
564
+	{
565
+		//verify the field exists
566
+		$this->get_model()->field_settings_for($fieldname);
567
+		$cache_type = $pretty ? 'pretty' : 'standard';
568
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
569
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
570
+			return $this->_cached_properties[$fieldname][$cache_type];
571
+		}
572
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
573
+		if ($field_obj instanceof EE_Model_Field_Base) {
574
+			// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
575
+			if ($field_obj instanceof EE_Datetime_Field) {
576
+				$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
577
+			}
578
+			if ( ! isset($this->_fields[$fieldname])) {
579
+				$this->_fields[$fieldname] = null;
580
+			}
581
+			$value = $pretty
582
+				? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
583
+				: $field_obj->prepare_for_get($this->_fields[$fieldname]);
584
+			$this->_set_cached_property($fieldname, $value, $cache_type);
585
+			return $value;
586
+		}
587
+		return null;
588
+	}
589
+
590
+
591
+
592
+	/**
593
+	 * set timezone, formats, and output for EE_Datetime_Field objects
594
+	 *
595
+	 * @param \EE_Datetime_Field $datetime_field
596
+	 * @param bool               $pretty
597
+	 * @param null $date_or_time
598
+	 * @return void
599
+	 * @throws \EE_Error
600
+	 */
601
+	protected function _prepare_datetime_field(
602
+		EE_Datetime_Field $datetime_field,
603
+		$pretty = false,
604
+		$date_or_time = null
605
+	) {
606
+		$datetime_field->set_timezone($this->_timezone);
607
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
608
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
609
+		//set the output returned
610
+		switch ($date_or_time) {
611
+			case 'D' :
612
+				$datetime_field->set_date_time_output('date');
613
+				break;
614
+			case 'T' :
615
+				$datetime_field->set_date_time_output('time');
616
+				break;
617
+			default :
618
+				$datetime_field->set_date_time_output();
619
+		}
620
+	}
621
+
622
+
623
+
624
+	/**
625
+	 * This just takes care of clearing out the cached_properties
626
+	 *
627
+	 * @return void
628
+	 */
629
+	protected function _clear_cached_properties()
630
+	{
631
+		$this->_cached_properties = array();
632
+	}
633
+
634
+
635
+
636
+	/**
637
+	 * This just clears out ONE property if it exists in the cache
638
+	 *
639
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
640
+	 * @return void
641
+	 */
642
+	protected function _clear_cached_property($property_name)
643
+	{
644
+		if (isset($this->_cached_properties[$property_name])) {
645
+			unset($this->_cached_properties[$property_name]);
646
+		}
647
+	}
648
+
649
+
650
+
651
+	/**
652
+	 * Ensures that this related thing is a model object.
653
+	 *
654
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
655
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
656
+	 * @return EE_Base_Class
657
+	 * @throws \EE_Error
658
+	 */
659
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
660
+	{
661
+		$other_model_instance = self::_get_model_instance_with_name(
662
+			self::_get_model_classname($model_name),
663
+			$this->_timezone
664
+		);
665
+		return $other_model_instance->ensure_is_obj($object_or_id);
666
+	}
667
+
668
+
669
+
670
+	/**
671
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
672
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
673
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
674
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
675
+	 *
676
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
677
+	 *                                                     Eg 'Registration'
678
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
679
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
680
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
681
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
682
+	 *                                                     this is HasMany or HABTM.
683
+	 * @throws EE_Error
684
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
685
+	 *                       relation from all
686
+	 */
687
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
688
+	{
689
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
690
+		$index_in_cache = '';
691
+		if ( ! $relationship_to_model) {
692
+			throw new EE_Error(
693
+				sprintf(
694
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
695
+					$relationName,
696
+					get_class($this)
697
+				)
698
+			);
699
+		}
700
+		if ($clear_all) {
701
+			$obj_removed = true;
702
+			$this->_model_relations[$relationName] = null;
703
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
704
+			$obj_removed = $this->_model_relations[$relationName];
705
+			$this->_model_relations[$relationName] = null;
706
+		} else {
707
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
708
+				&& $object_to_remove_or_index_into_array->ID()
709
+			) {
710
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
711
+				if (is_array($this->_model_relations[$relationName])
712
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
713
+				) {
714
+					$index_found_at = null;
715
+					//find this object in the array even though it has a different key
716
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
717
+						if (
718
+							$obj instanceof EE_Base_Class
719
+							&& (
720
+								$obj == $object_to_remove_or_index_into_array
721
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
722
+							)
723
+						) {
724
+							$index_found_at = $index;
725
+							break;
726
+						}
727
+					}
728
+					if ($index_found_at) {
729
+						$index_in_cache = $index_found_at;
730
+					} else {
731
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
732
+						//if it wasn't in it to begin with. So we're done
733
+						return $object_to_remove_or_index_into_array;
734
+					}
735
+				}
736
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
737
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
738
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
739
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
740
+						$index_in_cache = $index;
741
+					}
742
+				}
743
+			} else {
744
+				$index_in_cache = $object_to_remove_or_index_into_array;
745
+			}
746
+			//supposedly we've found it. But it could just be that the client code
747
+			//provided a bad index/object
748
+			if (
749
+			isset(
750
+				$this->_model_relations[$relationName],
751
+				$this->_model_relations[$relationName][$index_in_cache]
752
+			)
753
+			) {
754
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
755
+				unset($this->_model_relations[$relationName][$index_in_cache]);
756
+			} else {
757
+				//that thing was never cached anyways.
758
+				$obj_removed = null;
759
+			}
760
+		}
761
+		return $obj_removed;
762
+	}
763
+
764
+
765
+
766
+	/**
767
+	 * update_cache_after_object_save
768
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
769
+	 * obtained after being saved to the db
770
+	 *
771
+	 * @param string         $relationName       - the type of object that is cached
772
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
773
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
774
+	 * @return boolean TRUE on success, FALSE on fail
775
+	 * @throws \EE_Error
776
+	 */
777
+	public function update_cache_after_object_save(
778
+		$relationName,
779
+		EE_Base_Class $newly_saved_object,
780
+		$current_cache_id = ''
781
+	) {
782
+		// verify that incoming object is of the correct type
783
+		$obj_class = 'EE_' . $relationName;
784
+		if ($newly_saved_object instanceof $obj_class) {
785
+			/* @type EE_Base_Class $newly_saved_object */
786
+			// now get the type of relation
787
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
788
+			// if this is a 1:1 relationship
789
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
790
+				// then just replace the cached object with the newly saved object
791
+				$this->_model_relations[$relationName] = $newly_saved_object;
792
+				return true;
793
+				// or if it's some kind of sordid feral polyamorous relationship...
794
+			} elseif (is_array($this->_model_relations[$relationName])
795
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
796
+			) {
797
+				// then remove the current cached item
798
+				unset($this->_model_relations[$relationName][$current_cache_id]);
799
+				// and cache the newly saved object using it's new ID
800
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
801
+				return true;
802
+			}
803
+		}
804
+		return false;
805
+	}
806
+
807
+
808
+
809
+	/**
810
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
811
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
812
+	 *
813
+	 * @param string $relationName
814
+	 * @return EE_Base_Class
815
+	 */
816
+	public function get_one_from_cache($relationName)
817
+	{
818
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
819
+			: null;
820
+		if (is_array($cached_array_or_object)) {
821
+			return array_shift($cached_array_or_object);
822
+		} else {
823
+			return $cached_array_or_object;
824
+		}
825
+	}
826
+
827
+
828
+
829
+	/**
830
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
831
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
832
+	 *
833
+	 * @param string $relationName
834
+	 * @throws \EE_Error
835
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
836
+	 */
837
+	public function get_all_from_cache($relationName)
838
+	{
839
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
840
+		// if the result is not an array, but exists, make it an array
841
+		$objects = is_array($objects) ? $objects : array($objects);
842
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
843
+		//basically, if this model object was stored in the session, and these cached model objects
844
+		//already have IDs, let's make sure they're in their model's entity mapper
845
+		//otherwise we will have duplicates next time we call
846
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
847
+		$model = EE_Registry::instance()->load_model($relationName);
848
+		foreach ($objects as $model_object) {
849
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
850
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
851
+				if ($model_object->ID()) {
852
+					$model->add_to_entity_map($model_object);
853
+				}
854
+			} else {
855
+				throw new EE_Error(
856
+					sprintf(
857
+						__(
858
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
859
+							'event_espresso'
860
+						),
861
+						$relationName,
862
+						gettype($model_object)
863
+					)
864
+				);
865
+			}
866
+		}
867
+		return $objects;
868
+	}
869
+
870
+
871
+
872
+	/**
873
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
874
+	 * matching the given query conditions.
875
+	 *
876
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
877
+	 * @param int   $limit              How many objects to return.
878
+	 * @param array $query_params       Any additional conditions on the query.
879
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
880
+	 *                                  you can indicate just the columns you want returned
881
+	 * @return array|EE_Base_Class[]
882
+	 * @throws \EE_Error
883
+	 */
884
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
885
+	{
886
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
887
+			? $this->get_model()->get_primary_key_field()->get_name()
888
+			: $field_to_order_by;
889
+		$current_value = ! empty($field) ? $this->get($field) : null;
890
+		if (empty($field) || empty($current_value)) {
891
+			return array();
892
+		}
893
+		return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
894
+	}
895
+
896
+
897
+
898
+	/**
899
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
900
+	 * matching the given query conditions.
901
+	 *
902
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
903
+	 * @param int   $limit              How many objects to return.
904
+	 * @param array $query_params       Any additional conditions on the query.
905
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
906
+	 *                                  you can indicate just the columns you want returned
907
+	 * @return array|EE_Base_Class[]
908
+	 * @throws \EE_Error
909
+	 */
910
+	public function previous_x(
911
+		$field_to_order_by = null,
912
+		$limit = 1,
913
+		$query_params = array(),
914
+		$columns_to_select = null
915
+	) {
916
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
917
+			? $this->get_model()->get_primary_key_field()->get_name()
918
+			: $field_to_order_by;
919
+		$current_value = ! empty($field) ? $this->get($field) : null;
920
+		if (empty($field) || empty($current_value)) {
921
+			return array();
922
+		}
923
+		return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
924
+	}
925
+
926
+
927
+
928
+	/**
929
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
930
+	 * matching the given query conditions.
931
+	 *
932
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
933
+	 * @param array $query_params       Any additional conditions on the query.
934
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
935
+	 *                                  you can indicate just the columns you want returned
936
+	 * @return array|EE_Base_Class
937
+	 * @throws \EE_Error
938
+	 */
939
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
940
+	{
941
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
942
+			? $this->get_model()->get_primary_key_field()->get_name()
943
+			: $field_to_order_by;
944
+		$current_value = ! empty($field) ? $this->get($field) : null;
945
+		if (empty($field) || empty($current_value)) {
946
+			return array();
947
+		}
948
+		return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
949
+	}
950
+
951
+
952
+
953
+	/**
954
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
955
+	 * matching the given query conditions.
956
+	 *
957
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
958
+	 * @param array $query_params       Any additional conditions on the query.
959
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
960
+	 *                                  you can indicate just the column you want returned
961
+	 * @return array|EE_Base_Class
962
+	 * @throws \EE_Error
963
+	 */
964
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
965
+	{
966
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
967
+			? $this->get_model()->get_primary_key_field()->get_name()
968
+			: $field_to_order_by;
969
+		$current_value = ! empty($field) ? $this->get($field) : null;
970
+		if (empty($field) || empty($current_value)) {
971
+			return array();
972
+		}
973
+		return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
974
+	}
975
+
976
+
977
+
978
+	/**
979
+	 * Overrides parent because parent expects old models.
980
+	 * This also doesn't do any validation, and won't work for serialized arrays
981
+	 *
982
+	 * @param string $field_name
983
+	 * @param mixed  $field_value_from_db
984
+	 * @throws \EE_Error
985
+	 */
986
+	public function set_from_db($field_name, $field_value_from_db)
987
+	{
988
+		$field_obj = $this->get_model()->field_settings_for($field_name);
989
+		if ($field_obj instanceof EE_Model_Field_Base) {
990
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
991
+			//eg, a CPT model object could have an entry in the posts table, but no
992
+			//entry in the meta table. Meaning that all its columns in the meta table
993
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
994
+			if ($field_value_from_db === null) {
995
+				if ($field_obj->is_nullable()) {
996
+					//if the field allows nulls, then let it be null
997
+					$field_value = null;
998
+				} else {
999
+					$field_value = $field_obj->get_default_value();
1000
+				}
1001
+			} else {
1002
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1003
+			}
1004
+			$this->_fields[$field_name] = $field_value;
1005
+			$this->_clear_cached_property($field_name);
1006
+		}
1007
+	}
1008
+
1009
+
1010
+
1011
+	/**
1012
+	 * verifies that the specified field is of the correct type
1013
+	 *
1014
+	 * @param string $field_name
1015
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1016
+	 *                                (in cases where the same property may be used for different outputs
1017
+	 *                                - i.e. datetime, money etc.)
1018
+	 * @return mixed
1019
+	 * @throws \EE_Error
1020
+	 */
1021
+	public function get($field_name, $extra_cache_ref = null)
1022
+	{
1023
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1030
+	 *
1031
+	 * @param  string $field_name A valid fieldname
1032
+	 * @return mixed              Whatever the raw value stored on the property is.
1033
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1034
+	 */
1035
+	public function get_raw($field_name)
1036
+	{
1037
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1038
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1039
+			? $this->_fields[$field_name]->format('U')
1040
+			: $this->_fields[$field_name];
1041
+	}
1042
+
1043
+
1044
+
1045
+	/**
1046
+	 * This is used to return the internal DateTime object used for a field that is a
1047
+	 * EE_Datetime_Field.
1048
+	 *
1049
+	 * @param string $field_name               The field name retrieving the DateTime object.
1050
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1051
+	 * @throws \EE_Error
1052
+	 *                                         an error is set and false returned.  If the field IS an
1053
+	 *                                         EE_Datetime_Field and but the field value is null, then
1054
+	 *                                         just null is returned (because that indicates that likely
1055
+	 *                                         this field is nullable).
1056
+	 */
1057
+	public function get_DateTime_object($field_name)
1058
+	{
1059
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1060
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1061
+			EE_Error::add_error(
1062
+				sprintf(
1063
+					__(
1064
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1065
+						'event_espresso'
1066
+					),
1067
+					$field_name
1068
+				),
1069
+				__FILE__,
1070
+				__FUNCTION__,
1071
+				__LINE__
1072
+			);
1073
+			return false;
1074
+		}
1075
+		return $this->_fields[$field_name];
1076
+	}
1077
+
1078
+
1079
+
1080
+	/**
1081
+	 * To be used in template to immediately echo out the value, and format it for output.
1082
+	 * Eg, should call stripslashes and whatnot before echoing
1083
+	 *
1084
+	 * @param string $field_name      the name of the field as it appears in the DB
1085
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1086
+	 *                                (in cases where the same property may be used for different outputs
1087
+	 *                                - i.e. datetime, money etc.)
1088
+	 * @return void
1089
+	 * @throws \EE_Error
1090
+	 */
1091
+	public function e($field_name, $extra_cache_ref = null)
1092
+	{
1093
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1100
+	 * can be easily used as the value of form input.
1101
+	 *
1102
+	 * @param string $field_name
1103
+	 * @return void
1104
+	 * @throws \EE_Error
1105
+	 */
1106
+	public function f($field_name)
1107
+	{
1108
+		$this->e($field_name, 'form_input');
1109
+	}
1110
+
1111
+
1112
+
1113
+	/**
1114
+	 * @param string $field_name
1115
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1116
+	 *                                (in cases where the same property may be used for different outputs
1117
+	 *                                - i.e. datetime, money etc.)
1118
+	 * @return mixed
1119
+	 * @throws \EE_Error
1120
+	 */
1121
+	public function get_pretty($field_name, $extra_cache_ref = null)
1122
+	{
1123
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1124
+	}
1125
+
1126
+
1127
+
1128
+	/**
1129
+	 * This simply returns the datetime for the given field name
1130
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1131
+	 * (and the equivalent e_date, e_time, e_datetime).
1132
+	 *
1133
+	 * @access   protected
1134
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1135
+	 * @param string   $dt_frmt      valid datetime format used for date
1136
+	 *                               (if '' then we just use the default on the field,
1137
+	 *                               if NULL we use the last-used format)
1138
+	 * @param string   $tm_frmt      Same as above except this is for time format
1139
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1140
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1141
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1142
+	 *                               if field is not a valid dtt field, or void if echoing
1143
+	 * @throws \EE_Error
1144
+	 */
1145
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1146
+	{
1147
+		// clear cached property
1148
+		$this->_clear_cached_property($field_name);
1149
+		//reset format properties because they are used in get()
1150
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1151
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1152
+		if ($echo) {
1153
+			$this->e($field_name, $date_or_time);
1154
+			return '';
1155
+		}
1156
+		return $this->get($field_name, $date_or_time);
1157
+	}
1158
+
1159
+
1160
+
1161
+	/**
1162
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1163
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1164
+	 * other echoes the pretty value for dtt)
1165
+	 *
1166
+	 * @param  string $field_name name of model object datetime field holding the value
1167
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1168
+	 * @return string            datetime value formatted
1169
+	 * @throws \EE_Error
1170
+	 */
1171
+	public function get_date($field_name, $format = '')
1172
+	{
1173
+		return $this->_get_datetime($field_name, $format, null, 'D');
1174
+	}
1175
+
1176
+
1177
+
1178
+	/**
1179
+	 * @param      $field_name
1180
+	 * @param string $format
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	public function e_date($field_name, $format = '')
1184
+	{
1185
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1186
+	}
1187
+
1188
+
1189
+
1190
+	/**
1191
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1192
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1193
+	 * other echoes the pretty value for dtt)
1194
+	 *
1195
+	 * @param  string $field_name name of model object datetime field holding the value
1196
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1197
+	 * @return string             datetime value formatted
1198
+	 * @throws \EE_Error
1199
+	 */
1200
+	public function get_time($field_name, $format = '')
1201
+	{
1202
+		return $this->_get_datetime($field_name, null, $format, 'T');
1203
+	}
1204
+
1205
+
1206
+
1207
+	/**
1208
+	 * @param      $field_name
1209
+	 * @param string $format
1210
+	 * @throws \EE_Error
1211
+	 */
1212
+	public function e_time($field_name, $format = '')
1213
+	{
1214
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1215
+	}
1216
+
1217
+
1218
+
1219
+	/**
1220
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1221
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1222
+	 * other echoes the pretty value for dtt)
1223
+	 *
1224
+	 * @param  string $field_name name of model object datetime field holding the value
1225
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1226
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1227
+	 * @return string             datetime value formatted
1228
+	 * @throws \EE_Error
1229
+	 */
1230
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1231
+	{
1232
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1233
+	}
1234
+
1235
+
1236
+
1237
+	/**
1238
+	 * @param string $field_name
1239
+	 * @param string $dt_frmt
1240
+	 * @param string $tm_frmt
1241
+	 * @throws \EE_Error
1242
+	 */
1243
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1244
+	{
1245
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1246
+	}
1247
+
1248
+
1249
+
1250
+	/**
1251
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1252
+	 *
1253
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1254
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1255
+	 *                           on the object will be used.
1256
+	 * @return string Date and time string in set locale or false if no field exists for the given
1257
+	 * @throws \EE_Error
1258
+	 *                           field name.
1259
+	 */
1260
+	public function get_i18n_datetime($field_name, $format = '')
1261
+	{
1262
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1263
+		return date_i18n(
1264
+			$format,
1265
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1266
+		);
1267
+	}
1268
+
1269
+
1270
+
1271
+	/**
1272
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1273
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1274
+	 * thrown.
1275
+	 *
1276
+	 * @param  string $field_name The field name being checked
1277
+	 * @throws EE_Error
1278
+	 * @return EE_Datetime_Field
1279
+	 */
1280
+	protected function _get_dtt_field_settings($field_name)
1281
+	{
1282
+		$field = $this->get_model()->field_settings_for($field_name);
1283
+		//check if field is dtt
1284
+		if ($field instanceof EE_Datetime_Field) {
1285
+			return $field;
1286
+		} else {
1287
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1288
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1289
+		}
1290
+	}
1291
+
1292
+
1293
+
1294
+
1295
+	/**
1296
+	 * NOTE ABOUT BELOW:
1297
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1298
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1299
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1300
+	 * method and make sure you send the entire datetime value for setting.
1301
+	 */
1302
+	/**
1303
+	 * sets the time on a datetime property
1304
+	 *
1305
+	 * @access protected
1306
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1307
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1308
+	 * @throws \EE_Error
1309
+	 */
1310
+	protected function _set_time_for($time, $fieldname)
1311
+	{
1312
+		$this->_set_date_time('T', $time, $fieldname);
1313
+	}
1314
+
1315
+
1316
+
1317
+	/**
1318
+	 * sets the date on a datetime property
1319
+	 *
1320
+	 * @access protected
1321
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1322
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1323
+	 * @throws \EE_Error
1324
+	 */
1325
+	protected function _set_date_for($date, $fieldname)
1326
+	{
1327
+		$this->_set_date_time('D', $date, $fieldname);
1328
+	}
1329
+
1330
+
1331
+
1332
+	/**
1333
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1334
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1335
+	 *
1336
+	 * @access protected
1337
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1338
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1339
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1340
+	 *                                        EE_Datetime_Field property)
1341
+	 * @throws \EE_Error
1342
+	 */
1343
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1344
+	{
1345
+		$field = $this->_get_dtt_field_settings($fieldname);
1346
+		$field->set_timezone($this->_timezone);
1347
+		$field->set_date_format($this->_dt_frmt);
1348
+		$field->set_time_format($this->_tm_frmt);
1349
+		switch ($what) {
1350
+			case 'T' :
1351
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1352
+					$datetime_value,
1353
+					$this->_fields[$fieldname]
1354
+				);
1355
+				break;
1356
+			case 'D' :
1357
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1358
+					$datetime_value,
1359
+					$this->_fields[$fieldname]
1360
+				);
1361
+				break;
1362
+			case 'B' :
1363
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1364
+				break;
1365
+		}
1366
+		$this->_clear_cached_property($fieldname);
1367
+	}
1368
+
1369
+
1370
+
1371
+	/**
1372
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1373
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1374
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1375
+	 * that could lead to some unexpected results!
1376
+	 *
1377
+	 * @access public
1378
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time
1379
+	 *                                         value being returned.
1380
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1381
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1382
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1383
+	 * @param string               $append     You can include something to append on the timestamp
1384
+	 * @throws EE_Error
1385
+	 * @return string timestamp
1386
+	 */
1387
+	public function display_in_my_timezone(
1388
+		$field_name,
1389
+		$callback = 'get_datetime',
1390
+		$args = null,
1391
+		$prepend = '',
1392
+		$append = ''
1393
+	) {
1394
+		$timezone = EEH_DTT_Helper::get_timezone();
1395
+		if ($timezone === $this->_timezone) {
1396
+			return '';
1397
+		}
1398
+		$original_timezone = $this->_timezone;
1399
+		$this->set_timezone($timezone);
1400
+		$fn = (array)$field_name;
1401
+		$args = array_merge($fn, (array)$args);
1402
+		if ( ! method_exists($this, $callback)) {
1403
+			throw new EE_Error(
1404
+				sprintf(
1405
+					__(
1406
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1407
+						'event_espresso'
1408
+					),
1409
+					$callback
1410
+				)
1411
+			);
1412
+		}
1413
+		$args = (array)$args;
1414
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1415
+		$this->set_timezone($original_timezone);
1416
+		return $return;
1417
+	}
1418
+
1419
+
1420
+
1421
+	/**
1422
+	 * Deletes this model object.
1423
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1424
+	 * override
1425
+	 * `EE_Base_Class::_delete` NOT this class.
1426
+	 *
1427
+	 * @return boolean | int
1428
+	 * @throws \EE_Error
1429
+	 */
1430
+	public function delete()
1431
+	{
1432
+		/**
1433
+		 * Called just before the `EE_Base_Class::_delete` method call.
1434
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1435
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1436
+		 * soft deletes (trash) the object and does not permanently delete it.
1437
+		 *
1438
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1439
+		 */
1440
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1441
+		$result = $this->_delete();
1442
+		/**
1443
+		 * Called just after the `EE_Base_Class::_delete` method call.
1444
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1445
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1446
+		 * soft deletes (trash) the object and does not permanently delete it.
1447
+		 *
1448
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1449
+		 * @param boolean       $result
1450
+		 */
1451
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1452
+		return $result;
1453
+	}
1454
+
1455
+
1456
+
1457
+	/**
1458
+	 * Calls the specific delete method for the instantiated class.
1459
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1460
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1461
+	 * `EE_Base_Class::delete`
1462
+	 *
1463
+	 * @return bool|int
1464
+	 * @throws \EE_Error
1465
+	 */
1466
+	protected function _delete()
1467
+	{
1468
+		return $this->delete_permanently();
1469
+	}
1470
+
1471
+
1472
+
1473
+	/**
1474
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1475
+	 * error)
1476
+	 *
1477
+	 * @return bool | int
1478
+	 * @throws \EE_Error
1479
+	 */
1480
+	public function delete_permanently()
1481
+	{
1482
+		/**
1483
+		 * Called just before HARD deleting a model object
1484
+		 *
1485
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1486
+		 */
1487
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1488
+		$model = $this->get_model();
1489
+		$result = $model->delete_permanently_by_ID($this->ID());
1490
+		$this->refresh_cache_of_related_objects();
1491
+		/**
1492
+		 * Called just after HARD deleting a model object
1493
+		 *
1494
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1495
+		 * @param boolean       $result
1496
+		 */
1497
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1498
+		return $result;
1499
+	}
1500
+
1501
+
1502
+
1503
+	/**
1504
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1505
+	 * related model objects
1506
+	 *
1507
+	 * @throws \EE_Error
1508
+	 */
1509
+	public function refresh_cache_of_related_objects()
1510
+	{
1511
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1512
+			if ( ! empty($this->_model_relations[$relation_name])) {
1513
+				$related_objects = $this->_model_relations[$relation_name];
1514
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1515
+					//this relation only stores a single model object, not an array
1516
+					//but let's make it consistent
1517
+					$related_objects = array($related_objects);
1518
+				}
1519
+				foreach ($related_objects as $related_object) {
1520
+					//only refresh their cache if they're in memory
1521
+					if ($related_object instanceof EE_Base_Class) {
1522
+						$related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1523
+					}
1524
+				}
1525
+			}
1526
+		}
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1533
+	 * object just before saving.
1534
+	 *
1535
+	 * @access public
1536
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1537
+	 *                                 if provided during the save() method (often client code will change the fields'
1538
+	 *                                 values before calling save)
1539
+	 * @throws \EE_Error
1540
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1541
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1542
+	 */
1543
+	public function save($set_cols_n_values = array())
1544
+	{
1545
+		/**
1546
+		 * Filters the fields we're about to save on the model object
1547
+		 *
1548
+		 * @param array         $set_cols_n_values
1549
+		 * @param EE_Base_Class $model_object
1550
+		 */
1551
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1552
+			$this);
1553
+		//set attributes as provided in $set_cols_n_values
1554
+		foreach ($set_cols_n_values as $column => $value) {
1555
+			$this->set($column, $value);
1556
+		}
1557
+		/**
1558
+		 * Saving a model object.
1559
+		 * Before we perform a save, this action is fired.
1560
+		 *
1561
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1562
+		 */
1563
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1564
+		if ( ! $this->allow_persist()) {
1565
+			return 0;
1566
+		}
1567
+		//now get current attribute values
1568
+		$save_cols_n_values = $this->_fields;
1569
+		//if the object already has an ID, update it. Otherwise, insert it
1570
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1571
+		$old_assumption_concerning_value_preparation = $this->get_model()
1572
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1573
+		$this->get_model()->assume_values_already_prepared_by_model_object(true);
1574
+		//does this model have an autoincrement PK?
1575
+		if ($this->get_model()->has_primary_key_field()) {
1576
+			if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1577
+				//ok check if it's set, if so: update; if not, insert
1578
+				if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1579
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1580
+				} else {
1581
+					unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1582
+					$results = $this->get_model()->insert($save_cols_n_values);
1583
+					if ($results) {
1584
+						//if successful, set the primary key
1585
+						//but don't use the normal SET method, because it will check if
1586
+						//an item with the same ID exists in the mapper & db, then
1587
+						//will find it in the db (because we just added it) and THAT object
1588
+						//will get added to the mapper before we can add this one!
1589
+						//but if we just avoid using the SET method, all that headache can be avoided
1590
+						$pk_field_name = self::_get_primary_key_name(get_class($this));
1591
+						$this->_fields[$pk_field_name] = $results;
1592
+						$this->_clear_cached_property($pk_field_name);
1593
+						$this->get_model()->add_to_entity_map($this);
1594
+						$this->_update_cached_related_model_objs_fks();
1595
+					}
1596
+				}
1597
+			} else {//PK is NOT auto-increment
1598
+				//so check if one like it already exists in the db
1599
+				if ($this->get_model()->exists_by_ID($this->ID())) {
1600
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1601
+						throw new EE_Error(
1602
+							sprintf(
1603
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1604
+									'event_espresso'),
1605
+								get_class($this),
1606
+								get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1607
+								get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1608
+								'<br />'
1609
+							)
1610
+						);
1611
+					}
1612
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1613
+				} else {
1614
+					$results = $this->get_model()->insert($save_cols_n_values);
1615
+					$this->_update_cached_related_model_objs_fks();
1616
+				}
1617
+			}
1618
+		} else {//there is NO primary key
1619
+			$already_in_db = false;
1620
+			foreach ($this->get_model()->unique_indexes() as $index) {
1621
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1622
+				if ($this->get_model()->exists(array($uniqueness_where_params))) {
1623
+					$already_in_db = true;
1624
+				}
1625
+			}
1626
+			if ($already_in_db) {
1627
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1628
+					$this->get_model()->get_combined_primary_key_fields());
1629
+				$results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1630
+			} else {
1631
+				$results = $this->get_model()->insert($save_cols_n_values);
1632
+			}
1633
+		}
1634
+		//restore the old assumption about values being prepared by the model object
1635
+		$this->get_model()
1636
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1637
+		/**
1638
+		 * After saving the model object this action is called
1639
+		 *
1640
+		 * @param EE_Base_Class $model_object which was just saved
1641
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1642
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1643
+		 */
1644
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1645
+		return $results;
1646
+	}
1647
+
1648
+
1649
+
1650
+	/**
1651
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1652
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1653
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1654
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1655
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1656
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1657
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1658
+	 *
1659
+	 * @return void
1660
+	 * @throws \EE_Error
1661
+	 */
1662
+	protected function _update_cached_related_model_objs_fks()
1663
+	{
1664
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1665
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1666
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1667
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1668
+						$this->get_model()->get_this_model_name()
1669
+					);
1670
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1671
+					if ($related_model_obj_in_cache->ID()) {
1672
+						$related_model_obj_in_cache->save();
1673
+					}
1674
+				}
1675
+			}
1676
+		}
1677
+	}
1678
+
1679
+
1680
+
1681
+	/**
1682
+	 * Saves this model object and its NEW cached relations to the database.
1683
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1684
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1685
+	 * because otherwise, there's a potential for infinite looping of saving
1686
+	 * Saves the cached related model objects, and ensures the relation between them
1687
+	 * and this object and properly setup
1688
+	 *
1689
+	 * @return int ID of new model object on save; 0 on failure+
1690
+	 * @throws \EE_Error
1691
+	 */
1692
+	public function save_new_cached_related_model_objs()
1693
+	{
1694
+		//make sure this has been saved
1695
+		if ( ! $this->ID()) {
1696
+			$id = $this->save();
1697
+		} else {
1698
+			$id = $this->ID();
1699
+		}
1700
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1701
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1702
+			if ($this->_model_relations[$relationName]) {
1703
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1704
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1705
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1706
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1707
+					//but ONLY if it DOES NOT exist in the DB
1708
+					/* @var $related_model_obj EE_Base_Class */
1709
+					$related_model_obj = $this->_model_relations[$relationName];
1710
+					//					if( ! $related_model_obj->ID()){
1711
+					$this->_add_relation_to($related_model_obj, $relationName);
1712
+					$related_model_obj->save_new_cached_related_model_objs();
1713
+					//					}
1714
+				} else {
1715
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1716
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1717
+						//but ONLY if it DOES NOT exist in the DB
1718
+						//						if( ! $related_model_obj->ID()){
1719
+						$this->_add_relation_to($related_model_obj, $relationName);
1720
+						$related_model_obj->save_new_cached_related_model_objs();
1721
+						//						}
1722
+					}
1723
+				}
1724
+			}
1725
+		}
1726
+		return $id;
1727
+	}
1728
+
1729
+
1730
+
1731
+	/**
1732
+	 * for getting a model while instantiated.
1733
+	 *
1734
+	 * @return \EEM_Base | \EEM_CPT_Base
1735
+	 */
1736
+	public function get_model()
1737
+	{
1738
+		$modelName = self::_get_model_classname(get_class($this));
1739
+		return self::_get_model_instance_with_name($modelName, $this->_timezone);
1740
+	}
1741
+
1742
+
1743
+
1744
+	/**
1745
+	 * @param $props_n_values
1746
+	 * @param $classname
1747
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1748
+	 * @throws \EE_Error
1749
+	 */
1750
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1751
+	{
1752
+		//TODO: will not work for Term_Relationships because they have no PK!
1753
+		$primary_id_ref = self::_get_primary_key_name($classname);
1754
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1755
+			$id = $props_n_values[$primary_id_ref];
1756
+			return self::_get_model($classname)->get_from_entity_map($id);
1757
+		}
1758
+		return false;
1759
+	}
1760
+
1761
+
1762
+
1763
+	/**
1764
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1765
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1766
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1767
+	 * we return false.
1768
+	 *
1769
+	 * @param  array  $props_n_values   incoming array of properties and their values
1770
+	 * @param  string $classname        the classname of the child class
1771
+	 * @param null    $timezone
1772
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1773
+	 *                                  date_format and the second value is the time format
1774
+	 * @return mixed (EE_Base_Class|bool)
1775
+	 * @throws \EE_Error
1776
+	 */
1777
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1778
+	{
1779
+		$existing = null;
1780
+		if (self::_get_model($classname)->has_primary_key_field()) {
1781
+			$primary_id_ref = self::_get_primary_key_name($classname);
1782
+			if (array_key_exists($primary_id_ref, $props_n_values)
1783
+				&& ! empty($props_n_values[$primary_id_ref])
1784
+			) {
1785
+				$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1786
+					$props_n_values[$primary_id_ref]
1787
+				);
1788
+			}
1789
+		} elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1790
+			//no primary key on this model, but there's still a matching item in the DB
1791
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1792
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1793
+			);
1794
+		}
1795
+		if ($existing) {
1796
+			//set date formats if present before setting values
1797
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1798
+				$existing->set_date_format($date_formats[0]);
1799
+				$existing->set_time_format($date_formats[1]);
1800
+			} else {
1801
+				//set default formats for date and time
1802
+				$existing->set_date_format(get_option('date_format'));
1803
+				$existing->set_time_format(get_option('time_format'));
1804
+			}
1805
+			foreach ($props_n_values as $property => $field_value) {
1806
+				$existing->set($property, $field_value);
1807
+			}
1808
+			return $existing;
1809
+		} else {
1810
+			return false;
1811
+		}
1812
+	}
1813
+
1814
+
1815
+
1816
+	/**
1817
+	 * Gets the EEM_*_Model for this class
1818
+	 *
1819
+	 * @access public now, as this is more convenient
1820
+	 * @param      $classname
1821
+	 * @param null $timezone
1822
+	 * @throws EE_Error
1823
+	 * @return EEM_Base
1824
+	 */
1825
+	protected static function _get_model($classname, $timezone = null)
1826
+	{
1827
+		//find model for this class
1828
+		if ( ! $classname) {
1829
+			throw new EE_Error(
1830
+				sprintf(
1831
+					__(
1832
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1833
+						"event_espresso"
1834
+					),
1835
+					$classname
1836
+				)
1837
+			);
1838
+		}
1839
+		$modelName = self::_get_model_classname($classname);
1840
+		return self::_get_model_instance_with_name($modelName, $timezone);
1841
+	}
1842
+
1843
+
1844
+
1845
+	/**
1846
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1847
+	 *
1848
+	 * @param string $model_classname
1849
+	 * @param null   $timezone
1850
+	 * @return EEM_Base
1851
+	 */
1852
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1853
+	{
1854
+		$model_classname = str_replace('EEM_', '', $model_classname);
1855
+		$model = EE_Registry::instance()->load_model($model_classname);
1856
+		$model->set_timezone($timezone);
1857
+		return $model;
1858
+	}
1859
+
1860
+
1861
+
1862
+	/**
1863
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1864
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1865
+	 *
1866
+	 * @param null $model_name
1867
+	 * @return string like EEM_Attendee
1868
+	 */
1869
+	private static function _get_model_classname($model_name = null)
1870
+	{
1871
+		if (strpos($model_name, "EE_") === 0) {
1872
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1873
+		} else {
1874
+			$model_classname = "EEM_" . $model_name;
1875
+		}
1876
+		return $model_classname;
1877
+	}
1878
+
1879
+
1880
+
1881
+	/**
1882
+	 * returns the name of the primary key attribute
1883
+	 *
1884
+	 * @param null $classname
1885
+	 * @throws EE_Error
1886
+	 * @return string
1887
+	 */
1888
+	protected static function _get_primary_key_name($classname = null)
1889
+	{
1890
+		if ( ! $classname) {
1891
+			throw new EE_Error(
1892
+				sprintf(
1893
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1894
+					$classname
1895
+				)
1896
+			);
1897
+		}
1898
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
1899
+	}
1900
+
1901
+
1902
+
1903
+	/**
1904
+	 * Gets the value of the primary key.
1905
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
1906
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1907
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1908
+	 *
1909
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1910
+	 * @throws \EE_Error
1911
+	 */
1912
+	public function ID()
1913
+	{
1914
+		//now that we know the name of the variable, use a variable variable to get its value and return its
1915
+		if ($this->get_model()->has_primary_key_field()) {
1916
+			return $this->_fields[self::_get_primary_key_name(get_class($this))];
1917
+		} else {
1918
+			return $this->get_model()->get_index_primary_key_string($this->_fields);
1919
+		}
1920
+	}
1921
+
1922
+
1923
+
1924
+	/**
1925
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1926
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1927
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1928
+	 *
1929
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1930
+	 * @param string $relationName                     eg 'Events','Question',etc.
1931
+	 *                                                 an attendee to a group, you also want to specify which role they
1932
+	 *                                                 will have in that group. So you would use this parameter to
1933
+	 *                                                 specify array('role-column-name'=>'role-id')
1934
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1935
+	 *                                                 allow you to further constrict the relation to being added.
1936
+	 *                                                 However, keep in mind that the columns (keys) given must match a
1937
+	 *                                                 column on the JOIN table and currently only the HABTM models
1938
+	 *                                                 accept these additional conditions.  Also remember that if an
1939
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
1940
+	 *                                                 NEW row is created in the join table.
1941
+	 * @param null   $cache_id
1942
+	 * @throws EE_Error
1943
+	 * @return EE_Base_Class the object the relation was added to
1944
+	 */
1945
+	public function _add_relation_to(
1946
+		$otherObjectModelObjectOrID,
1947
+		$relationName,
1948
+		$extra_join_model_fields_n_values = array(),
1949
+		$cache_id = null
1950
+	) {
1951
+		//if this thing exists in the DB, save the relation to the DB
1952
+		if ($this->ID()) {
1953
+			$otherObject = $this->get_model()
1954
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
1955
+									$extra_join_model_fields_n_values);
1956
+			//clear cache so future get_many_related and get_first_related() return new results.
1957
+			$this->clear_cache($relationName, $otherObject, true);
1958
+			if ($otherObject instanceof EE_Base_Class) {
1959
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1960
+			}
1961
+		} else {
1962
+			//this thing doesn't exist in the DB,  so just cache it
1963
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1964
+				throw new EE_Error(sprintf(
1965
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
1966
+						'event_espresso'),
1967
+					$otherObjectModelObjectOrID,
1968
+					get_class($this)
1969
+				));
1970
+			} else {
1971
+				$otherObject = $otherObjectModelObjectOrID;
1972
+			}
1973
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1974
+		}
1975
+		if ($otherObject instanceof EE_Base_Class) {
1976
+			//fix the reciprocal relation too
1977
+			if ($otherObject->ID()) {
1978
+				//its saved so assumed relations exist in the DB, so we can just
1979
+				//clear the cache so future queries use the updated info in the DB
1980
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
1981
+			} else {
1982
+				//it's not saved, so it caches relations like this
1983
+				$otherObject->cache($this->get_model()->get_this_model_name(), $this);
1984
+			}
1985
+		}
1986
+		return $otherObject;
1987
+	}
1988
+
1989
+
1990
+
1991
+	/**
1992
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
1993
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
1994
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
1995
+	 * from the cache
1996
+	 *
1997
+	 * @param mixed  $otherObjectModelObjectOrID
1998
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
1999
+	 *                to the DB yet
2000
+	 * @param string $relationName
2001
+	 * @param array  $where_query
2002
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2003
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2004
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2005
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2006
+	 *                created in the join table.
2007
+	 * @return EE_Base_Class the relation was removed from
2008
+	 * @throws \EE_Error
2009
+	 */
2010
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2011
+	{
2012
+		if ($this->ID()) {
2013
+			//if this exists in the DB, save the relation change to the DB too
2014
+			$otherObject = $this->get_model()
2015
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2016
+									$where_query);
2017
+			$this->clear_cache($relationName, $otherObject);
2018
+		} else {
2019
+			//this doesn't exist in the DB, just remove it from the cache
2020
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2021
+		}
2022
+		if ($otherObject instanceof EE_Base_Class) {
2023
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2024
+		}
2025
+		return $otherObject;
2026
+	}
2027
+
2028
+
2029
+
2030
+	/**
2031
+	 * Removes ALL the related things for the $relationName.
2032
+	 *
2033
+	 * @param string $relationName
2034
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2035
+	 * @return EE_Base_Class
2036
+	 * @throws \EE_Error
2037
+	 */
2038
+	public function _remove_relations($relationName, $where_query_params = array())
2039
+	{
2040
+		if ($this->ID()) {
2041
+			//if this exists in the DB, save the relation change to the DB too
2042
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2043
+			$this->clear_cache($relationName, null, true);
2044
+		} else {
2045
+			//this doesn't exist in the DB, just remove it from the cache
2046
+			$otherObjects = $this->clear_cache($relationName, null, true);
2047
+		}
2048
+		if (is_array($otherObjects)) {
2049
+			foreach ($otherObjects as $otherObject) {
2050
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2051
+			}
2052
+		}
2053
+		return $otherObjects;
2054
+	}
2055
+
2056
+
2057
+
2058
+	/**
2059
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2060
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2061
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2062
+	 * because we want to get even deleted items etc.
2063
+	 *
2064
+	 * @param string $relationName key in the model's _model_relations array
2065
+	 * @param array  $query_params like EEM_Base::get_all
2066
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2067
+	 * @throws \EE_Error
2068
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2069
+	 *                             you want IDs
2070
+	 */
2071
+	public function get_many_related($relationName, $query_params = array())
2072
+	{
2073
+		if ($this->ID()) {
2074
+			//this exists in the DB, so get the related things from either the cache or the DB
2075
+			//if there are query parameters, forget about caching the related model objects.
2076
+			if ($query_params) {
2077
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2078
+			} else {
2079
+				//did we already cache the result of this query?
2080
+				$cached_results = $this->get_all_from_cache($relationName);
2081
+				if ( ! $cached_results) {
2082
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2083
+					//if no query parameters were passed, then we got all the related model objects
2084
+					//for that relation. We can cache them then.
2085
+					foreach ($related_model_objects as $related_model_object) {
2086
+						$this->cache($relationName, $related_model_object);
2087
+					}
2088
+				} else {
2089
+					$related_model_objects = $cached_results;
2090
+				}
2091
+			}
2092
+		} else {
2093
+			//this doesn't exist in the DB, so just get the related things from the cache
2094
+			$related_model_objects = $this->get_all_from_cache($relationName);
2095
+		}
2096
+		return $related_model_objects;
2097
+	}
2098
+
2099
+
2100
+
2101
+	/**
2102
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2103
+	 * unless otherwise specified in the $query_params
2104
+	 *
2105
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2106
+	 * @param array  $query_params   like EEM_Base::get_all's
2107
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2108
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2109
+	 *                               that by the setting $distinct to TRUE;
2110
+	 * @return int
2111
+	 */
2112
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2113
+	{
2114
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2115
+	}
2116
+
2117
+
2118
+
2119
+	/**
2120
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2121
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2122
+	 *
2123
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2124
+	 * @param array  $query_params  like EEM_Base::get_all's
2125
+	 * @param string $field_to_sum  name of field to count by.
2126
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2127
+	 *                              change it)
2128
+	 * @return int
2129
+	 */
2130
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2131
+	{
2132
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2133
+	}
2134
+
2135
+
2136
+
2137
+	/**
2138
+	 * Gets the first (ie, one) related model object of the specified type.
2139
+	 *
2140
+	 * @param string $relationName key in the model's _model_relations array
2141
+	 * @param array  $query_params like EEM_Base::get_all
2142
+	 * @return EE_Base_Class (not an array, a single object)
2143
+	 * @throws \EE_Error
2144
+	 */
2145
+	public function get_first_related($relationName, $query_params = array())
2146
+	{
2147
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2148
+			//if they've provided some query parameters, don't bother trying to cache the result
2149
+			//also make sure we're not caching the result of get_first_related
2150
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2151
+			if ($query_params
2152
+				|| ! $this->get_model()->related_settings_for($relationName)
2153
+					 instanceof
2154
+					 EE_Belongs_To_Relation
2155
+			) {
2156
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2157
+			} else {
2158
+				//first, check if we've already cached the result of this query
2159
+				$cached_result = $this->get_one_from_cache($relationName);
2160
+				if ( ! $cached_result) {
2161
+					$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2162
+					$this->cache($relationName, $related_model_object);
2163
+				} else {
2164
+					$related_model_object = $cached_result;
2165
+				}
2166
+			}
2167
+		} else {
2168
+			$related_model_object = null;
2169
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2170
+			if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2171
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2172
+			}
2173
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2174
+			if ( ! $related_model_object) {
2175
+				$related_model_object = $this->get_one_from_cache($relationName);
2176
+			}
2177
+		}
2178
+		return $related_model_object;
2179
+	}
2180
+
2181
+
2182
+
2183
+	/**
2184
+	 * Does a delete on all related objects of type $relationName and removes
2185
+	 * the current model object's relation to them. If they can't be deleted (because
2186
+	 * of blocking related model objects) does nothing. If the related model objects are
2187
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2188
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2189
+	 *
2190
+	 * @param string $relationName
2191
+	 * @param array  $query_params like EEM_Base::get_all's
2192
+	 * @return int how many deleted
2193
+	 * @throws \EE_Error
2194
+	 */
2195
+	public function delete_related($relationName, $query_params = array())
2196
+	{
2197
+		if ($this->ID()) {
2198
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2199
+		} else {
2200
+			$count = count($this->get_all_from_cache($relationName));
2201
+			$this->clear_cache($relationName, null, true);
2202
+		}
2203
+		return $count;
2204
+	}
2205
+
2206
+
2207
+
2208
+	/**
2209
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2210
+	 * the current model object's relation to them. If they can't be deleted (because
2211
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2212
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2213
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2214
+	 *
2215
+	 * @param string $relationName
2216
+	 * @param array  $query_params like EEM_Base::get_all's
2217
+	 * @return int how many deleted (including those soft deleted)
2218
+	 * @throws \EE_Error
2219
+	 */
2220
+	public function delete_related_permanently($relationName, $query_params = array())
2221
+	{
2222
+		if ($this->ID()) {
2223
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2224
+		} else {
2225
+			$count = count($this->get_all_from_cache($relationName));
2226
+		}
2227
+		$this->clear_cache($relationName, null, true);
2228
+		return $count;
2229
+	}
2230
+
2231
+
2232
+
2233
+	/**
2234
+	 * is_set
2235
+	 * Just a simple utility function children can use for checking if property exists
2236
+	 *
2237
+	 * @access  public
2238
+	 * @param  string $field_name property to check
2239
+	 * @return bool                              TRUE if existing,FALSE if not.
2240
+	 */
2241
+	public function is_set($field_name)
2242
+	{
2243
+		return isset($this->_fields[$field_name]);
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2250
+	 * EE_Error exception if they don't
2251
+	 *
2252
+	 * @param  mixed (string|array) $properties properties to check
2253
+	 * @throws EE_Error
2254
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2255
+	 */
2256
+	protected function _property_exists($properties)
2257
+	{
2258
+		foreach ((array)$properties as $property_name) {
2259
+			//first make sure this property exists
2260
+			if ( ! $this->_fields[$property_name]) {
2261
+				throw new EE_Error(
2262
+					sprintf(
2263
+						__(
2264
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2265
+							'event_espresso'
2266
+						),
2267
+						$property_name
2268
+					)
2269
+				);
2270
+			}
2271
+		}
2272
+		return true;
2273
+	}
2274
+
2275
+
2276
+
2277
+	/**
2278
+	 * This simply returns an array of model fields for this object
2279
+	 *
2280
+	 * @return array
2281
+	 * @throws \EE_Error
2282
+	 */
2283
+	public function model_field_array()
2284
+	{
2285
+		$fields = $this->get_model()->field_settings(false);
2286
+		$properties = array();
2287
+		//remove prepended underscore
2288
+		foreach ($fields as $field_name => $settings) {
2289
+			$properties[$field_name] = $this->get($field_name);
2290
+		}
2291
+		return $properties;
2292
+	}
2293
+
2294
+
2295
+
2296
+	/**
2297
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2298
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2299
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2300
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2301
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2302
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2303
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2304
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2305
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2306
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2307
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2308
+	 *        return $previousReturnValue.$returnString;
2309
+	 * }
2310
+	 * require('EE_Answer.class.php');
2311
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2312
+	 * echo $answer->my_callback('monkeys',100);
2313
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2314
+	 *
2315
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2316
+	 * @param array  $args       array of original arguments passed to the function
2317
+	 * @throws EE_Error
2318
+	 * @return mixed whatever the plugin which calls add_filter decides
2319
+	 */
2320
+	public function __call($methodName, $args)
2321
+	{
2322
+		$className = get_class($this);
2323
+		$tagName = "FHEE__{$className}__{$methodName}";
2324
+		if ( ! has_filter($tagName)) {
2325
+			throw new EE_Error(
2326
+				sprintf(
2327
+					__(
2328
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2329
+						"event_espresso"
2330
+					),
2331
+					$methodName,
2332
+					$className,
2333
+					$tagName
2334
+				)
2335
+			);
2336
+		}
2337
+		return apply_filters($tagName, null, $this, $args);
2338
+	}
2339
+
2340
+
2341
+
2342
+	/**
2343
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2344
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2345
+	 *
2346
+	 * @param string $meta_key
2347
+	 * @param string $meta_value
2348
+	 * @param string $previous_value
2349
+	 * @return int records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2350
+	 * @throws \EE_Error
2351
+	 * NOTE: if the values haven't changed, returns 0
2352
+	 */
2353
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2354
+	{
2355
+		$query_params = array(
2356
+			array(
2357
+				'EXM_key'  => $meta_key,
2358
+				'OBJ_ID'   => $this->ID(),
2359
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2360
+			),
2361
+		);
2362
+		if ($previous_value !== null) {
2363
+			$query_params[0]['EXM_value'] = $meta_value;
2364
+		}
2365
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2366
+		if ( ! $existing_rows_like_that) {
2367
+			return $this->add_extra_meta($meta_key, $meta_value);
2368
+		} else {
2369
+			foreach ($existing_rows_like_that as $existing_row) {
2370
+				$existing_row->save(array('EXM_value' => $meta_value));
2371
+			}
2372
+			return count($existing_rows_like_that);
2373
+		}
2374
+	}
2375
+
2376
+
2377
+
2378
+	/**
2379
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2380
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2381
+	 * extra meta row was entered, false if not
2382
+	 *
2383
+	 * @param string  $meta_key
2384
+	 * @param string  $meta_value
2385
+	 * @param boolean $unique
2386
+	 * @return boolean
2387
+	 * @throws \EE_Error
2388
+	 */
2389
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2390
+	{
2391
+		if ($unique) {
2392
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2393
+				array(
2394
+					array(
2395
+						'EXM_key'  => $meta_key,
2396
+						'OBJ_ID'   => $this->ID(),
2397
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2398
+					),
2399
+				)
2400
+			);
2401
+			if ($existing_extra_meta) {
2402
+				return false;
2403
+			}
2404
+		}
2405
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2406
+			array(
2407
+				'EXM_key'   => $meta_key,
2408
+				'EXM_value' => $meta_value,
2409
+				'OBJ_ID'    => $this->ID(),
2410
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2411
+			)
2412
+		);
2413
+		$new_extra_meta->save();
2414
+		return true;
2415
+	}
2416
+
2417
+
2418
+
2419
+	/**
2420
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2421
+	 * is specified, only deletes extra meta records with that value.
2422
+	 *
2423
+	 * @param string $meta_key
2424
+	 * @param string $meta_value
2425
+	 * @return int number of extra meta rows deleted
2426
+	 * @throws \EE_Error
2427
+	 */
2428
+	public function delete_extra_meta($meta_key, $meta_value = null)
2429
+	{
2430
+		$query_params = array(
2431
+			array(
2432
+				'EXM_key'  => $meta_key,
2433
+				'OBJ_ID'   => $this->ID(),
2434
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2435
+			),
2436
+		);
2437
+		if ($meta_value !== null) {
2438
+			$query_params[0]['EXM_value'] = $meta_value;
2439
+		}
2440
+		return EEM_Extra_Meta::instance()->delete($query_params);
2441
+	}
2442
+
2443
+
2444
+
2445
+	/**
2446
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2447
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2448
+	 * You can specify $default is case you haven't found the extra meta
2449
+	 *
2450
+	 * @param string  $meta_key
2451
+	 * @param boolean $single
2452
+	 * @param mixed   $default if we don't find anything, what should we return?
2453
+	 * @return mixed single value if $single; array if ! $single
2454
+	 * @throws \EE_Error
2455
+	 */
2456
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2457
+	{
2458
+		if ($single) {
2459
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2460
+			if ($result instanceof EE_Extra_Meta) {
2461
+				return $result->value();
2462
+			} else {
2463
+				return $default;
2464
+			}
2465
+		} else {
2466
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2467
+			if ($results) {
2468
+				$values = array();
2469
+				foreach ($results as $result) {
2470
+					if ($result instanceof EE_Extra_Meta) {
2471
+						$values[$result->ID()] = $result->value();
2472
+					}
2473
+				}
2474
+				return $values;
2475
+			} else {
2476
+				return $default;
2477
+			}
2478
+		}
2479
+	}
2480
+
2481
+
2482
+
2483
+	/**
2484
+	 * Returns a simple array of all the extra meta associated with this model object.
2485
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2486
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2487
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2488
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2489
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2490
+	 * finally the extra meta's value as each sub-value. (eg
2491
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2492
+	 *
2493
+	 * @param boolean $one_of_each_key
2494
+	 * @return array
2495
+	 * @throws \EE_Error
2496
+	 */
2497
+	public function all_extra_meta_array($one_of_each_key = true)
2498
+	{
2499
+		$return_array = array();
2500
+		if ($one_of_each_key) {
2501
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2502
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2503
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2504
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2505
+				}
2506
+			}
2507
+		} else {
2508
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2509
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2510
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2511
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2512
+						$return_array[$extra_meta_obj->key()] = array();
2513
+					}
2514
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2515
+				}
2516
+			}
2517
+		}
2518
+		return $return_array;
2519
+	}
2520
+
2521
+
2522
+
2523
+	/**
2524
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2525
+	 *
2526
+	 * @return string
2527
+	 * @throws \EE_Error
2528
+	 */
2529
+	public function name()
2530
+	{
2531
+		//find a field that's not a text field
2532
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2533
+		if ($field_we_can_use) {
2534
+			return $this->get($field_we_can_use->get_name());
2535
+		} else {
2536
+			$first_few_properties = $this->model_field_array();
2537
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2538
+			$name_parts = array();
2539
+			foreach ($first_few_properties as $name => $value) {
2540
+				$name_parts[] = "$name:$value";
2541
+			}
2542
+			return implode(",", $name_parts);
2543
+		}
2544
+	}
2545
+
2546
+
2547
+
2548
+	/**
2549
+	 * in_entity_map
2550
+	 * Checks if this model object has been proven to already be in the entity map
2551
+	 *
2552
+	 * @return boolean
2553
+	 * @throws \EE_Error
2554
+	 */
2555
+	public function in_entity_map()
2556
+	{
2557
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2558
+			//well, if we looked, did we find it in the entity map?
2559
+			return true;
2560
+		} else {
2561
+			return false;
2562
+		}
2563
+	}
2564
+
2565
+
2566
+
2567
+	/**
2568
+	 * refresh_from_db
2569
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2570
+	 *
2571
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2572
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2573
+	 */
2574
+	public function refresh_from_db()
2575
+	{
2576
+		if ($this->ID() && $this->in_entity_map()) {
2577
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2578
+		} else {
2579
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2580
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2581
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2582
+			//absolutely nothing in it for this ID
2583
+			if (WP_DEBUG) {
2584
+				throw new EE_Error(
2585
+					sprintf(
2586
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2587
+							'event_espresso'),
2588
+						$this->ID(),
2589
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2590
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2591
+					)
2592
+				);
2593
+			}
2594
+		}
2595
+	}
2596
+
2597
+
2598
+
2599
+	/**
2600
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2601
+	 * (probably a bad assumption they have made, oh well)
2602
+	 *
2603
+	 * @return string
2604
+	 */
2605
+	public function __toString()
2606
+	{
2607
+		try {
2608
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2609
+		} catch (Exception $e) {
2610
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2611
+			return '';
2612
+		}
2613
+	}
2614
+
2615
+
2616
+
2617
+	/**
2618
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2619
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2620
+	 * This means if we have made changes to those related model objects, and want to unserialize
2621
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2622
+	 * Instead, those related model objects should be directly serialized and stored.
2623
+	 * Eg, the following won't work:
2624
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2625
+	 * $att = $reg->attendee();
2626
+	 * $att->set( 'ATT_fname', 'Dirk' );
2627
+	 * update_option( 'my_option', serialize( $reg ) );
2628
+	 * //END REQUEST
2629
+	 * //START NEXT REQUEST
2630
+	 * $reg = get_option( 'my_option' );
2631
+	 * $reg->attendee()->save();
2632
+	 * And would need to be replace with:
2633
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2634
+	 * $att = $reg->attendee();
2635
+	 * $att->set( 'ATT_fname', 'Dirk' );
2636
+	 * update_option( 'my_option', serialize( $reg ) );
2637
+	 * //END REQUEST
2638
+	 * //START NEXT REQUEST
2639
+	 * $att = get_option( 'my_option' );
2640
+	 * $att->save();
2641
+	 *
2642
+	 * @return array
2643
+	 * @throws \EE_Error
2644
+	 */
2645
+	public function __sleep()
2646
+	{
2647
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2648
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2649
+				$classname = 'EE_' . $this->get_model()->get_this_model_name();
2650
+				if (
2651
+					$this->get_one_from_cache($relation_name) instanceof $classname
2652
+					&& $this->get_one_from_cache($relation_name)->ID()
2653
+				) {
2654
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2655
+				}
2656
+			}
2657
+		}
2658
+		$this->_props_n_values_provided_in_constructor = array();
2659
+		return array_keys(get_object_vars($this));
2660
+	}
2661
+
2662
+
2663
+
2664
+	/**
2665
+	 * restore _props_n_values_provided_in_constructor
2666
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2667
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2668
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2669
+	 */
2670
+	public function __wakeup()
2671
+	{
2672
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2673
+	}
2674 2674
 
2675 2675
 
2676 2676
 
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -145,8 +145,8 @@  discard block
 block discarded – undo
145 145
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
146 146
         } else {
147 147
             //set default formats for date and time
148
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
149
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
148
+            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
149
+            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
150 150
         }
151 151
         //if db model is instantiating
152 152
         if ($bydb) {
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
      */
458 458
     public function get_format($full = true)
459 459
     {
460
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
460
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
461 461
     }
462 462
 
463 463
 
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
         //verify the field exists
566 566
         $this->get_model()->field_settings_for($fieldname);
567 567
         $cache_type = $pretty ? 'pretty' : 'standard';
568
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
568
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
569 569
         if (isset($this->_cached_properties[$fieldname][$cache_type])) {
570 570
             return $this->_cached_properties[$fieldname][$cache_type];
571 571
         }
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
         $current_cache_id = ''
781 781
     ) {
782 782
         // verify that incoming object is of the correct type
783
-        $obj_class = 'EE_' . $relationName;
783
+        $obj_class = 'EE_'.$relationName;
784 784
         if ($newly_saved_object instanceof $obj_class) {
785 785
             /* @type EE_Base_Class $newly_saved_object */
786 786
             // now get the type of relation
@@ -1259,7 +1259,7 @@  discard block
 block discarded – undo
1259 1259
      */
1260 1260
     public function get_i18n_datetime($field_name, $format = '')
1261 1261
     {
1262
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1262
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1263 1263
         return date_i18n(
1264 1264
             $format,
1265 1265
             EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
@@ -1397,8 +1397,8 @@  discard block
 block discarded – undo
1397 1397
         }
1398 1398
         $original_timezone = $this->_timezone;
1399 1399
         $this->set_timezone($timezone);
1400
-        $fn = (array)$field_name;
1401
-        $args = array_merge($fn, (array)$args);
1400
+        $fn = (array) $field_name;
1401
+        $args = array_merge($fn, (array) $args);
1402 1402
         if ( ! method_exists($this, $callback)) {
1403 1403
             throw new EE_Error(
1404 1404
                 sprintf(
@@ -1410,8 +1410,8 @@  discard block
 block discarded – undo
1410 1410
                 )
1411 1411
             );
1412 1412
         }
1413
-        $args = (array)$args;
1414
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1413
+        $args = (array) $args;
1414
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1415 1415
         $this->set_timezone($original_timezone);
1416 1416
         return $return;
1417 1417
     }
@@ -1548,7 +1548,7 @@  discard block
 block discarded – undo
1548 1548
          * @param array         $set_cols_n_values
1549 1549
          * @param EE_Base_Class $model_object
1550 1550
          */
1551
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1551
+        $set_cols_n_values = (array) apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1552 1552
             $this);
1553 1553
         //set attributes as provided in $set_cols_n_values
1554 1554
         foreach ($set_cols_n_values as $column => $value) {
@@ -1603,8 +1603,8 @@  discard block
 block discarded – undo
1603 1603
                                 __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1604 1604
                                     'event_espresso'),
1605 1605
                                 get_class($this),
1606
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1607
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1606
+                                get_class($this->get_model()).'::instance()->add_to_entity_map()',
1607
+                                get_class($this->get_model()).'::instance()->get_one_by_ID()',
1608 1608
                                 '<br />'
1609 1609
                             )
1610 1610
                         );
@@ -1871,7 +1871,7 @@  discard block
 block discarded – undo
1871 1871
         if (strpos($model_name, "EE_") === 0) {
1872 1872
             $model_classname = str_replace("EE_", "EEM_", $model_name);
1873 1873
         } else {
1874
-            $model_classname = "EEM_" . $model_name;
1874
+            $model_classname = "EEM_".$model_name;
1875 1875
         }
1876 1876
         return $model_classname;
1877 1877
     }
@@ -2255,7 +2255,7 @@  discard block
 block discarded – undo
2255 2255
      */
2256 2256
     protected function _property_exists($properties)
2257 2257
     {
2258
-        foreach ((array)$properties as $property_name) {
2258
+        foreach ((array) $properties as $property_name) {
2259 2259
             //first make sure this property exists
2260 2260
             if ( ! $this->_fields[$property_name]) {
2261 2261
                 throw new EE_Error(
@@ -2586,8 +2586,8 @@  discard block
 block discarded – undo
2586 2586
                         __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2587 2587
                             'event_espresso'),
2588 2588
                         $this->ID(),
2589
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2590
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2589
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
2590
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
2591 2591
                     )
2592 2592
                 );
2593 2593
             }
@@ -2646,7 +2646,7 @@  discard block
 block discarded – undo
2646 2646
     {
2647 2647
         foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2648 2648
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
2649
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2649
+                $classname = 'EE_'.$this->get_model()->get_this_model_name();
2650 2650
                 if (
2651 2651
                     $this->get_one_from_cache($relation_name) instanceof $classname
2652 2652
                     && $this->get_one_from_cache($relation_name)->ID()
Please login to merge, or discard this patch.
modules/ticket_selector/DatetimeSelector.php 2 patches
Indentation   +169 added lines, -169 removed lines patch added patch discarded remove patch
@@ -16,175 +16,175 @@
 block discarded – undo
16 16
 class DatetimeSelector
17 17
 {
18 18
 
19
-    /**
20
-     * @var \EE_Event $event
21
-     */
22
-    protected $event;
23
-
24
-    /**
25
-     * @var \EE_Ticket[] $tickets
26
-     */
27
-    protected $tickets;
28
-
29
-    /**
30
-     * @var \EE_Datetime[] $datetimes
31
-     */
32
-    protected $datetimes;
33
-
34
-    /**
35
-     * @var \EE_Datetime[] $unique_dates
36
-     */
37
-    protected $unique_dates;
38
-
39
-    /**
40
-     * @var \EE_Ticket_Selector_Config $template_settings
41
-     */
42
-    protected $template_settings;
43
-
44
-    /**
45
-     * @var boolean $active
46
-     */
47
-    protected $active = false;
48
-
49
-
50
-
51
-    /**
52
-     * DatetimeSelector constructor.
53
-     *
54
-     * @param \EE_Event                  $event
55
-     * @param \EE_Ticket[]               $tickets
56
-     * @param \EE_Ticket_Selector_Config $template_settings
57
-     * @param string                     $date_format
58
-     * @param string                     $time_format
59
-     * @throws \EE_Error
60
-     */
61
-    public function __construct(
62
-        \EE_Event $event,
63
-        array $tickets,
64
-        \EE_Ticket_Selector_Config $template_settings,
65
-        $date_format = 'Y-m-d',
66
-        $time_format = 'g:i a'
67
-    ) {
68
-        $this->event = $event;
69
-        $this->tickets = $tickets;
70
-        $this->template_settings = $template_settings;
71
-        $this->datetimes = $this->getAllDatetimesForAllTicket($tickets);
72
-        $this->unique_dates = $this->getUniqueDatetimeOptions($date_format, $time_format);
73
-        $this->active = $this->template_settings->showDatetimeSelector($this->unique_dates);
74
-    }
75
-
76
-
77
-
78
-    /**
79
-     * @param \EE_Ticket[] $tickets
80
-     * @return array
81
-     * @throws \EE_Error
82
-     */
83
-    protected function getAllDatetimesForAllTicket($tickets = array())
84
-    {
85
-        $datetimes = array();
86
-        foreach ($tickets as $ticket) {
87
-            $datetimes = $this->getTicketDatetimes($ticket, $datetimes);
88
-        }
89
-        return $datetimes;
90
-    }
91
-
92
-
93
-
94
-    /**
95
-     * @param \EE_Ticket      $ticket
96
-     * @param  \EE_Datetime[] $datetimes
97
-     * @return \EE_Datetime[]
98
-     * @throws \EE_Error
99
-     */
100
-    protected function getTicketDatetimes(\EE_Ticket $ticket, $datetimes = array())
101
-    {
102
-        $ticket_datetimes = $ticket->datetimes(
103
-            array(
104
-                'order_by'                 => array(
105
-                    'DTT_order'     => 'ASC',
106
-                    'DTT_EVT_start' => 'ASC'
107
-                ),
108
-                'default_where_conditions' => 'none',
109
-            )
110
-        );
111
-        foreach ($ticket_datetimes as $ticket_datetime) {
112
-            if ( ! $ticket_datetime instanceof \EE_Datetime) {
113
-                continue;
114
-            }
115
-            $datetimes[ $ticket_datetime->ID() ] = $ticket_datetime;
116
-        }
117
-        return $datetimes;
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * @param \EE_Ticket                 $ticket
124
-     * @return string
125
-     * @throws \EE_Error
126
-     */
127
-    public function getTicketDatetimeClasses( \EE_Ticket $ticket ) {
128
-        if ( ! $this->active) {
129
-            return '';
130
-        }
131
-        $ticket_datetimes = $this->getTicketDatetimes($ticket);
132
-        $classes = '';
133
-        foreach ($this->datetimes as $datetime) {
134
-            if ( ! $datetime instanceof \EE_Datetime || ! in_array($datetime, $ticket_datetimes, true)) {
135
-                continue;
136
-            }
137
-            $classes .= ' ee-ticket-datetimes-' . $datetime->date_and_time_range('Y_m_d', 'H_i', '-', '_');
138
-        }
139
-        return $classes;
140
-    }
141
-
142
-
143
-
144
-    /**
145
-     * @param string $date_format
146
-     * @param string $time_format
147
-     * @return array
148
-     * @throws \EE_Error
149
-     */
150
-    public function getUniqueDatetimeOptions($date_format = 'Y-m-d', $time_format = 'g:i a') {
151
-        $datetime_options = array();
152
-        foreach ($this->datetimes as $datetime) {
153
-            if ( ! $datetime instanceof \EE_Datetime) {
154
-                continue;
155
-            }
156
-            $datetime_options[$datetime->date_and_time_range('Y_m_d', 'H_i', '-', '_')] =
157
-                $datetime->date_and_time_range($date_format, $time_format, ' - ');
158
-        }
159
-        return $datetime_options;
160
-    }
161
-
162
-
163
-
164
-    /**
165
-     * @return string
166
-     * @throws \EE_Error
167
-     */
168
-    public function getDatetimeSelector() {
169
-        if ( ! $this->active) {
170
-            return '';
171
-        }
172
-        $dropdown_selector = new \EE_Checkbox_Dropdown_Selector_Input(
173
-            $this->unique_dates,
174
-            array(
175
-                'html_id'               => 'datetime-selector-' . $this->event->ID(),
176
-                'html_name'             => 'datetime_selector_' . $this->event->ID(),
177
-                'html_class'            => 'datetime-selector',
178
-                'select_button_text'       => '<span class="dashicons dashicons-calendar-alt"></span> '
179
-                                            . esc_html__('Filter by Date', 'event_espresso'),
180
-                'other_html_attributes' => ' data-tkt_slctr_evt="' . $this->event->ID() . '"',
181
-            )
182
-        );
183
-        return \EEH_HTML::div(
184
-            $dropdown_selector->get_html_for_input(),
185
-            '', 'datetime_selector-dv'
186
-        );
187
-    }
19
+	/**
20
+	 * @var \EE_Event $event
21
+	 */
22
+	protected $event;
23
+
24
+	/**
25
+	 * @var \EE_Ticket[] $tickets
26
+	 */
27
+	protected $tickets;
28
+
29
+	/**
30
+	 * @var \EE_Datetime[] $datetimes
31
+	 */
32
+	protected $datetimes;
33
+
34
+	/**
35
+	 * @var \EE_Datetime[] $unique_dates
36
+	 */
37
+	protected $unique_dates;
38
+
39
+	/**
40
+	 * @var \EE_Ticket_Selector_Config $template_settings
41
+	 */
42
+	protected $template_settings;
43
+
44
+	/**
45
+	 * @var boolean $active
46
+	 */
47
+	protected $active = false;
48
+
49
+
50
+
51
+	/**
52
+	 * DatetimeSelector constructor.
53
+	 *
54
+	 * @param \EE_Event                  $event
55
+	 * @param \EE_Ticket[]               $tickets
56
+	 * @param \EE_Ticket_Selector_Config $template_settings
57
+	 * @param string                     $date_format
58
+	 * @param string                     $time_format
59
+	 * @throws \EE_Error
60
+	 */
61
+	public function __construct(
62
+		\EE_Event $event,
63
+		array $tickets,
64
+		\EE_Ticket_Selector_Config $template_settings,
65
+		$date_format = 'Y-m-d',
66
+		$time_format = 'g:i a'
67
+	) {
68
+		$this->event = $event;
69
+		$this->tickets = $tickets;
70
+		$this->template_settings = $template_settings;
71
+		$this->datetimes = $this->getAllDatetimesForAllTicket($tickets);
72
+		$this->unique_dates = $this->getUniqueDatetimeOptions($date_format, $time_format);
73
+		$this->active = $this->template_settings->showDatetimeSelector($this->unique_dates);
74
+	}
75
+
76
+
77
+
78
+	/**
79
+	 * @param \EE_Ticket[] $tickets
80
+	 * @return array
81
+	 * @throws \EE_Error
82
+	 */
83
+	protected function getAllDatetimesForAllTicket($tickets = array())
84
+	{
85
+		$datetimes = array();
86
+		foreach ($tickets as $ticket) {
87
+			$datetimes = $this->getTicketDatetimes($ticket, $datetimes);
88
+		}
89
+		return $datetimes;
90
+	}
91
+
92
+
93
+
94
+	/**
95
+	 * @param \EE_Ticket      $ticket
96
+	 * @param  \EE_Datetime[] $datetimes
97
+	 * @return \EE_Datetime[]
98
+	 * @throws \EE_Error
99
+	 */
100
+	protected function getTicketDatetimes(\EE_Ticket $ticket, $datetimes = array())
101
+	{
102
+		$ticket_datetimes = $ticket->datetimes(
103
+			array(
104
+				'order_by'                 => array(
105
+					'DTT_order'     => 'ASC',
106
+					'DTT_EVT_start' => 'ASC'
107
+				),
108
+				'default_where_conditions' => 'none',
109
+			)
110
+		);
111
+		foreach ($ticket_datetimes as $ticket_datetime) {
112
+			if ( ! $ticket_datetime instanceof \EE_Datetime) {
113
+				continue;
114
+			}
115
+			$datetimes[ $ticket_datetime->ID() ] = $ticket_datetime;
116
+		}
117
+		return $datetimes;
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * @param \EE_Ticket                 $ticket
124
+	 * @return string
125
+	 * @throws \EE_Error
126
+	 */
127
+	public function getTicketDatetimeClasses( \EE_Ticket $ticket ) {
128
+		if ( ! $this->active) {
129
+			return '';
130
+		}
131
+		$ticket_datetimes = $this->getTicketDatetimes($ticket);
132
+		$classes = '';
133
+		foreach ($this->datetimes as $datetime) {
134
+			if ( ! $datetime instanceof \EE_Datetime || ! in_array($datetime, $ticket_datetimes, true)) {
135
+				continue;
136
+			}
137
+			$classes .= ' ee-ticket-datetimes-' . $datetime->date_and_time_range('Y_m_d', 'H_i', '-', '_');
138
+		}
139
+		return $classes;
140
+	}
141
+
142
+
143
+
144
+	/**
145
+	 * @param string $date_format
146
+	 * @param string $time_format
147
+	 * @return array
148
+	 * @throws \EE_Error
149
+	 */
150
+	public function getUniqueDatetimeOptions($date_format = 'Y-m-d', $time_format = 'g:i a') {
151
+		$datetime_options = array();
152
+		foreach ($this->datetimes as $datetime) {
153
+			if ( ! $datetime instanceof \EE_Datetime) {
154
+				continue;
155
+			}
156
+			$datetime_options[$datetime->date_and_time_range('Y_m_d', 'H_i', '-', '_')] =
157
+				$datetime->date_and_time_range($date_format, $time_format, ' - ');
158
+		}
159
+		return $datetime_options;
160
+	}
161
+
162
+
163
+
164
+	/**
165
+	 * @return string
166
+	 * @throws \EE_Error
167
+	 */
168
+	public function getDatetimeSelector() {
169
+		if ( ! $this->active) {
170
+			return '';
171
+		}
172
+		$dropdown_selector = new \EE_Checkbox_Dropdown_Selector_Input(
173
+			$this->unique_dates,
174
+			array(
175
+				'html_id'               => 'datetime-selector-' . $this->event->ID(),
176
+				'html_name'             => 'datetime_selector_' . $this->event->ID(),
177
+				'html_class'            => 'datetime-selector',
178
+				'select_button_text'       => '<span class="dashicons dashicons-calendar-alt"></span> '
179
+											. esc_html__('Filter by Date', 'event_espresso'),
180
+				'other_html_attributes' => ' data-tkt_slctr_evt="' . $this->event->ID() . '"',
181
+			)
182
+		);
183
+		return \EEH_HTML::div(
184
+			$dropdown_selector->get_html_for_input(),
185
+			'', 'datetime_selector-dv'
186
+		);
187
+	}
188 188
 
189 189
 
190 190
 
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
             if ( ! $ticket_datetime instanceof \EE_Datetime) {
113 113
                 continue;
114 114
             }
115
-            $datetimes[ $ticket_datetime->ID() ] = $ticket_datetime;
115
+            $datetimes[$ticket_datetime->ID()] = $ticket_datetime;
116 116
         }
117 117
         return $datetimes;
118 118
     }
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
      * @return string
125 125
      * @throws \EE_Error
126 126
      */
127
-    public function getTicketDatetimeClasses( \EE_Ticket $ticket ) {
127
+    public function getTicketDatetimeClasses(\EE_Ticket $ticket) {
128 128
         if ( ! $this->active) {
129 129
             return '';
130 130
         }
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
             if ( ! $datetime instanceof \EE_Datetime || ! in_array($datetime, $ticket_datetimes, true)) {
135 135
                 continue;
136 136
             }
137
-            $classes .= ' ee-ticket-datetimes-' . $datetime->date_and_time_range('Y_m_d', 'H_i', '-', '_');
137
+            $classes .= ' ee-ticket-datetimes-'.$datetime->date_and_time_range('Y_m_d', 'H_i', '-', '_');
138 138
         }
139 139
         return $classes;
140 140
     }
@@ -172,12 +172,12 @@  discard block
 block discarded – undo
172 172
         $dropdown_selector = new \EE_Checkbox_Dropdown_Selector_Input(
173 173
             $this->unique_dates,
174 174
             array(
175
-                'html_id'               => 'datetime-selector-' . $this->event->ID(),
176
-                'html_name'             => 'datetime_selector_' . $this->event->ID(),
175
+                'html_id'               => 'datetime-selector-'.$this->event->ID(),
176
+                'html_name'             => 'datetime_selector_'.$this->event->ID(),
177 177
                 'html_class'            => 'datetime-selector',
178 178
                 'select_button_text'       => '<span class="dashicons dashicons-calendar-alt"></span> '
179 179
                                             . esc_html__('Filter by Date', 'event_espresso'),
180
-                'other_html_attributes' => ' data-tkt_slctr_evt="' . $this->event->ID() . '"',
180
+                'other_html_attributes' => ' data-tkt_slctr_evt="'.$this->event->ID().'"',
181 181
             )
182 182
         );
183 183
         return \EEH_HTML::div(
Please login to merge, or discard this patch.
modules/ticket_selector/TicketSelectorRow.php 2 patches
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -16,196 +16,196 @@
 block discarded – undo
16 16
 abstract class TicketSelectorRow
17 17
 {
18 18
 
19
-    /**
20
-     * @var \EE_Ticket $ticket
21
-     */
22
-    protected $ticket;
23
-
24
-    /**
25
-     * @var int $max_atndz
26
-     */
27
-    protected $max_atndz;
28
-
29
-    /**
30
-     * @var string $date_format
31
-     */
32
-    protected $date_format;
33
-
34
-    /**
35
-     * @var int $EVT_ID
36
-     */
37
-    protected $EVT_ID;
38
-
39
-    /**
40
-     * @var string $ticket_status_display
41
-     */
42
-    protected $ticket_status_display;
43
-
44
-
45
-
46
-    /**
47
-     * TicketDetails constructor.
48
-     *
49
-     * @param \EE_Ticket                 $ticket
50
-     * @param int                        $max_atndz
51
-     * @param string                     $date_format
52
-     */
53
-    public function __construct(
54
-        \EE_Ticket $ticket,
55
-        $max_atndz,
56
-        $date_format
57
-    ) {
58
-        $this->ticket = $ticket;
59
-        $this->max_atndz = $max_atndz;
60
-        $this->date_format = $date_format;
61
-        $this->EVT_ID = $this->ticket->get_event_ID();
62
-    }
63
-
64
-
65
-
66
-    /**
67
-     * @return string
68
-     */
69
-    public function getTicketStatusDisplay()
70
-    {
71
-        return $this->ticket_status_display;
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     * setTicketStatusDisplay
78
-     *
79
-     * @param string $tkt_status
80
-     * @param string $ticket_status
81
-     * @param int    $remaining
82
-     * @throws \EE_Error
83
-     */
84
-    protected function setTicketStatusDisplay($tkt_status, $ticket_status, $remaining) {
85
-        $this->ticket_status_display = '';
86
-        // now depending on the ticket and other circumstances...
87
-        if ($this->max_atndz === 0) {
88
-            // registration is CLOSED because admin set max attendees to ZERO
89
-            $this->ticket_status_display = $this->registrationClosed();
90
-        } else if ($tkt_status === \EE_Ticket::sold_out || $remaining === 0) {
91
-            // SOLD OUT - no tickets remaining
92
-            $this->ticket_status_display = $this->ticketsSoldOut();
93
-        } else if ($tkt_status === \EE_Ticket::expired || $tkt_status === \EE_Ticket::archived) {
94
-            // expired or archived ticket
95
-            $this->ticket_status_display = $ticket_status;
96
-        } else if ($tkt_status === \EE_Ticket::pending) {
97
-            // ticket not on sale yet
98
-            $this->ticket_status_display = $this->ticketsSalesPending();
99
-        } else if ($this->ticket->min() > $remaining) {
100
-            // min qty purchasable is less than tickets available
101
-            $this->ticket_status_display = $this->notEnoughTicketsAvailable();
102
-        }
103
-    }
104
-
105
-
106
-
107
-    /**
108
-     * registrationClosed
109
-     */
110
-    protected function registrationClosed()
111
-    {
112
-        return \EEH_HTML::span(
113
-            apply_filters(
114
-                'FHEE__ticket_selector_chart_template__ticket_closed_msg',
115
-                __('Closed', 'event_espresso')
116
-            ),
117
-            '', 'sold-out'
118
-        );
119
-    }
120
-
121
-
122
-
123
-    /**
124
-     * ticketsSoldOut
125
-     */
126
-    protected function ticketsSoldOut()
127
-    {
128
-        return \EEH_HTML::span(
129
-            apply_filters(
130
-                'FHEE__ticket_selector_chart_template__ticket_sold_out_msg',
131
-                __('Sold&nbsp;Out', 'event_espresso')
132
-            ),
133
-            '', 'sold-out'
134
-        );
135
-    }
136
-
137
-
138
-
139
-    /**
140
-     * ticketsSalesPending
141
-     *
142
-     * @throws \EE_Error
143
-     */
144
-    protected function ticketsSalesPending()
145
-    {
146
-        return \EEH_HTML::span(
147
-            \EEH_HTML::span(
148
-                apply_filters(
149
-                    'FHEE__ticket_selector_chart_template__ticket_goes_on_sale_msg',
150
-                    __('Goes&nbsp;On&nbsp;Sale', 'event_espresso')
151
-                ),
152
-                '', 'ticket-pending'
153
-            )
154
-            . \EEH_HTML::br()
155
-            . \EEH_HTML::span(
156
-                $this->ticket->get_i18n_datetime(
157
-                    'TKT_start_date',
158
-                    apply_filters(
159
-                        'FHEE__EED_Ticket_Selector__display_goes_on_sale__date_format',
160
-                        $this->date_format
161
-                    )
162
-                ),
163
-                '', 'small-text'
164
-            ),
165
-            '', 'ticket-pending-pg'
166
-        );
167
-    }
168
-
169
-
170
-
171
-    /**
172
-     * notEnoughTicketsAvailable
173
-     */
174
-    protected function notEnoughTicketsAvailable()
175
-    {
176
-        return \EEH_HTML::div(
177
-            \EEH_HTML::span(
178
-                apply_filters(
179
-                    'FHEE__ticket_selector_chart_template__ticket_not_available_msg',
180
-                    __('Not Available', 'event_espresso')
181
-                ),
182
-                '', 'archived-ticket small-text'
183
-            )
184
-            . \EEH_HTML::br(),
185
-            '', 'archived-ticket-pg'
186
-        );
187
-    }
188
-
189
-
190
-
191
-    /**
192
-     * getHiddenInputs
193
-     *
194
-     * @param string $anchor_id
195
-     * @param int    $row
196
-     * @param int    $max_atndz
197
-     * @return string
198
-     */
199
-    protected function getHiddenInputs($anchor_id, $row, $max_atndz)
200
-    {
201
-        $html = '<input type="hidden" name="noheader" value="true"/>';
202
-        $html .= '<input type="hidden" name="tkt-slctr-return-url-' . $this->EVT_ID . '"';
203
-        $html .= ' value="' . \EEH_URL::current_url() . $anchor_id . '"/>';
204
-        $html .= '<input type="hidden" name="tkt-slctr-rows-' . $this->EVT_ID . '" value="' . $row - 1 . '"/>';
205
-        $html .= '<input type="hidden" name="tkt-slctr-max-atndz-' . $this->EVT_ID . '" value="' . $max_atndz . '"/>';
206
-        $html .= '<input type="hidden" name="tkt-slctr-event-id" value="' . $this->EVT_ID . '"/>';
207
-        return $html;
208
-    }
19
+	/**
20
+	 * @var \EE_Ticket $ticket
21
+	 */
22
+	protected $ticket;
23
+
24
+	/**
25
+	 * @var int $max_atndz
26
+	 */
27
+	protected $max_atndz;
28
+
29
+	/**
30
+	 * @var string $date_format
31
+	 */
32
+	protected $date_format;
33
+
34
+	/**
35
+	 * @var int $EVT_ID
36
+	 */
37
+	protected $EVT_ID;
38
+
39
+	/**
40
+	 * @var string $ticket_status_display
41
+	 */
42
+	protected $ticket_status_display;
43
+
44
+
45
+
46
+	/**
47
+	 * TicketDetails constructor.
48
+	 *
49
+	 * @param \EE_Ticket                 $ticket
50
+	 * @param int                        $max_atndz
51
+	 * @param string                     $date_format
52
+	 */
53
+	public function __construct(
54
+		\EE_Ticket $ticket,
55
+		$max_atndz,
56
+		$date_format
57
+	) {
58
+		$this->ticket = $ticket;
59
+		$this->max_atndz = $max_atndz;
60
+		$this->date_format = $date_format;
61
+		$this->EVT_ID = $this->ticket->get_event_ID();
62
+	}
63
+
64
+
65
+
66
+	/**
67
+	 * @return string
68
+	 */
69
+	public function getTicketStatusDisplay()
70
+	{
71
+		return $this->ticket_status_display;
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 * setTicketStatusDisplay
78
+	 *
79
+	 * @param string $tkt_status
80
+	 * @param string $ticket_status
81
+	 * @param int    $remaining
82
+	 * @throws \EE_Error
83
+	 */
84
+	protected function setTicketStatusDisplay($tkt_status, $ticket_status, $remaining) {
85
+		$this->ticket_status_display = '';
86
+		// now depending on the ticket and other circumstances...
87
+		if ($this->max_atndz === 0) {
88
+			// registration is CLOSED because admin set max attendees to ZERO
89
+			$this->ticket_status_display = $this->registrationClosed();
90
+		} else if ($tkt_status === \EE_Ticket::sold_out || $remaining === 0) {
91
+			// SOLD OUT - no tickets remaining
92
+			$this->ticket_status_display = $this->ticketsSoldOut();
93
+		} else if ($tkt_status === \EE_Ticket::expired || $tkt_status === \EE_Ticket::archived) {
94
+			// expired or archived ticket
95
+			$this->ticket_status_display = $ticket_status;
96
+		} else if ($tkt_status === \EE_Ticket::pending) {
97
+			// ticket not on sale yet
98
+			$this->ticket_status_display = $this->ticketsSalesPending();
99
+		} else if ($this->ticket->min() > $remaining) {
100
+			// min qty purchasable is less than tickets available
101
+			$this->ticket_status_display = $this->notEnoughTicketsAvailable();
102
+		}
103
+	}
104
+
105
+
106
+
107
+	/**
108
+	 * registrationClosed
109
+	 */
110
+	protected function registrationClosed()
111
+	{
112
+		return \EEH_HTML::span(
113
+			apply_filters(
114
+				'FHEE__ticket_selector_chart_template__ticket_closed_msg',
115
+				__('Closed', 'event_espresso')
116
+			),
117
+			'', 'sold-out'
118
+		);
119
+	}
120
+
121
+
122
+
123
+	/**
124
+	 * ticketsSoldOut
125
+	 */
126
+	protected function ticketsSoldOut()
127
+	{
128
+		return \EEH_HTML::span(
129
+			apply_filters(
130
+				'FHEE__ticket_selector_chart_template__ticket_sold_out_msg',
131
+				__('Sold&nbsp;Out', 'event_espresso')
132
+			),
133
+			'', 'sold-out'
134
+		);
135
+	}
136
+
137
+
138
+
139
+	/**
140
+	 * ticketsSalesPending
141
+	 *
142
+	 * @throws \EE_Error
143
+	 */
144
+	protected function ticketsSalesPending()
145
+	{
146
+		return \EEH_HTML::span(
147
+			\EEH_HTML::span(
148
+				apply_filters(
149
+					'FHEE__ticket_selector_chart_template__ticket_goes_on_sale_msg',
150
+					__('Goes&nbsp;On&nbsp;Sale', 'event_espresso')
151
+				),
152
+				'', 'ticket-pending'
153
+			)
154
+			. \EEH_HTML::br()
155
+			. \EEH_HTML::span(
156
+				$this->ticket->get_i18n_datetime(
157
+					'TKT_start_date',
158
+					apply_filters(
159
+						'FHEE__EED_Ticket_Selector__display_goes_on_sale__date_format',
160
+						$this->date_format
161
+					)
162
+				),
163
+				'', 'small-text'
164
+			),
165
+			'', 'ticket-pending-pg'
166
+		);
167
+	}
168
+
169
+
170
+
171
+	/**
172
+	 * notEnoughTicketsAvailable
173
+	 */
174
+	protected function notEnoughTicketsAvailable()
175
+	{
176
+		return \EEH_HTML::div(
177
+			\EEH_HTML::span(
178
+				apply_filters(
179
+					'FHEE__ticket_selector_chart_template__ticket_not_available_msg',
180
+					__('Not Available', 'event_espresso')
181
+				),
182
+				'', 'archived-ticket small-text'
183
+			)
184
+			. \EEH_HTML::br(),
185
+			'', 'archived-ticket-pg'
186
+		);
187
+	}
188
+
189
+
190
+
191
+	/**
192
+	 * getHiddenInputs
193
+	 *
194
+	 * @param string $anchor_id
195
+	 * @param int    $row
196
+	 * @param int    $max_atndz
197
+	 * @return string
198
+	 */
199
+	protected function getHiddenInputs($anchor_id, $row, $max_atndz)
200
+	{
201
+		$html = '<input type="hidden" name="noheader" value="true"/>';
202
+		$html .= '<input type="hidden" name="tkt-slctr-return-url-' . $this->EVT_ID . '"';
203
+		$html .= ' value="' . \EEH_URL::current_url() . $anchor_id . '"/>';
204
+		$html .= '<input type="hidden" name="tkt-slctr-rows-' . $this->EVT_ID . '" value="' . $row - 1 . '"/>';
205
+		$html .= '<input type="hidden" name="tkt-slctr-max-atndz-' . $this->EVT_ID . '" value="' . $max_atndz . '"/>';
206
+		$html .= '<input type="hidden" name="tkt-slctr-event-id" value="' . $this->EVT_ID . '"/>';
207
+		return $html;
208
+	}
209 209
 
210 210
 
211 211
 
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -199,11 +199,11 @@
 block discarded – undo
199 199
     protected function getHiddenInputs($anchor_id, $row, $max_atndz)
200 200
     {
201 201
         $html = '<input type="hidden" name="noheader" value="true"/>';
202
-        $html .= '<input type="hidden" name="tkt-slctr-return-url-' . $this->EVT_ID . '"';
203
-        $html .= ' value="' . \EEH_URL::current_url() . $anchor_id . '"/>';
204
-        $html .= '<input type="hidden" name="tkt-slctr-rows-' . $this->EVT_ID . '" value="' . $row - 1 . '"/>';
205
-        $html .= '<input type="hidden" name="tkt-slctr-max-atndz-' . $this->EVT_ID . '" value="' . $max_atndz . '"/>';
206
-        $html .= '<input type="hidden" name="tkt-slctr-event-id" value="' . $this->EVT_ID . '"/>';
202
+        $html .= '<input type="hidden" name="tkt-slctr-return-url-'.$this->EVT_ID.'"';
203
+        $html .= ' value="'.\EEH_URL::current_url().$anchor_id.'"/>';
204
+        $html .= '<input type="hidden" name="tkt-slctr-rows-'.$this->EVT_ID.'" value="'.$row - 1.'"/>';
205
+        $html .= '<input type="hidden" name="tkt-slctr-max-atndz-'.$this->EVT_ID.'" value="'.$max_atndz.'"/>';
206
+        $html .= '<input type="hidden" name="tkt-slctr-event-id" value="'.$this->EVT_ID.'"/>';
207 207
         return $html;
208 208
     }
209 209
 
Please login to merge, or discard this patch.
modules/ticket_selector/templates/standard_ticket_selector.template.php 2 patches
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -28,12 +28,12 @@  discard block
 block discarded – undo
28 28
 			<tr>
29 29
 				<th scope="col" class="ee-ticket-selector-ticket-details-th">
30 30
 					<?php
31
-                    echo apply_filters(
32
-                        'FHEE__ticket_selector_chart_template__table_header_available_tickets',
33
-                        esc_html(''),
34
-                        $EVT_ID
35
-                    );
36
-                    ?>
31
+					echo apply_filters(
32
+						'FHEE__ticket_selector_chart_template__table_header_available_tickets',
33
+						esc_html(''),
34
+						$EVT_ID
35
+					);
36
+					?>
37 37
 				</th>
38 38
 				<?php if ( apply_filters( 'FHEE__ticket_selector_chart_template__display_ticket_price_details', TRUE ) ) { ?>
39 39
 				<th scope="col" class="ee-ticket-selector-ticket-price-th cntr">
@@ -47,28 +47,28 @@  discard block
 block discarded – undo
47 47
 						 * @param int $EVT_ID The Event ID
48 48
 						 */
49 49
 						echo apply_filters(
50
-                            'FHEE__ticket_selector_chart_template__table_header_price',
51
-                            esc_html__( 'Price', 'event_espresso' ),
52
-                            $EVT_ID
53
-                        );
50
+							'FHEE__ticket_selector_chart_template__table_header_price',
51
+							esc_html__( 'Price', 'event_espresso' ),
52
+							$EVT_ID
53
+						);
54 54
 					?>
55 55
 				</th>
56 56
 				<?php } ?>
57 57
 				<th scope="col" class="ee-ticket-selector-ticket-qty-th cntr">
58 58
 					<?php
59 59
 						/**
60
-						* Filters the text printed for the header of the quantity column in the ticket selector table
61
-						*
62
-						* @since 4.7.2
63
-						*
64
-						* @param string 'Qty' The translatable text to display in the table header for the Quantity of tickets
65
-						* @param int $EVT_ID The Event ID
66
-						*/
60
+						 * Filters the text printed for the header of the quantity column in the ticket selector table
61
+						 *
62
+						 * @since 4.7.2
63
+						 *
64
+						 * @param string 'Qty' The translatable text to display in the table header for the Quantity of tickets
65
+						 * @param int $EVT_ID The Event ID
66
+						 */
67 67
 						echo apply_filters(
68
-                            'FHEE__ticket_selector_chart_template__table_header_qty',
69
-                            esc_html__( 'Qty', 'event_espresso' ),
70
-                            $EVT_ID
71
-                        );
68
+							'FHEE__ticket_selector_chart_template__table_header_qty',
69
+							esc_html__( 'Qty', 'event_espresso' ),
70
+							$EVT_ID
71
+						);
72 72
 					?>
73 73
 				</th>
74 74
 			</tr>
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 if ( $max_atndz > 0 ) {
99 99
 	echo apply_filters(
100 100
 		'FHEE__ticket_selector_chart_template__maximum_tickets_purchased_footnote',
101
-        esc_html('')
101
+		esc_html('')
102 102
 	);
103 103
 }
104 104
 if ( ! apply_filters( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false ) ) {
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 ?>
21 21
 <div id="tkt-slctr-tbl-wrap-dv-<?php echo $EVT_ID; ?>" class="tkt-slctr-tbl-wrap-dv">
22 22
 
23
-	<?php do_action( 'AHEE__ticket_selector_chart__template__before_ticket_selector', $event ); ?>
23
+	<?php do_action('AHEE__ticket_selector_chart__template__before_ticket_selector', $event); ?>
24 24
 	<?php echo $datetime_selector; ?>
25 25
 
26 26
 	<table id="tkt-slctr-tbl-<?php echo $EVT_ID; ?>" class="tkt-slctr-tbl">
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
                     );
36 36
                     ?>
37 37
 				</th>
38
-				<?php if ( apply_filters( 'FHEE__ticket_selector_chart_template__display_ticket_price_details', TRUE ) ) { ?>
38
+				<?php if (apply_filters('FHEE__ticket_selector_chart_template__display_ticket_price_details', TRUE)) { ?>
39 39
 				<th scope="col" class="ee-ticket-selector-ticket-price-th cntr">
40 40
 					<?php
41 41
 						/**
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 						 */
49 49
 						echo apply_filters(
50 50
                             'FHEE__ticket_selector_chart_template__table_header_price',
51
-                            esc_html__( 'Price', 'event_espresso' ),
51
+                            esc_html__('Price', 'event_espresso'),
52 52
                             $EVT_ID
53 53
                         );
54 54
 					?>
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 						*/
67 67
 						echo apply_filters(
68 68
                             'FHEE__ticket_selector_chart_template__table_header_qty',
69
-                            esc_html__( 'Qty', 'event_espresso' ),
69
+                            esc_html__('Qty', 'event_espresso'),
70 70
                             $EVT_ID
71 71
                         );
72 72
 					?>
@@ -74,34 +74,34 @@  discard block
 block discarded – undo
74 74
 			</tr>
75 75
 		</thead>
76 76
 		<tbody>
77
-			<?php echo $ticket_row_html;?>
77
+			<?php echo $ticket_row_html; ?>
78 78
 		</tbody>
79 79
 	</table>
80 80
 	<?php
81
-	if ( $taxable_tickets && apply_filters( 'FHEE__ticket_selector_chart_template__display_ticket_price_details', true ) ) {
82
-		if ( $prices_displayed_including_taxes ) {
83
-			$ticket_price_includes_taxes = esc_html__( '* price includes taxes', 'event_espresso' );
81
+	if ($taxable_tickets && apply_filters('FHEE__ticket_selector_chart_template__display_ticket_price_details', true)) {
82
+		if ($prices_displayed_including_taxes) {
83
+			$ticket_price_includes_taxes = esc_html__('* price includes taxes', 'event_espresso');
84 84
 		} else {
85
-			$ticket_price_includes_taxes = esc_html__( '* price does not include taxes', 'event_espresso' );
85
+			$ticket_price_includes_taxes = esc_html__('* price does not include taxes', 'event_espresso');
86 86
 		}
87
-		echo '<p class="small-text lt-grey-text" style="text-align:right; margin: -1em 0 1em;">' . $ticket_price_includes_taxes . '</p>';
87
+		echo '<p class="small-text lt-grey-text" style="text-align:right; margin: -1em 0 1em;">'.$ticket_price_includes_taxes.'</p>';
88 88
 	}
89 89
 	?>
90 90
 
91 91
 	<input type="hidden" name="noheader" value="true" />
92
-	<input type="hidden" name="tkt-slctr-return-url-<?php echo $EVT_ID ?>" value="<?php echo EEH_URL::current_url() . $anchor_id; ?>" />
92
+	<input type="hidden" name="tkt-slctr-return-url-<?php echo $EVT_ID ?>" value="<?php echo EEH_URL::current_url().$anchor_id; ?>" />
93 93
 	<input type="hidden" name="tkt-slctr-rows-<?php echo $EVT_ID; ?>" value="<?php echo $row - 1; ?>" />
94 94
 	<input type="hidden" name="tkt-slctr-max-atndz-<?php echo $EVT_ID; ?>" value="<?php echo $max_atndz; ?>" />
95 95
 	<input type="hidden" name="tkt-slctr-event-id" value="<?php echo $EVT_ID; ?>" />
96 96
 
97 97
 <?php
98
-if ( $max_atndz > 0 ) {
98
+if ($max_atndz > 0) {
99 99
 	echo apply_filters(
100 100
 		'FHEE__ticket_selector_chart_template__maximum_tickets_purchased_footnote',
101 101
         esc_html('')
102 102
 	);
103 103
 }
104
-if ( ! apply_filters( 'FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false ) ) {
105
-	add_filter( 'FHEE__EE_Ticket_Selector__no_ticket_selector_submit', '__return_true' );
104
+if ( ! apply_filters('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', false)) {
105
+	add_filter('FHEE__EE_Ticket_Selector__no_ticket_selector_submit', '__return_true');
106 106
 }
107
-do_action( 'AHEE__ticket_selector_chart__template__after_ticket_selector', $EVT_ID, $event );
108 107
\ No newline at end of file
108
+do_action('AHEE__ticket_selector_chart__template__after_ticket_selector', $EVT_ID, $event);
109 109
\ No newline at end of file
Please login to merge, or discard this patch.