Completed
Branch BUG-10923-reg-form-question-cs... (bf89a7)
by
unknown
66:43 queued 55:42
created
core/libraries/messages/messenger/EE_Email_messenger.class.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
             'This messenger delivers messages via email using the built-in <code>wp_mail</code> function included with WordPress',
56 56
             'event_espresso'
57 57
         );
58
-        $this->label               = array(
58
+        $this->label = array(
59 59
             'singular' => esc_html__('email', 'event_espresso'),
60 60
             'plural'   => esc_html__('emails', 'event_espresso'),
61 61
         );
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
             $this->_body(),
420 420
             $this->_headers()
421 421
         );
422
-        if (! $success) {
422
+        if ( ! $success) {
423 423
             EE_Error::add_error(
424 424
                 sprintf(
425 425
                     esc_html__(
@@ -464,13 +464,13 @@  discard block
 block discarded – undo
464 464
         $from    = stripslashes_deep(html_entity_decode($this->_from, ENT_QUOTES, "UTF-8"));
465 465
         $headers = array(
466 466
             'MIME-Version: 1.0',
467
-            'From:' . $from,
468
-            'Reply-To:' . $from,
467
+            'From:'.$from,
468
+            'Reply-To:'.$from,
469 469
             'Content-Type:text/html; charset=utf-8',
470 470
         );
471 471
 
472
-        if (! empty($this->_cc)) {
473
-            $headers[] = 'cc: ' . $this->_cc;
472
+        if ( ! empty($this->_cc)) {
473
+            $headers[] = 'cc: '.$this->_cc;
474 474
         }
475 475
 
476 476
         //but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
                 )
581 581
             ),
582 582
         );
583
-        $body                 = $this->_get_main_template($preview);
583
+        $body = $this->_get_main_template($preview);
584 584
 
585 585
         /**
586 586
          * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
@@ -590,10 +590,10 @@  discard block
 block discarded – undo
590 590
          */
591 591
         if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
592 592
             //require CssToInlineStyles library and its dependencies via composer autoloader
593
-            require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
593
+            require_once EE_THIRD_PARTY.'cssinliner/vendor/autoload.php';
594 594
 
595 595
             //now if this isn't a preview, let's setup the body so it has inline styles
596
-            if (! $preview || ($preview && defined('DOING_AJAX'))) {
596
+            if ( ! $preview || ($preview && defined('DOING_AJAX'))) {
597 597
                 $style = file_get_contents(
598 598
                     $this->get_variation(
599 599
                         $this->_tmp_pack,
Please login to merge, or discard this patch.
Indentation   +639 added lines, -639 removed lines patch added patch discarded remove patch
@@ -8,643 +8,643 @@
 block discarded – undo
8 8
 class EE_Email_messenger extends EE_messenger
9 9
 {
10 10
 
11
-    /**
12
-     * To field for email
13
-     * @var string
14
-     */
15
-    protected $_to = '';
16
-
17
-
18
-    /**
19
-     * CC field for email.
20
-     * @var string
21
-     */
22
-    protected $_cc = '';
23
-
24
-    /**
25
-     * From field for email
26
-     * @var string
27
-     */
28
-    protected $_from = '';
29
-
30
-
31
-    /**
32
-     * Subject field for email
33
-     * @var string
34
-     */
35
-    protected $_subject = '';
36
-
37
-
38
-    /**
39
-     * Content field for email
40
-     * @var string
41
-     */
42
-    protected $_content = '';
43
-
44
-
45
-    /**
46
-     * constructor
47
-     *
48
-     * @access public
49
-     */
50
-    public function __construct()
51
-    {
52
-        //set name and description properties
53
-        $this->name                = 'email';
54
-        $this->description         = esc_html__(
55
-            'This messenger delivers messages via email using the built-in <code>wp_mail</code> function included with WordPress',
56
-            'event_espresso'
57
-        );
58
-        $this->label               = array(
59
-            'singular' => esc_html__('email', 'event_espresso'),
60
-            'plural'   => esc_html__('emails', 'event_espresso'),
61
-        );
62
-        $this->activate_on_install = true;
63
-
64
-        //we're using defaults so let's call parent constructor that will take care of setting up all the other
65
-        // properties
66
-        parent::__construct();
67
-    }
68
-
69
-
70
-    /**
71
-     * see abstract declaration in parent class for details.
72
-     */
73
-    protected function _set_admin_pages()
74
-    {
75
-        $this->admin_registered_pages = array(
76
-            'events_edit' => true,
77
-        );
78
-    }
79
-
80
-
81
-    /**
82
-     * see abstract declaration in parent class for details
83
-     */
84
-    protected function _set_valid_shortcodes()
85
-    {
86
-        //remember by leaving the other fields not set, those fields will inherit the valid shortcodes from the
87
-        // message type.
88
-        $this->_valid_shortcodes = array(
89
-            'to'   => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
90
-            'cc' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
91
-            'from' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
92
-        );
93
-    }
94
-
95
-
96
-    /**
97
-     * see abstract declaration in parent class for details
98
-     *
99
-     * @access protected
100
-     * @return void
101
-     */
102
-    protected function _set_validator_config()
103
-    {
104
-        $valid_shortcodes = $this->get_valid_shortcodes();
105
-
106
-        $this->_validator_config = array(
107
-            'to'            => array(
108
-                'shortcodes' => $valid_shortcodes['to'],
109
-                'type'       => 'email',
110
-            ),
111
-            'cc' => array(
112
-                'shortcodes' => $valid_shortcodes['to'],
113
-                'type' => 'email',
114
-            ),
115
-            'from'          => array(
116
-                'shortcodes' => $valid_shortcodes['from'],
117
-                'type'       => 'email',
118
-            ),
119
-            'subject'       => array(
120
-                'shortcodes' => array(
121
-                    'organization',
122
-                    'primary_registration_details',
123
-                    'event_author',
124
-                    'primary_registration_details',
125
-                    'recipient_details',
126
-                ),
127
-            ),
128
-            'content'       => array(
129
-                'shortcodes' => array(
130
-                    'event_list',
131
-                    'attendee_list',
132
-                    'ticket_list',
133
-                    'organization',
134
-                    'primary_registration_details',
135
-                    'primary_registration_list',
136
-                    'event_author',
137
-                    'recipient_details',
138
-                    'recipient_list',
139
-                    'transaction',
140
-                    'messenger',
141
-                ),
142
-            ),
143
-            'attendee_list' => array(
144
-                'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
145
-                'required'   => array('[ATTENDEE_LIST]'),
146
-            ),
147
-            'event_list'    => array(
148
-                'shortcodes' => array(
149
-                    'event',
150
-                    'attendee_list',
151
-                    'ticket_list',
152
-                    'venue',
153
-                    'datetime_list',
154
-                    'attendee',
155
-                    'primary_registration_details',
156
-                    'primary_registration_list',
157
-                    'event_author',
158
-                    'recipient_details',
159
-                    'recipient_list',
160
-                ),
161
-                'required'   => array('[EVENT_LIST]'),
162
-            ),
163
-            'ticket_list'   => array(
164
-                'shortcodes' => array(
165
-                    'event_list',
166
-                    'attendee_list',
167
-                    'ticket',
168
-                    'datetime_list',
169
-                    'primary_registration_details',
170
-                    'recipient_details',
171
-                ),
172
-                'required'   => array('[TICKET_LIST]'),
173
-            ),
174
-            'datetime_list' => array(
175
-                'shortcodes' => array('datetime'),
176
-                'required'   => array('[DATETIME_LIST]'),
177
-            ),
178
-        );
179
-    }
180
-
181
-
182
-    /**
183
-     * @see   parent EE_messenger class for docs
184
-     * @since 4.5.0
185
-     */
186
-    public function do_secondary_messenger_hooks($sending_messenger_name)
187
-    {
188
-        if ($sending_messenger_name = 'html') {
189
-            add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
190
-        }
191
-    }
192
-
193
-
194
-    public function add_email_css(
195
-        $variation_path,
196
-        $messenger,
197
-        $message_type,
198
-        $type,
199
-        $variation,
200
-        $file_extension,
201
-        $url,
202
-        EE_Messages_Template_Pack $template_pack
203
-    ) {
204
-        //prevent recursion on this callback.
205
-        remove_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10);
206
-        $variation = $this->get_variation($template_pack, $message_type, $url, 'main', $variation, false);
207
-
208
-        add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
209
-        return $variation;
210
-    }
211
-
212
-
213
-    /**
214
-     * See parent for details
215
-     *
216
-     * @access protected
217
-     * @return void
218
-     */
219
-    protected function _set_test_settings_fields()
220
-    {
221
-        $this->_test_settings_fields = array(
222
-            'to'      => array(
223
-                'input'      => 'text',
224
-                'label'      => esc_html__('Send a test email to', 'event_espresso'),
225
-                'type'       => 'email',
226
-                'required'   => true,
227
-                'validation' => true,
228
-                'css_class'  => 'large-text',
229
-                'format'     => '%s',
230
-                'default'    => get_bloginfo('admin_email'),
231
-            ),
232
-            'subject' => array(
233
-                'input'      => 'hidden',
234
-                'label'      => '',
235
-                'type'       => 'string',
236
-                'required'   => false,
237
-                'validation' => false,
238
-                'format'     => '%s',
239
-                'value'      => sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name')),
240
-                'default'    => '',
241
-                'css_class'  => '',
242
-            ),
243
-        );
244
-    }
245
-
246
-
247
-    /**
248
-     * _set_template_fields
249
-     * This sets up the fields that a messenger requires for the message to go out.
250
-     *
251
-     * @access  protected
252
-     * @return void
253
-     */
254
-    protected function _set_template_fields()
255
-    {
256
-        // any extra template fields that are NOT used by the messenger but will get used by a messenger field for
257
-        // shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field
258
-        // they relate to.  This is important for the Messages_admin to know what fields to display to the user.
259
-        //  Also, notice that the "values" are equal to the field type that messages admin will use to know what
260
-        // kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array
261
-        // indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be
262
-        // displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and
263
-        // will not be displayed/parsed.
264
-        $this->_template_fields = array(
265
-            'to'      => array(
266
-                'input'      => 'text',
267
-                'label'      => esc_html_x(
268
-                    'To',
269
-                    'Label for the "To" field for email addresses',
270
-                    'event_espresso'
271
-                ),
272
-                'type'       => 'string',
273
-                'required'   => true,
274
-                'validation' => true,
275
-                'css_class'  => 'large-text',
276
-                'format'     => '%s',
277
-            ),
278
-            'cc'      => array(
279
-                'input'      => 'text',
280
-                'label'      => esc_html_x(
281
-                    'CC',
282
-                    'Label for the "Carbon Copy" field used for additional email addresses',
283
-                    'event_espresso'
284
-                ),
285
-                'type'       => 'string',
286
-                'required'   => false,
287
-                'validation' => true,
288
-                'css_class'  => 'large-text',
289
-                'format'     => '%s',
290
-            ),
291
-            'from'    => array(
292
-                'input'      => 'text',
293
-                'label'      => esc_html_x(
294
-                    'From',
295
-                    'Label for the "From" field for email addresses.',
296
-                    'event_espresso'
297
-                ),
298
-                'type'       => 'string',
299
-                'required'   => true,
300
-                'validation' => true,
301
-                'css_class'  => 'large-text',
302
-                'format'     => '%s',
303
-            ),
304
-            'subject' => array(
305
-                'input'      => 'text',
306
-                'label'      => esc_html_x(
307
-                    'Subject',
308
-                    'Label for the "Subject" field (short description of contents) for emails.',
309
-                    'event_espresso'
310
-                ),
311
-                'type'       => 'string',
312
-                'required'   => true,
313
-                'validation' => true,
314
-                'css_class'  => 'large-text',
315
-                'format'     => '%s',
316
-            ),
317
-            'content' => '',
318
-            //left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
319
-            'extra'   => array(
320
-                'content' => array(
321
-                    'main'          => array(
322
-                        'input'      => 'wp_editor',
323
-                        'label'      => esc_html__('Main Content', 'event_espresso'),
324
-                        'type'       => 'string',
325
-                        'required'   => true,
326
-                        'validation' => true,
327
-                        'format'     => '%s',
328
-                        'rows'       => '15',
329
-                    ),
330
-                    'event_list'    => array(
331
-                        'input'               => 'wp_editor',
332
-                        'label'               => '[EVENT_LIST]',
333
-                        'type'                => 'string',
334
-                        'required'            => true,
335
-                        'validation'          => true,
336
-                        'format'              => '%s',
337
-                        'rows'                => '15',
338
-                        'shortcodes_required' => array('[EVENT_LIST]'),
339
-                    ),
340
-                    'attendee_list' => array(
341
-                        'input'               => 'textarea',
342
-                        'label'               => '[ATTENDEE_LIST]',
343
-                        'type'                => 'string',
344
-                        'required'            => true,
345
-                        'validation'          => true,
346
-                        'format'              => '%s',
347
-                        'css_class'           => 'large-text',
348
-                        'rows'                => '5',
349
-                        'shortcodes_required' => array('[ATTENDEE_LIST]'),
350
-                    ),
351
-                    'ticket_list'   => array(
352
-                        'input'               => 'textarea',
353
-                        'label'               => '[TICKET_LIST]',
354
-                        'type'                => 'string',
355
-                        'required'            => true,
356
-                        'validation'          => true,
357
-                        'format'              => '%s',
358
-                        'css_class'           => 'large-text',
359
-                        'rows'                => '10',
360
-                        'shortcodes_required' => array('[TICKET_LIST]'),
361
-                    ),
362
-                    'datetime_list' => array(
363
-                        'input'               => 'textarea',
364
-                        'label'               => '[DATETIME_LIST]',
365
-                        'type'                => 'string',
366
-                        'required'            => true,
367
-                        'validation'          => true,
368
-                        'format'              => '%s',
369
-                        'css_class'           => 'large-text',
370
-                        'rows'                => '10',
371
-                        'shortcodes_required' => array('[DATETIME_LIST]'),
372
-                    ),
373
-                ),
374
-            ),
375
-        );
376
-    }
377
-
378
-
379
-    /**
380
-     * See definition of this class in parent
381
-     */
382
-    protected function _set_default_message_types()
383
-    {
384
-        $this->_default_message_types = array(
385
-            'payment',
386
-            'payment_refund',
387
-            'registration',
388
-            'not_approved_registration',
389
-            'pending_approval',
390
-        );
391
-    }
392
-
393
-
394
-    /**
395
-     * @see   definition of this class in parent
396
-     * @since 4.5.0
397
-     */
398
-    protected function _set_valid_message_types()
399
-    {
400
-        $this->_valid_message_types = array(
401
-            'payment',
402
-            'registration',
403
-            'not_approved_registration',
404
-            'declined_registration',
405
-            'cancelled_registration',
406
-            'pending_approval',
407
-            'registration_summary',
408
-            'payment_reminder',
409
-            'payment_declined',
410
-            'payment_refund',
411
-        );
412
-    }
413
-
414
-
415
-    /**
416
-     * setting up admin_settings_fields for messenger.
417
-     */
418
-    protected function _set_admin_settings_fields()
419
-    {
420
-    }
421
-
422
-    /**
423
-     * We just deliver the messages don't kill us!!
424
-     *
425
-     * @return bool|WP_Error true if message delivered, false if it didn't deliver OR bubble up any error object if
426
-     *              present.
427
-     * @throws EE_Error
428
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
429
-     */
430
-    protected function _send_message()
431
-    {
432
-        $success = wp_mail(
433
-            html_entity_decode($this->_to, ENT_QUOTES, "UTF-8"),
434
-            stripslashes(html_entity_decode($this->_subject, ENT_QUOTES, "UTF-8")),
435
-            $this->_body(),
436
-            $this->_headers()
437
-        );
438
-        if (! $success) {
439
-            EE_Error::add_error(
440
-                sprintf(
441
-                    esc_html__(
442
-                        'The email did not send successfully.%3$sThe WordPress wp_mail function is used for sending mails but does not give any useful information when an email fails to send.%3$sIt is possible the "to" address (%1$s) or "from" address (%2$s) is invalid.%3$s',
443
-                        'event_espresso'
444
-                    ),
445
-                    $this->_to,
446
-                    $this->_from,
447
-                    '<br />'
448
-                ),
449
-                __FILE__,
450
-                __FUNCTION__,
451
-                __LINE__
452
-            );
453
-        }
454
-        return $success;
455
-    }
456
-
457
-
458
-    /**
459
-     * see parent for definition
460
-     *
461
-     * @return string html body of the message content and the related css.
462
-     * @throws EE_Error
463
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
464
-     */
465
-    protected function _preview()
466
-    {
467
-        return $this->_body(true);
468
-    }
469
-
470
-
471
-    /**
472
-     * Setup headers for email
473
-     *
474
-     * @access protected
475
-     * @return string formatted header for email
476
-     */
477
-    protected function _headers()
478
-    {
479
-        $this->_ensure_has_from_email_address();
480
-        $from    = stripslashes_deep(html_entity_decode($this->_from, ENT_QUOTES, "UTF-8"));
481
-        $headers = array(
482
-            'MIME-Version: 1.0',
483
-            'From:' . $from,
484
-            'Reply-To:' . $from,
485
-            'Content-Type:text/html; charset=utf-8',
486
-        );
487
-
488
-        if (! empty($this->_cc)) {
489
-            $headers[] = 'cc: ' . $this->_cc;
490
-        }
491
-
492
-        //but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
493
-        // header.
494
-        add_filter('wp_mail_from', array($this, 'set_from_address'), 100);
495
-        add_filter('wp_mail_from_name', array($this, 'set_from_name'), 100);
496
-        return apply_filters('FHEE__EE_Email_messenger___headers', $headers, $this->_incoming_message_type, $this);
497
-    }
498
-
499
-
500
-    /**
501
-     * This simply ensures that the from address is not empty.  If it is, then we use whatever is set as the site email
502
-     * address for the from address to avoid problems with sending emails.
503
-     */
504
-    protected function _ensure_has_from_email_address()
505
-    {
506
-        if (empty($this->_from)) {
507
-            $this->_from = get_bloginfo('admin_email');
508
-        }
509
-    }
510
-
511
-
512
-    /**
513
-     * This simply parses whatever is set as the $_from address and determines if it is in the format {name} <{email}>
514
-     * or just {email} and returns an array with the "from_name" and "from_email" as the values. Note from_name *MAY*
515
-     * be empty
516
-     *
517
-     * @since 4.3.1
518
-     * @return array
519
-     */
520
-    private function _parse_from()
521
-    {
522
-        if (strpos($this->_from, '<') !== false) {
523
-            $from_name = substr($this->_from, 0, strpos($this->_from, '<') - 1);
524
-            $from_name = str_replace('"', '', $from_name);
525
-            $from_name = trim($from_name);
526
-
527
-            $from_email = substr($this->_from, strpos($this->_from, '<') + 1);
528
-            $from_email = str_replace('>', '', $from_email);
529
-            $from_email = trim($from_email);
530
-        } elseif (trim($this->_from) !== '') {
531
-            $from_name  = '';
532
-            $from_email = trim($this->_from);
533
-        } else {
534
-            $from_name = $from_email = '';
535
-        }
536
-        return array($from_name, $from_email);
537
-    }
538
-
539
-
540
-    /**
541
-     * Callback for the wp_mail_from filter.
542
-     *
543
-     * @since 4.3.1
544
-     * @param string $from_email What the original from_email is.
545
-     * @return string
546
-     */
547
-    public function set_from_address($from_email)
548
-    {
549
-        $parsed_from = $this->_parse_from();
550
-        //includes fallback if the parsing failed.
551
-        $from_email = is_array($parsed_from) && ! empty($parsed_from[1])
552
-            ? $parsed_from[1]
553
-            : get_bloginfo('admin_email');
554
-        return $from_email;
555
-    }
556
-
557
-
558
-    /**
559
-     * Callback fro the wp_mail_from_name filter.
560
-     *
561
-     * @since 4.3.1
562
-     * @param string $from_name The original from_name.
563
-     * @return string
564
-     */
565
-    public function set_from_name($from_name)
566
-    {
567
-        $parsed_from = $this->_parse_from();
568
-        if (is_array($parsed_from) && ! empty($parsed_from[0])) {
569
-            $from_name = $parsed_from[0];
570
-        }
571
-
572
-        //if from name is "WordPress" let's sub in the site name instead (more friendly!)
573
-        $from_name = $from_name == 'WordPress' ? get_bloginfo() : $from_name;
574
-
575
-        return stripslashes_deep(html_entity_decode($from_name, ENT_QUOTES, "UTF-8"));
576
-    }
577
-
578
-
579
-    /**
580
-     * setup body for email
581
-     *
582
-     * @param bool $preview will determine whether this is preview template or not.
583
-     * @return string formatted body for email.
584
-     * @throws EE_Error
585
-     * @throws \TijsVerkoyen\CssToInlineStyles\Exception
586
-     */
587
-    protected function _body($preview = false)
588
-    {
589
-        //setup template args!
590
-        $this->_template_args = array(
591
-            'subject'   => $this->_subject,
592
-            'from'      => $this->_from,
593
-            'main_body' => wpautop(
594
-                stripslashes_deep(
595
-                    html_entity_decode($this->_content, ENT_QUOTES, "UTF-8")
596
-                )
597
-            ),
598
-        );
599
-        $body                 = $this->_get_main_template($preview);
600
-
601
-        /**
602
-         * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
603
-         *
604
-         * @type    bool $preview Indicates whether a preview is being generated or not.
605
-         * @return  bool    true  indicates to use the inliner, false bypasses it.
606
-         */
607
-        if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
608
-            //require CssToInlineStyles library and its dependencies via composer autoloader
609
-            require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
610
-
611
-            //now if this isn't a preview, let's setup the body so it has inline styles
612
-            if (! $preview || ($preview && defined('DOING_AJAX'))) {
613
-                $style = file_get_contents(
614
-                    $this->get_variation(
615
-                        $this->_tmp_pack,
616
-                        $this->_incoming_message_type->name,
617
-                        false,
618
-                        'main',
619
-                        $this->_variation
620
-                    ),
621
-                    true
622
-                );
623
-                $CSS   = new TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($body, $style);
624
-                //for some reason the library has a bracket and new line at the beginning.  This takes care of that.
625
-                $body  = ltrim($CSS->convert(true), ">\n");
626
-                //see https://events.codebasehq.com/projects/event-espresso/tickets/8609
627
-                $body  = ltrim($body, "<?");
628
-            }
629
-
630
-        }
631
-        return $body;
632
-    }
633
-
634
-
635
-    /**
636
-     * This just returns any existing test settings that might be saved in the database
637
-     *
638
-     * @access public
639
-     * @return array
640
-     */
641
-    public function get_existing_test_settings()
642
-    {
643
-        $settings = parent::get_existing_test_settings();
644
-        //override subject if present because we always want it to be fresh.
645
-        if (is_array($settings) && ! empty($settings['subject'])) {
646
-            $settings['subject'] = sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name'));
647
-        }
648
-        return $settings;
649
-    }
11
+	/**
12
+	 * To field for email
13
+	 * @var string
14
+	 */
15
+	protected $_to = '';
16
+
17
+
18
+	/**
19
+	 * CC field for email.
20
+	 * @var string
21
+	 */
22
+	protected $_cc = '';
23
+
24
+	/**
25
+	 * From field for email
26
+	 * @var string
27
+	 */
28
+	protected $_from = '';
29
+
30
+
31
+	/**
32
+	 * Subject field for email
33
+	 * @var string
34
+	 */
35
+	protected $_subject = '';
36
+
37
+
38
+	/**
39
+	 * Content field for email
40
+	 * @var string
41
+	 */
42
+	protected $_content = '';
43
+
44
+
45
+	/**
46
+	 * constructor
47
+	 *
48
+	 * @access public
49
+	 */
50
+	public function __construct()
51
+	{
52
+		//set name and description properties
53
+		$this->name                = 'email';
54
+		$this->description         = esc_html__(
55
+			'This messenger delivers messages via email using the built-in <code>wp_mail</code> function included with WordPress',
56
+			'event_espresso'
57
+		);
58
+		$this->label               = array(
59
+			'singular' => esc_html__('email', 'event_espresso'),
60
+			'plural'   => esc_html__('emails', 'event_espresso'),
61
+		);
62
+		$this->activate_on_install = true;
63
+
64
+		//we're using defaults so let's call parent constructor that will take care of setting up all the other
65
+		// properties
66
+		parent::__construct();
67
+	}
68
+
69
+
70
+	/**
71
+	 * see abstract declaration in parent class for details.
72
+	 */
73
+	protected function _set_admin_pages()
74
+	{
75
+		$this->admin_registered_pages = array(
76
+			'events_edit' => true,
77
+		);
78
+	}
79
+
80
+
81
+	/**
82
+	 * see abstract declaration in parent class for details
83
+	 */
84
+	protected function _set_valid_shortcodes()
85
+	{
86
+		//remember by leaving the other fields not set, those fields will inherit the valid shortcodes from the
87
+		// message type.
88
+		$this->_valid_shortcodes = array(
89
+			'to'   => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
90
+			'cc' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
91
+			'from' => array('email', 'event_author', 'primary_registration_details', 'recipient_details'),
92
+		);
93
+	}
94
+
95
+
96
+	/**
97
+	 * see abstract declaration in parent class for details
98
+	 *
99
+	 * @access protected
100
+	 * @return void
101
+	 */
102
+	protected function _set_validator_config()
103
+	{
104
+		$valid_shortcodes = $this->get_valid_shortcodes();
105
+
106
+		$this->_validator_config = array(
107
+			'to'            => array(
108
+				'shortcodes' => $valid_shortcodes['to'],
109
+				'type'       => 'email',
110
+			),
111
+			'cc' => array(
112
+				'shortcodes' => $valid_shortcodes['to'],
113
+				'type' => 'email',
114
+			),
115
+			'from'          => array(
116
+				'shortcodes' => $valid_shortcodes['from'],
117
+				'type'       => 'email',
118
+			),
119
+			'subject'       => array(
120
+				'shortcodes' => array(
121
+					'organization',
122
+					'primary_registration_details',
123
+					'event_author',
124
+					'primary_registration_details',
125
+					'recipient_details',
126
+				),
127
+			),
128
+			'content'       => array(
129
+				'shortcodes' => array(
130
+					'event_list',
131
+					'attendee_list',
132
+					'ticket_list',
133
+					'organization',
134
+					'primary_registration_details',
135
+					'primary_registration_list',
136
+					'event_author',
137
+					'recipient_details',
138
+					'recipient_list',
139
+					'transaction',
140
+					'messenger',
141
+				),
142
+			),
143
+			'attendee_list' => array(
144
+				'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
145
+				'required'   => array('[ATTENDEE_LIST]'),
146
+			),
147
+			'event_list'    => array(
148
+				'shortcodes' => array(
149
+					'event',
150
+					'attendee_list',
151
+					'ticket_list',
152
+					'venue',
153
+					'datetime_list',
154
+					'attendee',
155
+					'primary_registration_details',
156
+					'primary_registration_list',
157
+					'event_author',
158
+					'recipient_details',
159
+					'recipient_list',
160
+				),
161
+				'required'   => array('[EVENT_LIST]'),
162
+			),
163
+			'ticket_list'   => array(
164
+				'shortcodes' => array(
165
+					'event_list',
166
+					'attendee_list',
167
+					'ticket',
168
+					'datetime_list',
169
+					'primary_registration_details',
170
+					'recipient_details',
171
+				),
172
+				'required'   => array('[TICKET_LIST]'),
173
+			),
174
+			'datetime_list' => array(
175
+				'shortcodes' => array('datetime'),
176
+				'required'   => array('[DATETIME_LIST]'),
177
+			),
178
+		);
179
+	}
180
+
181
+
182
+	/**
183
+	 * @see   parent EE_messenger class for docs
184
+	 * @since 4.5.0
185
+	 */
186
+	public function do_secondary_messenger_hooks($sending_messenger_name)
187
+	{
188
+		if ($sending_messenger_name = 'html') {
189
+			add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
190
+		}
191
+	}
192
+
193
+
194
+	public function add_email_css(
195
+		$variation_path,
196
+		$messenger,
197
+		$message_type,
198
+		$type,
199
+		$variation,
200
+		$file_extension,
201
+		$url,
202
+		EE_Messages_Template_Pack $template_pack
203
+	) {
204
+		//prevent recursion on this callback.
205
+		remove_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10);
206
+		$variation = $this->get_variation($template_pack, $message_type, $url, 'main', $variation, false);
207
+
208
+		add_filter('FHEE__EE_Messages_Template_Pack__get_variation', array($this, 'add_email_css'), 10, 8);
209
+		return $variation;
210
+	}
211
+
212
+
213
+	/**
214
+	 * See parent for details
215
+	 *
216
+	 * @access protected
217
+	 * @return void
218
+	 */
219
+	protected function _set_test_settings_fields()
220
+	{
221
+		$this->_test_settings_fields = array(
222
+			'to'      => array(
223
+				'input'      => 'text',
224
+				'label'      => esc_html__('Send a test email to', 'event_espresso'),
225
+				'type'       => 'email',
226
+				'required'   => true,
227
+				'validation' => true,
228
+				'css_class'  => 'large-text',
229
+				'format'     => '%s',
230
+				'default'    => get_bloginfo('admin_email'),
231
+			),
232
+			'subject' => array(
233
+				'input'      => 'hidden',
234
+				'label'      => '',
235
+				'type'       => 'string',
236
+				'required'   => false,
237
+				'validation' => false,
238
+				'format'     => '%s',
239
+				'value'      => sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name')),
240
+				'default'    => '',
241
+				'css_class'  => '',
242
+			),
243
+		);
244
+	}
245
+
246
+
247
+	/**
248
+	 * _set_template_fields
249
+	 * This sets up the fields that a messenger requires for the message to go out.
250
+	 *
251
+	 * @access  protected
252
+	 * @return void
253
+	 */
254
+	protected function _set_template_fields()
255
+	{
256
+		// any extra template fields that are NOT used by the messenger but will get used by a messenger field for
257
+		// shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field
258
+		// they relate to.  This is important for the Messages_admin to know what fields to display to the user.
259
+		//  Also, notice that the "values" are equal to the field type that messages admin will use to know what
260
+		// kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array
261
+		// indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be
262
+		// displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and
263
+		// will not be displayed/parsed.
264
+		$this->_template_fields = array(
265
+			'to'      => array(
266
+				'input'      => 'text',
267
+				'label'      => esc_html_x(
268
+					'To',
269
+					'Label for the "To" field for email addresses',
270
+					'event_espresso'
271
+				),
272
+				'type'       => 'string',
273
+				'required'   => true,
274
+				'validation' => true,
275
+				'css_class'  => 'large-text',
276
+				'format'     => '%s',
277
+			),
278
+			'cc'      => array(
279
+				'input'      => 'text',
280
+				'label'      => esc_html_x(
281
+					'CC',
282
+					'Label for the "Carbon Copy" field used for additional email addresses',
283
+					'event_espresso'
284
+				),
285
+				'type'       => 'string',
286
+				'required'   => false,
287
+				'validation' => true,
288
+				'css_class'  => 'large-text',
289
+				'format'     => '%s',
290
+			),
291
+			'from'    => array(
292
+				'input'      => 'text',
293
+				'label'      => esc_html_x(
294
+					'From',
295
+					'Label for the "From" field for email addresses.',
296
+					'event_espresso'
297
+				),
298
+				'type'       => 'string',
299
+				'required'   => true,
300
+				'validation' => true,
301
+				'css_class'  => 'large-text',
302
+				'format'     => '%s',
303
+			),
304
+			'subject' => array(
305
+				'input'      => 'text',
306
+				'label'      => esc_html_x(
307
+					'Subject',
308
+					'Label for the "Subject" field (short description of contents) for emails.',
309
+					'event_espresso'
310
+				),
311
+				'type'       => 'string',
312
+				'required'   => true,
313
+				'validation' => true,
314
+				'css_class'  => 'large-text',
315
+				'format'     => '%s',
316
+			),
317
+			'content' => '',
318
+			//left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
319
+			'extra'   => array(
320
+				'content' => array(
321
+					'main'          => array(
322
+						'input'      => 'wp_editor',
323
+						'label'      => esc_html__('Main Content', 'event_espresso'),
324
+						'type'       => 'string',
325
+						'required'   => true,
326
+						'validation' => true,
327
+						'format'     => '%s',
328
+						'rows'       => '15',
329
+					),
330
+					'event_list'    => array(
331
+						'input'               => 'wp_editor',
332
+						'label'               => '[EVENT_LIST]',
333
+						'type'                => 'string',
334
+						'required'            => true,
335
+						'validation'          => true,
336
+						'format'              => '%s',
337
+						'rows'                => '15',
338
+						'shortcodes_required' => array('[EVENT_LIST]'),
339
+					),
340
+					'attendee_list' => array(
341
+						'input'               => 'textarea',
342
+						'label'               => '[ATTENDEE_LIST]',
343
+						'type'                => 'string',
344
+						'required'            => true,
345
+						'validation'          => true,
346
+						'format'              => '%s',
347
+						'css_class'           => 'large-text',
348
+						'rows'                => '5',
349
+						'shortcodes_required' => array('[ATTENDEE_LIST]'),
350
+					),
351
+					'ticket_list'   => array(
352
+						'input'               => 'textarea',
353
+						'label'               => '[TICKET_LIST]',
354
+						'type'                => 'string',
355
+						'required'            => true,
356
+						'validation'          => true,
357
+						'format'              => '%s',
358
+						'css_class'           => 'large-text',
359
+						'rows'                => '10',
360
+						'shortcodes_required' => array('[TICKET_LIST]'),
361
+					),
362
+					'datetime_list' => array(
363
+						'input'               => 'textarea',
364
+						'label'               => '[DATETIME_LIST]',
365
+						'type'                => 'string',
366
+						'required'            => true,
367
+						'validation'          => true,
368
+						'format'              => '%s',
369
+						'css_class'           => 'large-text',
370
+						'rows'                => '10',
371
+						'shortcodes_required' => array('[DATETIME_LIST]'),
372
+					),
373
+				),
374
+			),
375
+		);
376
+	}
377
+
378
+
379
+	/**
380
+	 * See definition of this class in parent
381
+	 */
382
+	protected function _set_default_message_types()
383
+	{
384
+		$this->_default_message_types = array(
385
+			'payment',
386
+			'payment_refund',
387
+			'registration',
388
+			'not_approved_registration',
389
+			'pending_approval',
390
+		);
391
+	}
392
+
393
+
394
+	/**
395
+	 * @see   definition of this class in parent
396
+	 * @since 4.5.0
397
+	 */
398
+	protected function _set_valid_message_types()
399
+	{
400
+		$this->_valid_message_types = array(
401
+			'payment',
402
+			'registration',
403
+			'not_approved_registration',
404
+			'declined_registration',
405
+			'cancelled_registration',
406
+			'pending_approval',
407
+			'registration_summary',
408
+			'payment_reminder',
409
+			'payment_declined',
410
+			'payment_refund',
411
+		);
412
+	}
413
+
414
+
415
+	/**
416
+	 * setting up admin_settings_fields for messenger.
417
+	 */
418
+	protected function _set_admin_settings_fields()
419
+	{
420
+	}
421
+
422
+	/**
423
+	 * We just deliver the messages don't kill us!!
424
+	 *
425
+	 * @return bool|WP_Error true if message delivered, false if it didn't deliver OR bubble up any error object if
426
+	 *              present.
427
+	 * @throws EE_Error
428
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
429
+	 */
430
+	protected function _send_message()
431
+	{
432
+		$success = wp_mail(
433
+			html_entity_decode($this->_to, ENT_QUOTES, "UTF-8"),
434
+			stripslashes(html_entity_decode($this->_subject, ENT_QUOTES, "UTF-8")),
435
+			$this->_body(),
436
+			$this->_headers()
437
+		);
438
+		if (! $success) {
439
+			EE_Error::add_error(
440
+				sprintf(
441
+					esc_html__(
442
+						'The email did not send successfully.%3$sThe WordPress wp_mail function is used for sending mails but does not give any useful information when an email fails to send.%3$sIt is possible the "to" address (%1$s) or "from" address (%2$s) is invalid.%3$s',
443
+						'event_espresso'
444
+					),
445
+					$this->_to,
446
+					$this->_from,
447
+					'<br />'
448
+				),
449
+				__FILE__,
450
+				__FUNCTION__,
451
+				__LINE__
452
+			);
453
+		}
454
+		return $success;
455
+	}
456
+
457
+
458
+	/**
459
+	 * see parent for definition
460
+	 *
461
+	 * @return string html body of the message content and the related css.
462
+	 * @throws EE_Error
463
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
464
+	 */
465
+	protected function _preview()
466
+	{
467
+		return $this->_body(true);
468
+	}
469
+
470
+
471
+	/**
472
+	 * Setup headers for email
473
+	 *
474
+	 * @access protected
475
+	 * @return string formatted header for email
476
+	 */
477
+	protected function _headers()
478
+	{
479
+		$this->_ensure_has_from_email_address();
480
+		$from    = stripslashes_deep(html_entity_decode($this->_from, ENT_QUOTES, "UTF-8"));
481
+		$headers = array(
482
+			'MIME-Version: 1.0',
483
+			'From:' . $from,
484
+			'Reply-To:' . $from,
485
+			'Content-Type:text/html; charset=utf-8',
486
+		);
487
+
488
+		if (! empty($this->_cc)) {
489
+			$headers[] = 'cc: ' . $this->_cc;
490
+		}
491
+
492
+		//but wait!  Header's for the from is NOT reliable because some plugins don't respect From: as set in the
493
+		// header.
494
+		add_filter('wp_mail_from', array($this, 'set_from_address'), 100);
495
+		add_filter('wp_mail_from_name', array($this, 'set_from_name'), 100);
496
+		return apply_filters('FHEE__EE_Email_messenger___headers', $headers, $this->_incoming_message_type, $this);
497
+	}
498
+
499
+
500
+	/**
501
+	 * This simply ensures that the from address is not empty.  If it is, then we use whatever is set as the site email
502
+	 * address for the from address to avoid problems with sending emails.
503
+	 */
504
+	protected function _ensure_has_from_email_address()
505
+	{
506
+		if (empty($this->_from)) {
507
+			$this->_from = get_bloginfo('admin_email');
508
+		}
509
+	}
510
+
511
+
512
+	/**
513
+	 * This simply parses whatever is set as the $_from address and determines if it is in the format {name} <{email}>
514
+	 * or just {email} and returns an array with the "from_name" and "from_email" as the values. Note from_name *MAY*
515
+	 * be empty
516
+	 *
517
+	 * @since 4.3.1
518
+	 * @return array
519
+	 */
520
+	private function _parse_from()
521
+	{
522
+		if (strpos($this->_from, '<') !== false) {
523
+			$from_name = substr($this->_from, 0, strpos($this->_from, '<') - 1);
524
+			$from_name = str_replace('"', '', $from_name);
525
+			$from_name = trim($from_name);
526
+
527
+			$from_email = substr($this->_from, strpos($this->_from, '<') + 1);
528
+			$from_email = str_replace('>', '', $from_email);
529
+			$from_email = trim($from_email);
530
+		} elseif (trim($this->_from) !== '') {
531
+			$from_name  = '';
532
+			$from_email = trim($this->_from);
533
+		} else {
534
+			$from_name = $from_email = '';
535
+		}
536
+		return array($from_name, $from_email);
537
+	}
538
+
539
+
540
+	/**
541
+	 * Callback for the wp_mail_from filter.
542
+	 *
543
+	 * @since 4.3.1
544
+	 * @param string $from_email What the original from_email is.
545
+	 * @return string
546
+	 */
547
+	public function set_from_address($from_email)
548
+	{
549
+		$parsed_from = $this->_parse_from();
550
+		//includes fallback if the parsing failed.
551
+		$from_email = is_array($parsed_from) && ! empty($parsed_from[1])
552
+			? $parsed_from[1]
553
+			: get_bloginfo('admin_email');
554
+		return $from_email;
555
+	}
556
+
557
+
558
+	/**
559
+	 * Callback fro the wp_mail_from_name filter.
560
+	 *
561
+	 * @since 4.3.1
562
+	 * @param string $from_name The original from_name.
563
+	 * @return string
564
+	 */
565
+	public function set_from_name($from_name)
566
+	{
567
+		$parsed_from = $this->_parse_from();
568
+		if (is_array($parsed_from) && ! empty($parsed_from[0])) {
569
+			$from_name = $parsed_from[0];
570
+		}
571
+
572
+		//if from name is "WordPress" let's sub in the site name instead (more friendly!)
573
+		$from_name = $from_name == 'WordPress' ? get_bloginfo() : $from_name;
574
+
575
+		return stripslashes_deep(html_entity_decode($from_name, ENT_QUOTES, "UTF-8"));
576
+	}
577
+
578
+
579
+	/**
580
+	 * setup body for email
581
+	 *
582
+	 * @param bool $preview will determine whether this is preview template or not.
583
+	 * @return string formatted body for email.
584
+	 * @throws EE_Error
585
+	 * @throws \TijsVerkoyen\CssToInlineStyles\Exception
586
+	 */
587
+	protected function _body($preview = false)
588
+	{
589
+		//setup template args!
590
+		$this->_template_args = array(
591
+			'subject'   => $this->_subject,
592
+			'from'      => $this->_from,
593
+			'main_body' => wpautop(
594
+				stripslashes_deep(
595
+					html_entity_decode($this->_content, ENT_QUOTES, "UTF-8")
596
+				)
597
+			),
598
+		);
599
+		$body                 = $this->_get_main_template($preview);
600
+
601
+		/**
602
+		 * This filter allows one to bypass the CSSToInlineStyles tool and leave the body untouched.
603
+		 *
604
+		 * @type    bool $preview Indicates whether a preview is being generated or not.
605
+		 * @return  bool    true  indicates to use the inliner, false bypasses it.
606
+		 */
607
+		if (apply_filters('FHEE__EE_Email_messenger__apply_CSSInliner ', true, $preview)) {
608
+			//require CssToInlineStyles library and its dependencies via composer autoloader
609
+			require_once EE_THIRD_PARTY . 'cssinliner/vendor/autoload.php';
610
+
611
+			//now if this isn't a preview, let's setup the body so it has inline styles
612
+			if (! $preview || ($preview && defined('DOING_AJAX'))) {
613
+				$style = file_get_contents(
614
+					$this->get_variation(
615
+						$this->_tmp_pack,
616
+						$this->_incoming_message_type->name,
617
+						false,
618
+						'main',
619
+						$this->_variation
620
+					),
621
+					true
622
+				);
623
+				$CSS   = new TijsVerkoyen\CssToInlineStyles\CssToInlineStyles($body, $style);
624
+				//for some reason the library has a bracket and new line at the beginning.  This takes care of that.
625
+				$body  = ltrim($CSS->convert(true), ">\n");
626
+				//see https://events.codebasehq.com/projects/event-espresso/tickets/8609
627
+				$body  = ltrim($body, "<?");
628
+			}
629
+
630
+		}
631
+		return $body;
632
+	}
633
+
634
+
635
+	/**
636
+	 * This just returns any existing test settings that might be saved in the database
637
+	 *
638
+	 * @access public
639
+	 * @return array
640
+	 */
641
+	public function get_existing_test_settings()
642
+	{
643
+		$settings = parent::get_existing_test_settings();
644
+		//override subject if present because we always want it to be fresh.
645
+		if (is_array($settings) && ! empty($settings['subject'])) {
646
+			$settings['subject'] = sprintf(__('Test email sent from %s', 'event_espresso'), get_bloginfo('name'));
647
+		}
648
+		return $settings;
649
+	}
650 650
 }
Please login to merge, or discard this patch.
modules/messages/EED_Messages.module.php 1 patch
Indentation   +1080 added lines, -1080 removed lines patch added patch discarded remove patch
@@ -13,1095 +13,1095 @@
 block discarded – undo
13 13
 class EED_Messages extends EED_Module
14 14
 {
15 15
 
16
-    /**
17
-     * This holds the EE_messages controller
18
-     *
19
-     * @deprecated 4.9.0
20
-     * @var EE_messages $_EEMSG
21
-     */
22
-    protected static $_EEMSG;
23
-
24
-    /**
25
-     * @type EE_Message_Resource_Manager $_message_resource_manager
26
-     */
27
-    protected static $_message_resource_manager;
28
-
29
-    /**
30
-     * This holds the EE_Messages_Processor business class.
31
-     *
32
-     * @type EE_Messages_Processor
33
-     */
34
-    protected static $_MSG_PROCESSOR;
35
-
36
-    /**
37
-     * holds all the paths for various messages components.
38
-     * Utilized by autoloader registry
39
-     *
40
-     * @var array
41
-     */
42
-    protected static $_MSG_PATHS;
43
-
44
-
45
-    /**
46
-     * This will hold an array of messages template packs that are registered in the messages system.
47
-     * Format is:
48
-     * array(
49
-     *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
50
-     * )
51
-     *
52
-     * @var EE_Messages_Template_Pack[]
53
-     */
54
-    protected static $_TMP_PACKS = array();
55
-
56
-
57
-    /**
58
-     * @return EED_Messages
59
-     */
60
-    public static function instance()
61
-    {
62
-        return parent::get_instance(__CLASS__);
63
-    }
64
-
65
-
66
-    /**
67
-     *  set_hooks - for hooking into EE Core, other modules, etc
68
-     *
69
-     * @since 4.5.0
70
-     * @return    void
71
-     */
72
-    public static function set_hooks()
73
-    {
74
-        //actions
75
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
76
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
77
-            array('EED_Messages', 'maybe_registration'), 10, 2);
78
-        //filters
79
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
80
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
81
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
82
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
83
-        //register routes
84
-        self::_register_routes();
85
-    }
86
-
87
-    /**
88
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
89
-     *
90
-     * @access    public
91
-     * @return    void
92
-     */
93
-    public static function set_hooks_admin()
94
-    {
95
-        //actions
96
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
97
-        add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
98
-            array('EED_Messages', 'payment_reminder'), 10);
99
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
100
-            array('EED_Messages', 'maybe_registration'), 10, 3);
101
-        add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
102
-            array('EED_Messages', 'send_newsletter_message'), 10, 2);
103
-        add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
104
-            array('EED_Messages', 'cancelled_registration'), 10);
105
-        add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
106
-            array('EED_Messages', 'process_admin_payment'), 10, 1);
107
-        //filters
108
-        add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
109
-            array('EED_Messages', 'process_resend'), 10, 2);
110
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
111
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
112
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
113
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
114
-    }
115
-
116
-
117
-    /**
118
-     * All the message triggers done by route go in here.
119
-     *
120
-     * @since 4.5.0
121
-     * @return void
122
-     */
123
-    protected static function _register_routes()
124
-    {
125
-        EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
126
-        EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
127
-        EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
128
-        EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
129
-        do_action('AHEE__EED_Messages___register_routes');
130
-    }
131
-
132
-
133
-    /**
134
-     * This is called when a browser display trigger is executed.
135
-     * The browser display trigger is typically used when a already generated message is displayed directly in the
136
-     * browser.
137
-     *
138
-     * @since 4.9.0
139
-     * @param WP $WP
140
-     */
141
-    public function browser_trigger($WP)
142
-    {
143
-        //ensure controller is loaded
144
-        self::_load_controller();
145
-        $token = EE_Registry::instance()->REQ->get('token');
146
-        try {
147
-            $mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
148
-            self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
149
-        } catch (EE_Error $e) {
150
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
151
-                'event_espresso');
152
-            // add specific message for developers if WP_DEBUG in on
153
-            $error_msg .= '||' . $e->getMessage();
154
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
155
-        }
156
-    }
157
-
158
-
159
-    /**
160
-     * This is called when a browser error trigger is executed.
161
-     * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
162
-     * message and display it.
163
-     *
164
-     * @since 4.9.0
165
-     * @param $WP
166
-     */
167
-    public function browser_error_trigger($WP)
168
-    {
169
-        $token = EE_Registry::instance()->REQ->get('token');
170
-        if ($token) {
171
-            $message = EEM_Message::instance()->get_one_by_token($token);
172
-            if ($message instanceof EE_Message) {
173
-                header('HTTP/1.1 200 OK');
174
-                $error_msg = nl2br($message->error_message());
175
-                ?>
16
+	/**
17
+	 * This holds the EE_messages controller
18
+	 *
19
+	 * @deprecated 4.9.0
20
+	 * @var EE_messages $_EEMSG
21
+	 */
22
+	protected static $_EEMSG;
23
+
24
+	/**
25
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
26
+	 */
27
+	protected static $_message_resource_manager;
28
+
29
+	/**
30
+	 * This holds the EE_Messages_Processor business class.
31
+	 *
32
+	 * @type EE_Messages_Processor
33
+	 */
34
+	protected static $_MSG_PROCESSOR;
35
+
36
+	/**
37
+	 * holds all the paths for various messages components.
38
+	 * Utilized by autoloader registry
39
+	 *
40
+	 * @var array
41
+	 */
42
+	protected static $_MSG_PATHS;
43
+
44
+
45
+	/**
46
+	 * This will hold an array of messages template packs that are registered in the messages system.
47
+	 * Format is:
48
+	 * array(
49
+	 *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
50
+	 * )
51
+	 *
52
+	 * @var EE_Messages_Template_Pack[]
53
+	 */
54
+	protected static $_TMP_PACKS = array();
55
+
56
+
57
+	/**
58
+	 * @return EED_Messages
59
+	 */
60
+	public static function instance()
61
+	{
62
+		return parent::get_instance(__CLASS__);
63
+	}
64
+
65
+
66
+	/**
67
+	 *  set_hooks - for hooking into EE Core, other modules, etc
68
+	 *
69
+	 * @since 4.5.0
70
+	 * @return    void
71
+	 */
72
+	public static function set_hooks()
73
+	{
74
+		//actions
75
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
76
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
77
+			array('EED_Messages', 'maybe_registration'), 10, 2);
78
+		//filters
79
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
80
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
81
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
82
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
83
+		//register routes
84
+		self::_register_routes();
85
+	}
86
+
87
+	/**
88
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
89
+	 *
90
+	 * @access    public
91
+	 * @return    void
92
+	 */
93
+	public static function set_hooks_admin()
94
+	{
95
+		//actions
96
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
97
+		add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
98
+			array('EED_Messages', 'payment_reminder'), 10);
99
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
100
+			array('EED_Messages', 'maybe_registration'), 10, 3);
101
+		add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
102
+			array('EED_Messages', 'send_newsletter_message'), 10, 2);
103
+		add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
104
+			array('EED_Messages', 'cancelled_registration'), 10);
105
+		add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
106
+			array('EED_Messages', 'process_admin_payment'), 10, 1);
107
+		//filters
108
+		add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
109
+			array('EED_Messages', 'process_resend'), 10, 2);
110
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
111
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
112
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
113
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
114
+	}
115
+
116
+
117
+	/**
118
+	 * All the message triggers done by route go in here.
119
+	 *
120
+	 * @since 4.5.0
121
+	 * @return void
122
+	 */
123
+	protected static function _register_routes()
124
+	{
125
+		EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
126
+		EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
127
+		EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
128
+		EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
129
+		do_action('AHEE__EED_Messages___register_routes');
130
+	}
131
+
132
+
133
+	/**
134
+	 * This is called when a browser display trigger is executed.
135
+	 * The browser display trigger is typically used when a already generated message is displayed directly in the
136
+	 * browser.
137
+	 *
138
+	 * @since 4.9.0
139
+	 * @param WP $WP
140
+	 */
141
+	public function browser_trigger($WP)
142
+	{
143
+		//ensure controller is loaded
144
+		self::_load_controller();
145
+		$token = EE_Registry::instance()->REQ->get('token');
146
+		try {
147
+			$mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
148
+			self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
149
+		} catch (EE_Error $e) {
150
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
151
+				'event_espresso');
152
+			// add specific message for developers if WP_DEBUG in on
153
+			$error_msg .= '||' . $e->getMessage();
154
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
155
+		}
156
+	}
157
+
158
+
159
+	/**
160
+	 * This is called when a browser error trigger is executed.
161
+	 * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
162
+	 * message and display it.
163
+	 *
164
+	 * @since 4.9.0
165
+	 * @param $WP
166
+	 */
167
+	public function browser_error_trigger($WP)
168
+	{
169
+		$token = EE_Registry::instance()->REQ->get('token');
170
+		if ($token) {
171
+			$message = EEM_Message::instance()->get_one_by_token($token);
172
+			if ($message instanceof EE_Message) {
173
+				header('HTTP/1.1 200 OK');
174
+				$error_msg = nl2br($message->error_message());
175
+				?>
176 176
                 <!DOCTYPE html>
177 177
                 <html>
178 178
                 <head></head>
179 179
                 <body>
180 180
                 <?php echo empty($error_msg)
181
-                    ? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
182
-                        'event_espresso')
183
-                    : wp_kses(
184
-                        $error_msg,
185
-                        array(
186
-                            'a'      => array(
187
-                                'href'  => array(),
188
-                                'title' => array(),
189
-                            ),
190
-                            'span'   => array(),
191
-                            'div'    => array(),
192
-                            'p'      => array(),
193
-                            'strong' => array(),
194
-                            'em'     => array(),
195
-                            'br'     => array(),
196
-                        )
197
-                    ); ?>
181
+					? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
182
+						'event_espresso')
183
+					: wp_kses(
184
+						$error_msg,
185
+						array(
186
+							'a'      => array(
187
+								'href'  => array(),
188
+								'title' => array(),
189
+							),
190
+							'span'   => array(),
191
+							'div'    => array(),
192
+							'p'      => array(),
193
+							'strong' => array(),
194
+							'em'     => array(),
195
+							'br'     => array(),
196
+						)
197
+					); ?>
198 198
                 </body>
199 199
                 </html>
200 200
                 <?php
201
-                exit;
202
-            }
203
-        }
204
-        return;
205
-    }
206
-
207
-
208
-    /**
209
-     *  This runs when the msg_url_trigger route has initiated.
210
-     *
211
-     * @since 4.5.0
212
-     * @param WP $WP
213
-     * @throws EE_Error
214
-     * @return    void
215
-     */
216
-    public function run($WP)
217
-    {
218
-        //ensure controller is loaded
219
-        self::_load_controller();
220
-        // attempt to process message
221
-        try {
222
-            /** @type EE_Message_To_Generate_From_Request $message_to_generate */
223
-            $message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
224
-            self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
225
-        } catch (EE_Error $e) {
226
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
227
-                'event_espresso');
228
-            // add specific message for developers if WP_DEBUG in on
229
-            $error_msg .= '||' . $e->getMessage();
230
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
231
-        }
232
-    }
233
-
234
-
235
-    /**
236
-     * This is triggered by the 'msg_cron_trigger' route.
237
-     *
238
-     * @param WP $WP
239
-     */
240
-    public function execute_batch_request($WP)
241
-    {
242
-        $this->run_cron();
243
-        header('HTTP/1.1 200 OK');
244
-        exit();
245
-    }
246
-
247
-
248
-    /**
249
-     * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
250
-     * request.
251
-     */
252
-    public function run_cron()
253
-    {
254
-        self::_load_controller();
255
-        //get required vars
256
-        $cron_type     = EE_Registry::instance()->REQ->get('type');
257
-        $transient_key = EE_Registry::instance()->REQ->get('key');
258
-
259
-        //now let's verify transient, if not valid exit immediately
260
-        if (! get_transient($transient_key)) {
261
-            /**
262
-             * trigger error so this gets in the error logs.  This is important because it happens on a non-user request.
263
-             */
264
-            trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
265
-        }
266
-
267
-        //if made it here, lets' delete the transient to keep the db clean
268
-        delete_transient($transient_key);
269
-
270
-        if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
271
-
272
-            $method = 'batch_' . $cron_type . '_from_queue';
273
-            if (method_exists(self::$_MSG_PROCESSOR, $method)) {
274
-                self::$_MSG_PROCESSOR->$method();
275
-            } else {
276
-                //no matching task
277
-                /**
278
-                 * trigger error so this gets in the error logs.  This is important because it happens on a non user request.
279
-                 */
280
-                trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
281
-                    $cron_type)));
282
-            }
283
-        }
284
-
285
-        do_action('FHEE__EED_Messages__run_cron__end');
286
-    }
287
-
288
-
289
-    /**
290
-     * This is used to retrieve the template pack for the given name.
291
-     * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
292
-     * the default template pack is returned.
293
-     *
294
-     * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
295
-     * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
296
-     *                                   in generating the Pack class name).
297
-     * @return EE_Messages_Template_Pack
298
-     */
299
-    public static function get_template_pack($template_pack_name)
300
-    {
301
-        EE_Registry::instance()->load_helper('MSG_Template');
302
-        return EEH_MSG_Template::get_template_pack($template_pack_name);
303
-    }
304
-
305
-
306
-    /**
307
-     * Retrieves an array of all template packs.
308
-     * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
309
-     *
310
-     * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
311
-     * @return EE_Messages_Template_Pack[]
312
-     */
313
-    public static function get_template_packs()
314
-    {
315
-        EE_Registry::instance()->load_helper('MSG_Template');
316
-
317
-        //for backward compat, let's make sure this returns in the same format as originally.
318
-        $template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
319
-        $template_pack_collection->rewind();
320
-        $template_packs = array();
321
-        while ($template_pack_collection->valid()) {
322
-            $template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
323
-            $template_pack_collection->next();
324
-        }
325
-        return $template_packs;
326
-    }
327
-
328
-
329
-    /**
330
-     * This simply makes sure the autoloaders are registered for the EE_messages system.
331
-     *
332
-     * @since 4.5.0
333
-     * @return void
334
-     */
335
-    public static function set_autoloaders()
336
-    {
337
-        if (empty(self::$_MSG_PATHS)) {
338
-            self::_set_messages_paths();
339
-            foreach (self::$_MSG_PATHS as $path) {
340
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
341
-            }
342
-            // add aliases
343
-            EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
344
-            EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
345
-        }
346
-    }
347
-
348
-
349
-    /**
350
-     * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
351
-     * for use by the Messages Autoloaders
352
-     *
353
-     * @since 4.5.0
354
-     * @return void.
355
-     */
356
-    protected static function _set_messages_paths()
357
-    {
358
-        $dir_ref = array(
359
-            'messages/message_type',
360
-            'messages/messenger',
361
-            'messages/defaults',
362
-            'messages/defaults/email',
363
-            'messages/data_class',
364
-            'messages/validators',
365
-            'messages/validators/email',
366
-            'messages/validators/html',
367
-            'shortcodes',
368
-        );
369
-        $paths   = array();
370
-        foreach ($dir_ref as $index => $dir) {
371
-            $paths[$index] = EE_LIBRARIES . $dir;
372
-        }
373
-        self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
374
-    }
375
-
376
-
377
-    /**
378
-     * Takes care of loading dependencies
379
-     *
380
-     * @since 4.5.0
381
-     * @return void
382
-     */
383
-    protected static function _load_controller()
384
-    {
385
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
386
-            EE_Registry::instance()->load_core('Request_Handler');
387
-            self::set_autoloaders();
388
-            self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
389
-            self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
390
-            self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
391
-        }
392
-    }
393
-
394
-
395
-    /**
396
-     * @param EE_Transaction $transaction
397
-     */
398
-    public static function payment_reminder(EE_Transaction $transaction)
399
-    {
400
-        self::_load_controller();
401
-        $data = array($transaction, null);
402
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
403
-    }
404
-
405
-
406
-    /**
407
-     * Any messages triggers for after successful gateway payments should go in here.
408
-     *
409
-     * @param  EE_Transaction object
410
-     * @param  EE_Payment     object
411
-     * @return void
412
-     */
413
-    public static function payment(EE_Transaction $transaction, EE_Payment $payment)
414
-    {
415
-        self::_load_controller();
416
-        $data = array($transaction, $payment);
417
-        EE_Registry::instance()->load_helper('MSG_Template');
418
-        $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
419
-        //if payment amount is less than 0 then switch to payment_refund message type.
420
-        $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
421
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
422
-    }
423
-
424
-
425
-    /**
426
-     * @param EE_Transaction $transaction
427
-     */
428
-    public static function cancelled_registration(EE_Transaction $transaction)
429
-    {
430
-        self::_load_controller();
431
-        $data = array($transaction, null);
432
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
433
-    }
434
-
435
-
436
-    /**
437
-     * Trigger for Registration messages
438
-     * Note that what registration message type is sent depends on what the reg status is for the registrations on the
439
-     * incoming transaction.
440
-     *
441
-     * @param EE_Registration $registration
442
-     * @param array           $extra_details
443
-     * @return void
444
-     */
445
-    public static function maybe_registration(EE_Registration $registration, $extra_details = array())
446
-    {
447
-
448
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
449
-            //no messages please
450
-            return;
451
-        }
452
-
453
-
454
-        //get all registrations so we make sure we send messages for the right status.
455
-        $all_registrations = $registration->transaction()->registrations();
456
-
457
-        //cached array of statuses so we only trigger messages once per status.
458
-        $statuses_sent = array();
459
-        self::_load_controller();
460
-        $mtgs = array();
461
-
462
-        //loop through registrations and trigger messages once per status.
463
-        foreach ($all_registrations as $reg) {
464
-
465
-            //already triggered?
466
-            if (in_array($reg->status_ID(), $statuses_sent)) {
467
-                continue;
468
-            }
469
-
470
-            $message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
471
-            $mtgs            = array_merge(
472
-                    $mtgs,
473
-                    self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
474
-                            $message_type,
475
-                            array($registration->transaction(), null, $reg->status_ID())
476
-                    )
477
-            );
478
-            $statuses_sent[] = $reg->status_ID();
479
-        }
480
-
481
-        if (count($statuses_sent) > 1) {
482
-            $mtgs = array_merge(
483
-                $mtgs,
484
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
485
-                    'registration_summary',
486
-                    array($registration->transaction(), null)
487
-                )
488
-            );
489
-        }
490
-
491
-        //batch queue and initiate request
492
-        self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
493
-        self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
494
-    }
495
-
496
-
497
-    /**
498
-     * This is a helper method used to very whether a registration notification should be sent or
499
-     * not.  Prevents duplicate notifications going out for registration context notifications.
500
-     *
501
-     * @param EE_Registration $registration  [description]
502
-     * @param array           $extra_details [description]
503
-     * @return bool          true = send away, false = nope halt the presses.
504
-     */
505
-    protected static function _verify_registration_notification_send(
506
-        EE_Registration $registration,
507
-        $extra_details = array()
508
-    ) {
509
-        //self::log(
510
-        //	__CLASS__, __FUNCTION__, __LINE__,
511
-        //	$registration->transaction(),
512
-        //	array( '$extra_details' => $extra_details )
513
-        //);
514
-        // currently only using this to send messages for the primary registrant
515
-        if (! $registration->is_primary_registrant()) {
516
-            return false;
517
-        }
518
-        // first we check if we're in admin and not doing front ajax
519
-        if (is_admin() && ! EE_FRONT_AJAX) {
520
-            //make sure appropriate admin params are set for sending messages
521
-            if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
522
-                //no messages sent please.
523
-                return false;
524
-            }
525
-        } else {
526
-            // frontend request (either regular or via AJAX)
527
-            // TXN is NOT finalized ?
528
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
529
-                return false;
530
-            }
531
-            // return visit but nothing changed ???
532
-            if (
533
-                isset($extra_details['revisit'], $extra_details['status_updates']) &&
534
-                $extra_details['revisit'] && ! $extra_details['status_updates']
535
-            ) {
536
-                return false;
537
-            }
538
-            // NOT sending messages && reg status is something other than "Not-Approved"
539
-            if (
540
-                ! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
541
-                $registration->status_ID() !== EEM_Registration::status_id_not_approved
542
-            ) {
543
-                return false;
544
-            }
545
-        }
546
-        // release the kraken
547
-        return true;
548
-    }
549
-
550
-
551
-    /**
552
-     * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
553
-     * status id.
554
-     *
555
-     * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
556
-     *                    or EEH_MSG_Template::convert_reg_status_to_message_type
557
-     * @param string $reg_status
558
-     * @return array
559
-     */
560
-    protected static function _get_reg_status_array($reg_status = '')
561
-    {
562
-        EE_Registry::instance()->load_helper('MSG_Template');
563
-        return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
564
-            ? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
565
-            : EEH_MSG_Template::reg_status_to_message_type_array();
566
-    }
567
-
568
-
569
-    /**
570
-     * Simply returns the payment message type for the given payment status.
571
-     *
572
-     * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
573
-     *                   or EEH_MSG_Template::convert_payment_status_to_message_type
574
-     * @param string $payment_status The payment status being matched.
575
-     * @return string|bool The payment message type slug matching the status or false if no match.
576
-     */
577
-    protected static function _get_payment_message_type($payment_status)
578
-    {
579
-        EE_Registry::instance()->load_helper('MSG_Template');
580
-        return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
581
-            ? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
582
-            : false;
583
-    }
584
-
585
-
586
-    /**
587
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
588
-     *
589
-     * @access public
590
-     * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
591
-     * @return bool          success/fail
592
-     */
593
-    public static function process_resend($req_data)
594
-    {
595
-        self::_load_controller();
596
-
597
-        //if $msgID in this request then skip to the new resend_message
598
-        if (EE_Registry::instance()->REQ->get('MSG_ID')) {
599
-            return self::resend_message();
600
-        }
601
-
602
-        //make sure any incoming request data is set on the REQ so that it gets picked up later.
603
-        $req_data = (array)$req_data;
604
-        foreach ($req_data as $request_key => $request_value) {
605
-            EE_Registry::instance()->REQ->set($request_key, $request_value);
606
-        }
607
-
608
-        if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
609
-            return false;
610
-        }
611
-
612
-        try {
613
-            self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
614
-            self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
615
-        } catch (EE_Error $e) {
616
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
617
-            return false;
618
-        }
619
-        EE_Error::add_success(
620
-            __('Messages have been successfully queued for generation and sending.', 'event_espresso')
621
-        );
622
-        return true; //everything got queued.
623
-    }
624
-
625
-
626
-    /**
627
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
628
-     *
629
-     * @return bool
630
-     */
631
-    public static function resend_message()
632
-    {
633
-        self::_load_controller();
634
-
635
-        $msgID = EE_Registry::instance()->REQ->get('MSG_ID');
636
-        if (! $msgID) {
637
-            EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
638
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
639
-            return false;
640
-        }
641
-
642
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
643
-
644
-        //setup success message.
645
-        $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
646
-        EE_Error::add_success(sprintf(
647
-            _n(
648
-                'There was %d message queued for resending.',
649
-                'There were %d messages queued for resending.',
650
-                $count_ready_for_resend,
651
-                'event_espresso'
652
-            ),
653
-            $count_ready_for_resend
654
-        ));
655
-        return true;
656
-    }
657
-
658
-
659
-    /**
660
-     * Message triggers for manual payment applied by admin
661
-     *
662
-     * @param  EE_Payment $payment EE_payment object
663
-     * @return bool              success/fail
664
-     */
665
-    public static function process_admin_payment(EE_Payment $payment)
666
-    {
667
-        EE_Registry::instance()->load_helper('MSG_Template');
668
-        //we need to get the transaction object
669
-        $transaction = $payment->transaction();
670
-        if ($transaction instanceof EE_Transaction) {
671
-            $data         = array($transaction, $payment);
672
-            $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
673
-
674
-            //if payment amount is less than 0 then switch to payment_refund message type.
675
-            $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
676
-
677
-            //if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
678
-            $message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
679
-
680
-            self::_load_controller();
681
-
682
-            self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
683
-
684
-            //get count of queued for generation
685
-            $count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
686
-                EEM_Message::status_incomplete,
687
-                EEM_Message::status_idle,
688
-            ));
689
-
690
-            if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
691
-                add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
692
-                return true;
693
-            } else {
694
-                $count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
695
-                /**
696
-                 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
697
-                 * IMMEDIATE generation.
698
-                 */
699
-                if ($count_failed > 0) {
700
-                    EE_Error::add_error(sprintf(
701
-                        _n(
702
-                            'The payment notification generation failed.',
703
-                            '%d payment notifications failed being sent.',
704
-                            $count_failed,
705
-                            'event_espresso'
706
-                        ),
707
-                        $count_failed
708
-                    ), __FILE__, __FUNCTION__, __LINE__);
709
-
710
-                    return false;
711
-                } else {
712
-                    add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
713
-                    return true;
714
-                }
715
-            }
716
-        } else {
717
-            EE_Error::add_error(
718
-                'Unable to generate the payment notification because the given value for the transaction is invalid.',
719
-                'event_espresso'
720
-            );
721
-            return false;
722
-        }
723
-    }
724
-
725
-
726
-    /**
727
-     * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
728
-     *
729
-     * @since   4.3.0
730
-     * @param  EE_Registration[] $registrations an array of EE_Registration objects
731
-     * @param  int               $grp_id        a specific message template group id.
732
-     * @return void
733
-     */
734
-    public static function send_newsletter_message($registrations, $grp_id)
735
-    {
736
-        //make sure mtp is id and set it in the EE_Request Handler later messages setup.
737
-        EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
738
-        self::_load_controller();
739
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
740
-    }
741
-
742
-
743
-    /**
744
-     * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
745
-     *
746
-     * @since   4.3.0
747
-     * @param    string          $registration_message_trigger_url
748
-     * @param    EE_Registration $registration
749
-     * @param string             $messenger
750
-     * @param string             $message_type
751
-     * @return    string
752
-     */
753
-    public static function registration_message_trigger_url(
754
-        $registration_message_trigger_url,
755
-        EE_Registration $registration,
756
-        $messenger = 'html',
757
-        $message_type = 'invoice'
758
-    ) {
759
-        // whitelist $messenger
760
-        switch ($messenger) {
761
-            case 'pdf' :
762
-                $sending_messenger    = 'pdf';
763
-                $generating_messenger = 'html';
764
-                break;
765
-            case 'html' :
766
-            default :
767
-                $sending_messenger    = 'html';
768
-                $generating_messenger = 'html';
769
-                break;
770
-        }
771
-        // whitelist $message_type
772
-        switch ($message_type) {
773
-            case 'receipt' :
774
-                $message_type = 'receipt';
775
-                break;
776
-            case 'invoice' :
777
-            default :
778
-                $message_type = 'invoice';
779
-                break;
780
-        }
781
-        // verify that both the messenger AND the message type are active
782
-        if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
783
-            //need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
784
-            $template_query_params = array(
785
-                'MTP_is_active'    => true,
786
-                'MTP_messenger'    => $generating_messenger,
787
-                'MTP_message_type' => $message_type,
788
-                'Event.EVT_ID'     => $registration->event_ID(),
789
-            );
790
-            //get the message template group.
791
-            $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
792
-            //if we don't have an EE_Message_Template_Group then return
793
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
794
-                // remove EVT_ID from query params so that global templates get picked up
795
-                unset($template_query_params['Event.EVT_ID']);
796
-                //get global template as the fallback
797
-                $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
798
-            }
799
-            //if we don't have an EE_Message_Template_Group then return
800
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
801
-                return '';
802
-            }
803
-            // generate the URL
804
-            $registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
805
-                $sending_messenger,
806
-                $generating_messenger,
807
-                'purchaser',
808
-                $message_type,
809
-                $registration,
810
-                $msg_template_group->ID(),
811
-                $registration->transaction_ID()
812
-            );
813
-
814
-        }
815
-        return $registration_message_trigger_url;
816
-    }
817
-
818
-
819
-    /**
820
-     * Use to generate and return a message preview!
821
-     *
822
-     * @param  string $type      This should correspond with a valid message type
823
-     * @param  string $context   This should correspond with a valid context for the message type
824
-     * @param  string $messenger This should correspond with a valid messenger.
825
-     * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
826
-     *                           preview
827
-     * @return bool|string The body of the message or if send is requested, sends.
828
-     * @throws EE_Error
829
-     */
830
-    public static function preview_message($type, $context, $messenger, $send = false)
831
-    {
832
-        self::_load_controller();
833
-        $mtg                     = new EE_Message_To_Generate(
834
-            $messenger,
835
-            $type,
836
-            array(),
837
-            $context,
838
-            true
839
-        );
840
-        $generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
841
-        if ($generated_preview_queue instanceof EE_Messages_Queue) {
842
-            $content = $generated_preview_queue->get_message_repository()->current()->content();
843
-            //if the current message was persisted to the db (which will happen with any extra fields on a message) then
844
-            //let's delete it because we don't need previews cluttering up the db.
845
-            if ($generated_preview_queue->get_message_repository()->current()->ID() > 0
846
-                && $generated_preview_queue->get_message_repository()->current()->STS_ID() !== EEM_Message::status_failed
847
-            ) {
848
-                $generated_preview_queue->get_message_repository()->delete();
849
-            }
850
-            return $content;
851
-        } else {
852
-            return $generated_preview_queue;
853
-        }
854
-    }
855
-
856
-
857
-    /**
858
-     * This is a method that allows for sending a message using a messenger matching the string given and the provided
859
-     * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
860
-     * content found in the EE_Message objects in the queue.
861
-     *
862
-     * @since 4.9.0
863
-     * @param string            $messenger            a string matching a valid active messenger in the system
864
-     * @param string            $message_type         Although it seems contrary to the name of the method, a message
865
-     *                                                type name is still required to send along the message type to the
866
-     *                                                messenger because this is used for determining what specific
867
-     *                                                variations might be loaded for the generated message.
868
-     * @param EE_Messages_Queue $queue
869
-     * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
870
-     *                                                aggregate EE_Message object.
871
-     * @return bool          success or fail.
872
-     */
873
-    public static function send_message_with_messenger_only(
874
-        $messenger,
875
-        $message_type,
876
-        EE_Messages_Queue $queue,
877
-        $custom_subject = ''
878
-    ) {
879
-        self::_load_controller();
880
-        /** @type EE_Message_To_Generate_From_Queue $message_to_generate */
881
-        $message_to_generate = EE_Registry::instance()->load_lib(
882
-            'Message_To_Generate_From_Queue',
883
-            array(
884
-                $messenger,
885
-                $message_type,
886
-                $queue,
887
-                $custom_subject,
888
-            )
889
-        );
890
-        return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
891
-    }
892
-
893
-
894
-    /**
895
-     * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
896
-     *
897
-     * @since 4.9.0
898
-     * @param array $message_ids An array of message ids
899
-     * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
900
-     *              messages.
901
-     */
902
-    public static function generate_now($message_ids)
903
-    {
904
-        self::_load_controller();
905
-        $messages        = EEM_Message::instance()->get_all(
906
-            array(
907
-                0 => array(
908
-                    'MSG_ID' => array('IN', $message_ids),
909
-                    'STS_ID' => EEM_Message::status_incomplete,
910
-                ),
911
-            )
912
-        );
913
-        $generated_queue = false;
914
-        if ($messages) {
915
-            $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
916
-        }
917
-
918
-        if (! $generated_queue instanceof EE_Messages_Queue) {
919
-            EE_Error::add_error(
920
-                __('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
921
-                    'event_espresso'),
922
-                __FILE__, __FUNCTION__, __LINE__
923
-            );
924
-        }
925
-        return $generated_queue;
926
-    }
927
-
928
-
929
-    /**
930
-     * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
931
-     * EEM_Message::status_idle
932
-     *
933
-     * @since 4.9.0
934
-     * @param $message_ids
935
-     * @return bool | EE_Messages_Queue  false if no messages sent.
936
-     */
937
-    public static function send_now($message_ids)
938
-    {
939
-        self::_load_controller();
940
-        $messages   = EEM_Message::instance()->get_all(
941
-            array(
942
-                0 => array(
943
-                    'MSG_ID' => array('IN', $message_ids),
944
-                    'STS_ID' => array(
945
-                        'IN',
946
-                        array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
947
-                    ),
948
-                ),
949
-            )
950
-        );
951
-        $sent_queue = false;
952
-        if ($messages) {
953
-            $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
954
-        }
955
-
956
-        if (! $sent_queue instanceof EE_Messages_Queue) {
957
-            EE_Error::add_error(
958
-                __('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
959
-                    'event_espresso'),
960
-                __FILE__, __FUNCTION__, __LINE__
961
-            );
962
-        } else {
963
-            //can count how many sent by using the messages in the queue
964
-            $sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
965
-            if ($sent_count > 0) {
966
-                EE_Error::add_success(
967
-                    sprintf(
968
-                        _n(
969
-                            'There was %d message successfully sent.',
970
-                            'There were %d messages successfully sent.',
971
-                            $sent_count,
972
-                            'event_espresso'
973
-                        ),
974
-                        $sent_count
975
-                    )
976
-                );
977
-            } else {
978
-                EE_Error::overwrite_errors();
979
-                EE_Error::add_error(
980
-                    __('No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
201
+				exit;
202
+			}
203
+		}
204
+		return;
205
+	}
206
+
207
+
208
+	/**
209
+	 *  This runs when the msg_url_trigger route has initiated.
210
+	 *
211
+	 * @since 4.5.0
212
+	 * @param WP $WP
213
+	 * @throws EE_Error
214
+	 * @return    void
215
+	 */
216
+	public function run($WP)
217
+	{
218
+		//ensure controller is loaded
219
+		self::_load_controller();
220
+		// attempt to process message
221
+		try {
222
+			/** @type EE_Message_To_Generate_From_Request $message_to_generate */
223
+			$message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
224
+			self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
225
+		} catch (EE_Error $e) {
226
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
227
+				'event_espresso');
228
+			// add specific message for developers if WP_DEBUG in on
229
+			$error_msg .= '||' . $e->getMessage();
230
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
231
+		}
232
+	}
233
+
234
+
235
+	/**
236
+	 * This is triggered by the 'msg_cron_trigger' route.
237
+	 *
238
+	 * @param WP $WP
239
+	 */
240
+	public function execute_batch_request($WP)
241
+	{
242
+		$this->run_cron();
243
+		header('HTTP/1.1 200 OK');
244
+		exit();
245
+	}
246
+
247
+
248
+	/**
249
+	 * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
250
+	 * request.
251
+	 */
252
+	public function run_cron()
253
+	{
254
+		self::_load_controller();
255
+		//get required vars
256
+		$cron_type     = EE_Registry::instance()->REQ->get('type');
257
+		$transient_key = EE_Registry::instance()->REQ->get('key');
258
+
259
+		//now let's verify transient, if not valid exit immediately
260
+		if (! get_transient($transient_key)) {
261
+			/**
262
+			 * trigger error so this gets in the error logs.  This is important because it happens on a non-user request.
263
+			 */
264
+			trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
265
+		}
266
+
267
+		//if made it here, lets' delete the transient to keep the db clean
268
+		delete_transient($transient_key);
269
+
270
+		if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
271
+
272
+			$method = 'batch_' . $cron_type . '_from_queue';
273
+			if (method_exists(self::$_MSG_PROCESSOR, $method)) {
274
+				self::$_MSG_PROCESSOR->$method();
275
+			} else {
276
+				//no matching task
277
+				/**
278
+				 * trigger error so this gets in the error logs.  This is important because it happens on a non user request.
279
+				 */
280
+				trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
281
+					$cron_type)));
282
+			}
283
+		}
284
+
285
+		do_action('FHEE__EED_Messages__run_cron__end');
286
+	}
287
+
288
+
289
+	/**
290
+	 * This is used to retrieve the template pack for the given name.
291
+	 * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
292
+	 * the default template pack is returned.
293
+	 *
294
+	 * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
295
+	 * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
296
+	 *                                   in generating the Pack class name).
297
+	 * @return EE_Messages_Template_Pack
298
+	 */
299
+	public static function get_template_pack($template_pack_name)
300
+	{
301
+		EE_Registry::instance()->load_helper('MSG_Template');
302
+		return EEH_MSG_Template::get_template_pack($template_pack_name);
303
+	}
304
+
305
+
306
+	/**
307
+	 * Retrieves an array of all template packs.
308
+	 * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
309
+	 *
310
+	 * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
311
+	 * @return EE_Messages_Template_Pack[]
312
+	 */
313
+	public static function get_template_packs()
314
+	{
315
+		EE_Registry::instance()->load_helper('MSG_Template');
316
+
317
+		//for backward compat, let's make sure this returns in the same format as originally.
318
+		$template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
319
+		$template_pack_collection->rewind();
320
+		$template_packs = array();
321
+		while ($template_pack_collection->valid()) {
322
+			$template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
323
+			$template_pack_collection->next();
324
+		}
325
+		return $template_packs;
326
+	}
327
+
328
+
329
+	/**
330
+	 * This simply makes sure the autoloaders are registered for the EE_messages system.
331
+	 *
332
+	 * @since 4.5.0
333
+	 * @return void
334
+	 */
335
+	public static function set_autoloaders()
336
+	{
337
+		if (empty(self::$_MSG_PATHS)) {
338
+			self::_set_messages_paths();
339
+			foreach (self::$_MSG_PATHS as $path) {
340
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
341
+			}
342
+			// add aliases
343
+			EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
344
+			EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
345
+		}
346
+	}
347
+
348
+
349
+	/**
350
+	 * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
351
+	 * for use by the Messages Autoloaders
352
+	 *
353
+	 * @since 4.5.0
354
+	 * @return void.
355
+	 */
356
+	protected static function _set_messages_paths()
357
+	{
358
+		$dir_ref = array(
359
+			'messages/message_type',
360
+			'messages/messenger',
361
+			'messages/defaults',
362
+			'messages/defaults/email',
363
+			'messages/data_class',
364
+			'messages/validators',
365
+			'messages/validators/email',
366
+			'messages/validators/html',
367
+			'shortcodes',
368
+		);
369
+		$paths   = array();
370
+		foreach ($dir_ref as $index => $dir) {
371
+			$paths[$index] = EE_LIBRARIES . $dir;
372
+		}
373
+		self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
374
+	}
375
+
376
+
377
+	/**
378
+	 * Takes care of loading dependencies
379
+	 *
380
+	 * @since 4.5.0
381
+	 * @return void
382
+	 */
383
+	protected static function _load_controller()
384
+	{
385
+		if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
386
+			EE_Registry::instance()->load_core('Request_Handler');
387
+			self::set_autoloaders();
388
+			self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
389
+			self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
390
+			self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
391
+		}
392
+	}
393
+
394
+
395
+	/**
396
+	 * @param EE_Transaction $transaction
397
+	 */
398
+	public static function payment_reminder(EE_Transaction $transaction)
399
+	{
400
+		self::_load_controller();
401
+		$data = array($transaction, null);
402
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
403
+	}
404
+
405
+
406
+	/**
407
+	 * Any messages triggers for after successful gateway payments should go in here.
408
+	 *
409
+	 * @param  EE_Transaction object
410
+	 * @param  EE_Payment     object
411
+	 * @return void
412
+	 */
413
+	public static function payment(EE_Transaction $transaction, EE_Payment $payment)
414
+	{
415
+		self::_load_controller();
416
+		$data = array($transaction, $payment);
417
+		EE_Registry::instance()->load_helper('MSG_Template');
418
+		$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
419
+		//if payment amount is less than 0 then switch to payment_refund message type.
420
+		$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
421
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
422
+	}
423
+
424
+
425
+	/**
426
+	 * @param EE_Transaction $transaction
427
+	 */
428
+	public static function cancelled_registration(EE_Transaction $transaction)
429
+	{
430
+		self::_load_controller();
431
+		$data = array($transaction, null);
432
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
433
+	}
434
+
435
+
436
+	/**
437
+	 * Trigger for Registration messages
438
+	 * Note that what registration message type is sent depends on what the reg status is for the registrations on the
439
+	 * incoming transaction.
440
+	 *
441
+	 * @param EE_Registration $registration
442
+	 * @param array           $extra_details
443
+	 * @return void
444
+	 */
445
+	public static function maybe_registration(EE_Registration $registration, $extra_details = array())
446
+	{
447
+
448
+		if (! self::_verify_registration_notification_send($registration, $extra_details)) {
449
+			//no messages please
450
+			return;
451
+		}
452
+
453
+
454
+		//get all registrations so we make sure we send messages for the right status.
455
+		$all_registrations = $registration->transaction()->registrations();
456
+
457
+		//cached array of statuses so we only trigger messages once per status.
458
+		$statuses_sent = array();
459
+		self::_load_controller();
460
+		$mtgs = array();
461
+
462
+		//loop through registrations and trigger messages once per status.
463
+		foreach ($all_registrations as $reg) {
464
+
465
+			//already triggered?
466
+			if (in_array($reg->status_ID(), $statuses_sent)) {
467
+				continue;
468
+			}
469
+
470
+			$message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
471
+			$mtgs            = array_merge(
472
+					$mtgs,
473
+					self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
474
+							$message_type,
475
+							array($registration->transaction(), null, $reg->status_ID())
476
+					)
477
+			);
478
+			$statuses_sent[] = $reg->status_ID();
479
+		}
480
+
481
+		if (count($statuses_sent) > 1) {
482
+			$mtgs = array_merge(
483
+				$mtgs,
484
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
485
+					'registration_summary',
486
+					array($registration->transaction(), null)
487
+				)
488
+			);
489
+		}
490
+
491
+		//batch queue and initiate request
492
+		self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
493
+		self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
494
+	}
495
+
496
+
497
+	/**
498
+	 * This is a helper method used to very whether a registration notification should be sent or
499
+	 * not.  Prevents duplicate notifications going out for registration context notifications.
500
+	 *
501
+	 * @param EE_Registration $registration  [description]
502
+	 * @param array           $extra_details [description]
503
+	 * @return bool          true = send away, false = nope halt the presses.
504
+	 */
505
+	protected static function _verify_registration_notification_send(
506
+		EE_Registration $registration,
507
+		$extra_details = array()
508
+	) {
509
+		//self::log(
510
+		//	__CLASS__, __FUNCTION__, __LINE__,
511
+		//	$registration->transaction(),
512
+		//	array( '$extra_details' => $extra_details )
513
+		//);
514
+		// currently only using this to send messages for the primary registrant
515
+		if (! $registration->is_primary_registrant()) {
516
+			return false;
517
+		}
518
+		// first we check if we're in admin and not doing front ajax
519
+		if (is_admin() && ! EE_FRONT_AJAX) {
520
+			//make sure appropriate admin params are set for sending messages
521
+			if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
522
+				//no messages sent please.
523
+				return false;
524
+			}
525
+		} else {
526
+			// frontend request (either regular or via AJAX)
527
+			// TXN is NOT finalized ?
528
+			if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
529
+				return false;
530
+			}
531
+			// return visit but nothing changed ???
532
+			if (
533
+				isset($extra_details['revisit'], $extra_details['status_updates']) &&
534
+				$extra_details['revisit'] && ! $extra_details['status_updates']
535
+			) {
536
+				return false;
537
+			}
538
+			// NOT sending messages && reg status is something other than "Not-Approved"
539
+			if (
540
+				! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
541
+				$registration->status_ID() !== EEM_Registration::status_id_not_approved
542
+			) {
543
+				return false;
544
+			}
545
+		}
546
+		// release the kraken
547
+		return true;
548
+	}
549
+
550
+
551
+	/**
552
+	 * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
553
+	 * status id.
554
+	 *
555
+	 * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
556
+	 *                    or EEH_MSG_Template::convert_reg_status_to_message_type
557
+	 * @param string $reg_status
558
+	 * @return array
559
+	 */
560
+	protected static function _get_reg_status_array($reg_status = '')
561
+	{
562
+		EE_Registry::instance()->load_helper('MSG_Template');
563
+		return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
564
+			? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
565
+			: EEH_MSG_Template::reg_status_to_message_type_array();
566
+	}
567
+
568
+
569
+	/**
570
+	 * Simply returns the payment message type for the given payment status.
571
+	 *
572
+	 * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
573
+	 *                   or EEH_MSG_Template::convert_payment_status_to_message_type
574
+	 * @param string $payment_status The payment status being matched.
575
+	 * @return string|bool The payment message type slug matching the status or false if no match.
576
+	 */
577
+	protected static function _get_payment_message_type($payment_status)
578
+	{
579
+		EE_Registry::instance()->load_helper('MSG_Template');
580
+		return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
581
+			? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
582
+			: false;
583
+	}
584
+
585
+
586
+	/**
587
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
588
+	 *
589
+	 * @access public
590
+	 * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
591
+	 * @return bool          success/fail
592
+	 */
593
+	public static function process_resend($req_data)
594
+	{
595
+		self::_load_controller();
596
+
597
+		//if $msgID in this request then skip to the new resend_message
598
+		if (EE_Registry::instance()->REQ->get('MSG_ID')) {
599
+			return self::resend_message();
600
+		}
601
+
602
+		//make sure any incoming request data is set on the REQ so that it gets picked up later.
603
+		$req_data = (array)$req_data;
604
+		foreach ($req_data as $request_key => $request_value) {
605
+			EE_Registry::instance()->REQ->set($request_key, $request_value);
606
+		}
607
+
608
+		if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
609
+			return false;
610
+		}
611
+
612
+		try {
613
+			self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
614
+			self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
615
+		} catch (EE_Error $e) {
616
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
617
+			return false;
618
+		}
619
+		EE_Error::add_success(
620
+			__('Messages have been successfully queued for generation and sending.', 'event_espresso')
621
+		);
622
+		return true; //everything got queued.
623
+	}
624
+
625
+
626
+	/**
627
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
628
+	 *
629
+	 * @return bool
630
+	 */
631
+	public static function resend_message()
632
+	{
633
+		self::_load_controller();
634
+
635
+		$msgID = EE_Registry::instance()->REQ->get('MSG_ID');
636
+		if (! $msgID) {
637
+			EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
638
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
639
+			return false;
640
+		}
641
+
642
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
643
+
644
+		//setup success message.
645
+		$count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
646
+		EE_Error::add_success(sprintf(
647
+			_n(
648
+				'There was %d message queued for resending.',
649
+				'There were %d messages queued for resending.',
650
+				$count_ready_for_resend,
651
+				'event_espresso'
652
+			),
653
+			$count_ready_for_resend
654
+		));
655
+		return true;
656
+	}
657
+
658
+
659
+	/**
660
+	 * Message triggers for manual payment applied by admin
661
+	 *
662
+	 * @param  EE_Payment $payment EE_payment object
663
+	 * @return bool              success/fail
664
+	 */
665
+	public static function process_admin_payment(EE_Payment $payment)
666
+	{
667
+		EE_Registry::instance()->load_helper('MSG_Template');
668
+		//we need to get the transaction object
669
+		$transaction = $payment->transaction();
670
+		if ($transaction instanceof EE_Transaction) {
671
+			$data         = array($transaction, $payment);
672
+			$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
673
+
674
+			//if payment amount is less than 0 then switch to payment_refund message type.
675
+			$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
676
+
677
+			//if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
678
+			$message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
679
+
680
+			self::_load_controller();
681
+
682
+			self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
683
+
684
+			//get count of queued for generation
685
+			$count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
686
+				EEM_Message::status_incomplete,
687
+				EEM_Message::status_idle,
688
+			));
689
+
690
+			if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
691
+				add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
692
+				return true;
693
+			} else {
694
+				$count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
695
+				/**
696
+				 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
697
+				 * IMMEDIATE generation.
698
+				 */
699
+				if ($count_failed > 0) {
700
+					EE_Error::add_error(sprintf(
701
+						_n(
702
+							'The payment notification generation failed.',
703
+							'%d payment notifications failed being sent.',
704
+							$count_failed,
705
+							'event_espresso'
706
+						),
707
+						$count_failed
708
+					), __FILE__, __FUNCTION__, __LINE__);
709
+
710
+					return false;
711
+				} else {
712
+					add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
713
+					return true;
714
+				}
715
+			}
716
+		} else {
717
+			EE_Error::add_error(
718
+				'Unable to generate the payment notification because the given value for the transaction is invalid.',
719
+				'event_espresso'
720
+			);
721
+			return false;
722
+		}
723
+	}
724
+
725
+
726
+	/**
727
+	 * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
728
+	 *
729
+	 * @since   4.3.0
730
+	 * @param  EE_Registration[] $registrations an array of EE_Registration objects
731
+	 * @param  int               $grp_id        a specific message template group id.
732
+	 * @return void
733
+	 */
734
+	public static function send_newsletter_message($registrations, $grp_id)
735
+	{
736
+		//make sure mtp is id and set it in the EE_Request Handler later messages setup.
737
+		EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
738
+		self::_load_controller();
739
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
740
+	}
741
+
742
+
743
+	/**
744
+	 * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
745
+	 *
746
+	 * @since   4.3.0
747
+	 * @param    string          $registration_message_trigger_url
748
+	 * @param    EE_Registration $registration
749
+	 * @param string             $messenger
750
+	 * @param string             $message_type
751
+	 * @return    string
752
+	 */
753
+	public static function registration_message_trigger_url(
754
+		$registration_message_trigger_url,
755
+		EE_Registration $registration,
756
+		$messenger = 'html',
757
+		$message_type = 'invoice'
758
+	) {
759
+		// whitelist $messenger
760
+		switch ($messenger) {
761
+			case 'pdf' :
762
+				$sending_messenger    = 'pdf';
763
+				$generating_messenger = 'html';
764
+				break;
765
+			case 'html' :
766
+			default :
767
+				$sending_messenger    = 'html';
768
+				$generating_messenger = 'html';
769
+				break;
770
+		}
771
+		// whitelist $message_type
772
+		switch ($message_type) {
773
+			case 'receipt' :
774
+				$message_type = 'receipt';
775
+				break;
776
+			case 'invoice' :
777
+			default :
778
+				$message_type = 'invoice';
779
+				break;
780
+		}
781
+		// verify that both the messenger AND the message type are active
782
+		if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
783
+			//need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
784
+			$template_query_params = array(
785
+				'MTP_is_active'    => true,
786
+				'MTP_messenger'    => $generating_messenger,
787
+				'MTP_message_type' => $message_type,
788
+				'Event.EVT_ID'     => $registration->event_ID(),
789
+			);
790
+			//get the message template group.
791
+			$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
792
+			//if we don't have an EE_Message_Template_Group then return
793
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
794
+				// remove EVT_ID from query params so that global templates get picked up
795
+				unset($template_query_params['Event.EVT_ID']);
796
+				//get global template as the fallback
797
+				$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
798
+			}
799
+			//if we don't have an EE_Message_Template_Group then return
800
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
801
+				return '';
802
+			}
803
+			// generate the URL
804
+			$registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
805
+				$sending_messenger,
806
+				$generating_messenger,
807
+				'purchaser',
808
+				$message_type,
809
+				$registration,
810
+				$msg_template_group->ID(),
811
+				$registration->transaction_ID()
812
+			);
813
+
814
+		}
815
+		return $registration_message_trigger_url;
816
+	}
817
+
818
+
819
+	/**
820
+	 * Use to generate and return a message preview!
821
+	 *
822
+	 * @param  string $type      This should correspond with a valid message type
823
+	 * @param  string $context   This should correspond with a valid context for the message type
824
+	 * @param  string $messenger This should correspond with a valid messenger.
825
+	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
826
+	 *                           preview
827
+	 * @return bool|string The body of the message or if send is requested, sends.
828
+	 * @throws EE_Error
829
+	 */
830
+	public static function preview_message($type, $context, $messenger, $send = false)
831
+	{
832
+		self::_load_controller();
833
+		$mtg                     = new EE_Message_To_Generate(
834
+			$messenger,
835
+			$type,
836
+			array(),
837
+			$context,
838
+			true
839
+		);
840
+		$generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
841
+		if ($generated_preview_queue instanceof EE_Messages_Queue) {
842
+			$content = $generated_preview_queue->get_message_repository()->current()->content();
843
+			//if the current message was persisted to the db (which will happen with any extra fields on a message) then
844
+			//let's delete it because we don't need previews cluttering up the db.
845
+			if ($generated_preview_queue->get_message_repository()->current()->ID() > 0
846
+				&& $generated_preview_queue->get_message_repository()->current()->STS_ID() !== EEM_Message::status_failed
847
+			) {
848
+				$generated_preview_queue->get_message_repository()->delete();
849
+			}
850
+			return $content;
851
+		} else {
852
+			return $generated_preview_queue;
853
+		}
854
+	}
855
+
856
+
857
+	/**
858
+	 * This is a method that allows for sending a message using a messenger matching the string given and the provided
859
+	 * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
860
+	 * content found in the EE_Message objects in the queue.
861
+	 *
862
+	 * @since 4.9.0
863
+	 * @param string            $messenger            a string matching a valid active messenger in the system
864
+	 * @param string            $message_type         Although it seems contrary to the name of the method, a message
865
+	 *                                                type name is still required to send along the message type to the
866
+	 *                                                messenger because this is used for determining what specific
867
+	 *                                                variations might be loaded for the generated message.
868
+	 * @param EE_Messages_Queue $queue
869
+	 * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
870
+	 *                                                aggregate EE_Message object.
871
+	 * @return bool          success or fail.
872
+	 */
873
+	public static function send_message_with_messenger_only(
874
+		$messenger,
875
+		$message_type,
876
+		EE_Messages_Queue $queue,
877
+		$custom_subject = ''
878
+	) {
879
+		self::_load_controller();
880
+		/** @type EE_Message_To_Generate_From_Queue $message_to_generate */
881
+		$message_to_generate = EE_Registry::instance()->load_lib(
882
+			'Message_To_Generate_From_Queue',
883
+			array(
884
+				$messenger,
885
+				$message_type,
886
+				$queue,
887
+				$custom_subject,
888
+			)
889
+		);
890
+		return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
891
+	}
892
+
893
+
894
+	/**
895
+	 * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
896
+	 *
897
+	 * @since 4.9.0
898
+	 * @param array $message_ids An array of message ids
899
+	 * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
900
+	 *              messages.
901
+	 */
902
+	public static function generate_now($message_ids)
903
+	{
904
+		self::_load_controller();
905
+		$messages        = EEM_Message::instance()->get_all(
906
+			array(
907
+				0 => array(
908
+					'MSG_ID' => array('IN', $message_ids),
909
+					'STS_ID' => EEM_Message::status_incomplete,
910
+				),
911
+			)
912
+		);
913
+		$generated_queue = false;
914
+		if ($messages) {
915
+			$generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
916
+		}
917
+
918
+		if (! $generated_queue instanceof EE_Messages_Queue) {
919
+			EE_Error::add_error(
920
+				__('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
921
+					'event_espresso'),
922
+				__FILE__, __FUNCTION__, __LINE__
923
+			);
924
+		}
925
+		return $generated_queue;
926
+	}
927
+
928
+
929
+	/**
930
+	 * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
931
+	 * EEM_Message::status_idle
932
+	 *
933
+	 * @since 4.9.0
934
+	 * @param $message_ids
935
+	 * @return bool | EE_Messages_Queue  false if no messages sent.
936
+	 */
937
+	public static function send_now($message_ids)
938
+	{
939
+		self::_load_controller();
940
+		$messages   = EEM_Message::instance()->get_all(
941
+			array(
942
+				0 => array(
943
+					'MSG_ID' => array('IN', $message_ids),
944
+					'STS_ID' => array(
945
+						'IN',
946
+						array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
947
+					),
948
+				),
949
+			)
950
+		);
951
+		$sent_queue = false;
952
+		if ($messages) {
953
+			$sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
954
+		}
955
+
956
+		if (! $sent_queue instanceof EE_Messages_Queue) {
957
+			EE_Error::add_error(
958
+				__('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
959
+					'event_espresso'),
960
+				__FILE__, __FUNCTION__, __LINE__
961
+			);
962
+		} else {
963
+			//can count how many sent by using the messages in the queue
964
+			$sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
965
+			if ($sent_count > 0) {
966
+				EE_Error::add_success(
967
+					sprintf(
968
+						_n(
969
+							'There was %d message successfully sent.',
970
+							'There were %d messages successfully sent.',
971
+							$sent_count,
972
+							'event_espresso'
973
+						),
974
+						$sent_count
975
+					)
976
+				);
977
+			} else {
978
+				EE_Error::overwrite_errors();
979
+				EE_Error::add_error(
980
+					__('No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
981 981
 					If there was an error, you can look at the messages in the message activity list table for any error messages.',
982
-                        'event_espresso'),
983
-                    __FILE__, __FUNCTION__, __LINE__
984
-                );
985
-            }
986
-        }
987
-        return $sent_queue;
988
-    }
989
-
990
-
991
-    /**
992
-     * This will queue the incoming message ids for resending.
993
-     * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
994
-     *
995
-     * @since 4.9.0
996
-     * @param array $message_ids An array of EE_Message IDs
997
-     * @return bool  true means messages were successfully queued for resending, false means none were queued for
998
-     *               resending.
999
-     */
1000
-    public static function queue_for_resending($message_ids)
1001
-    {
1002
-        self::_load_controller();
1003
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1004
-
1005
-        //get queue and count
1006
-        $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1007
-
1008
-        if (
1009
-            $queue_count > 0
1010
-        ) {
1011
-            EE_Error::add_success(
1012
-                sprintf(
1013
-                    _n(
1014
-                        '%d message successfully queued for resending.',
1015
-                        '%d messages successfully queued for resending.',
1016
-                        $queue_count,
1017
-                        'event_espresso'
1018
-                    ),
1019
-                    $queue_count
1020
-                )
1021
-            );
1022
-            /**
1023
-             * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1024
-             */
1025
-        } elseif (
1026
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1027
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1028
-        ) {
1029
-            $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1030
-            if ($queue_count > 0) {
1031
-                EE_Error::add_success(
1032
-                    sprintf(
1033
-                        _n(
1034
-                            '%d message successfully sent.',
1035
-                            '%d messages successfully sent.',
1036
-                            $queue_count,
1037
-                            'event_espresso'
1038
-                        ),
1039
-                        $queue_count
1040
-                    )
1041
-                );
1042
-            } else {
1043
-                EE_Error::add_error(
1044
-                    __('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1045
-                        'event_espresso'),
1046
-                    __FILE__, __FUNCTION__, __LINE__
1047
-                );
1048
-            }
1049
-        } else {
1050
-            EE_Error::add_error(
1051
-                __('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1052
-                    'event_espresso'),
1053
-                __FILE__, __FUNCTION__, __LINE__
1054
-            );
1055
-        }
1056
-        return (bool)$queue_count;
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * debug
1062
-     *
1063
-     * @param string          $class
1064
-     * @param string          $func
1065
-     * @param string          $line
1066
-     * @param \EE_Transaction $transaction
1067
-     * @param array           $info
1068
-     * @param bool            $display_request
1069
-     */
1070
-    protected static function log(
1071
-        $class = '',
1072
-        $func = '',
1073
-        $line = '',
1074
-        EE_Transaction $transaction,
1075
-        $info = array(),
1076
-        $display_request = false
1077
-    ) {
1078
-        if (WP_DEBUG && false) {
1079
-            if ($transaction instanceof EE_Transaction) {
1080
-                // don't serialize objects
1081
-                $info                  = EEH_Debug_Tools::strip_objects($info);
1082
-                $info['TXN_status']    = $transaction->status_ID();
1083
-                $info['TXN_reg_steps'] = $transaction->reg_steps();
1084
-                if ($transaction->ID()) {
1085
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1086
-                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1087
-                }
1088
-            }
1089
-        }
1090
-
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     *  Resets all the static properties in this class when called.
1096
-     */
1097
-    public static function reset()
1098
-    {
1099
-        self::$_EEMSG                    = null;
1100
-        self::$_message_resource_manager = null;
1101
-        self::$_MSG_PROCESSOR            = null;
1102
-        self::$_MSG_PATHS                = null;
1103
-        self::$_TMP_PACKS                = array();
1104
-    }
982
+						'event_espresso'),
983
+					__FILE__, __FUNCTION__, __LINE__
984
+				);
985
+			}
986
+		}
987
+		return $sent_queue;
988
+	}
989
+
990
+
991
+	/**
992
+	 * This will queue the incoming message ids for resending.
993
+	 * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
994
+	 *
995
+	 * @since 4.9.0
996
+	 * @param array $message_ids An array of EE_Message IDs
997
+	 * @return bool  true means messages were successfully queued for resending, false means none were queued for
998
+	 *               resending.
999
+	 */
1000
+	public static function queue_for_resending($message_ids)
1001
+	{
1002
+		self::_load_controller();
1003
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1004
+
1005
+		//get queue and count
1006
+		$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1007
+
1008
+		if (
1009
+			$queue_count > 0
1010
+		) {
1011
+			EE_Error::add_success(
1012
+				sprintf(
1013
+					_n(
1014
+						'%d message successfully queued for resending.',
1015
+						'%d messages successfully queued for resending.',
1016
+						$queue_count,
1017
+						'event_espresso'
1018
+					),
1019
+					$queue_count
1020
+				)
1021
+			);
1022
+			/**
1023
+			 * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1024
+			 */
1025
+		} elseif (
1026
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1027
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1028
+		) {
1029
+			$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1030
+			if ($queue_count > 0) {
1031
+				EE_Error::add_success(
1032
+					sprintf(
1033
+						_n(
1034
+							'%d message successfully sent.',
1035
+							'%d messages successfully sent.',
1036
+							$queue_count,
1037
+							'event_espresso'
1038
+						),
1039
+						$queue_count
1040
+					)
1041
+				);
1042
+			} else {
1043
+				EE_Error::add_error(
1044
+					__('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1045
+						'event_espresso'),
1046
+					__FILE__, __FUNCTION__, __LINE__
1047
+				);
1048
+			}
1049
+		} else {
1050
+			EE_Error::add_error(
1051
+				__('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1052
+					'event_espresso'),
1053
+				__FILE__, __FUNCTION__, __LINE__
1054
+			);
1055
+		}
1056
+		return (bool)$queue_count;
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * debug
1062
+	 *
1063
+	 * @param string          $class
1064
+	 * @param string          $func
1065
+	 * @param string          $line
1066
+	 * @param \EE_Transaction $transaction
1067
+	 * @param array           $info
1068
+	 * @param bool            $display_request
1069
+	 */
1070
+	protected static function log(
1071
+		$class = '',
1072
+		$func = '',
1073
+		$line = '',
1074
+		EE_Transaction $transaction,
1075
+		$info = array(),
1076
+		$display_request = false
1077
+	) {
1078
+		if (WP_DEBUG && false) {
1079
+			if ($transaction instanceof EE_Transaction) {
1080
+				// don't serialize objects
1081
+				$info                  = EEH_Debug_Tools::strip_objects($info);
1082
+				$info['TXN_status']    = $transaction->status_ID();
1083
+				$info['TXN_reg_steps'] = $transaction->reg_steps();
1084
+				if ($transaction->ID()) {
1085
+					$index = 'EE_Transaction: ' . $transaction->ID();
1086
+					EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1087
+				}
1088
+			}
1089
+		}
1090
+
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 *  Resets all the static properties in this class when called.
1096
+	 */
1097
+	public static function reset()
1098
+	{
1099
+		self::$_EEMSG                    = null;
1100
+		self::$_message_resource_manager = null;
1101
+		self::$_MSG_PROCESSOR            = null;
1102
+		self::$_MSG_PATHS                = null;
1103
+		self::$_TMP_PACKS                = array();
1104
+	}
1105 1105
 
1106 1106
 }
1107 1107
 // End of file EED_Messages.module.php
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Processor.lib.php 1 patch
Spacing   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	 *
36 36
 	 * @param EE_Message_Resource_Manager $message_resource_manager
37 37
 	 */
38
-	public function __construct( EE_Message_Resource_Manager $message_resource_manager ) {
38
+	public function __construct(EE_Message_Resource_Manager $message_resource_manager) {
39 39
 		$this->_message_resource_manager = $message_resource_manager;
40 40
 		$this->_init_queue_and_generator();
41 41
 	}
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 	 * - $_generator = holds the messages generator
51 51
 	 */
52 52
 	protected function _init_queue_and_generator() {
53
-		$this->_generator = EE_Registry::factory( 'EE_Messages_Generator' );
53
+		$this->_generator = EE_Registry::factory('EE_Messages_Generator');
54 54
 		$this->_queue = $this->_generator->generation_queue();
55 55
 	}
56 56
 
@@ -75,31 +75,31 @@  discard block
 block discarded – undo
75 75
 	 * @param EE_Messages_Queue $queue_to_process
76 76
 	 * @return bool  true for success false for error.
77 77
 	 */
78
-	public function process_immediately_from_queue( EE_Messages_Queue $queue_to_process ) {
78
+	public function process_immediately_from_queue(EE_Messages_Queue $queue_to_process) {
79 79
 		$success = false;
80 80
 		$messages_to_send = array();
81 81
 		$messages_to_generate = array();
82 82
 		//loop through and setup the various messages from the queue so we know what is being processed
83 83
 		$queue_to_process->get_message_repository()->rewind();
84
-		foreach ( $queue_to_process->get_message_repository() as $message ) {
85
-			if ( $message->STS_ID() === EEM_Message::status_incomplete ) {
84
+		foreach ($queue_to_process->get_message_repository() as $message) {
85
+			if ($message->STS_ID() === EEM_Message::status_incomplete) {
86 86
 				$messages_to_generate[] = $message;
87 87
 				continue;
88 88
 			}
89 89
 
90
-			if ( in_array( $message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send() ) ) {
90
+			if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
91 91
 				$messages_to_send[] = $message;
92 92
 				continue;
93 93
 			}
94 94
 		}
95 95
 
96 96
 		//do generation/sends
97
-		if ( $messages_to_generate ) {
98
-			$success = $this->batch_generate_from_queue( $messages_to_generate, true );
97
+		if ($messages_to_generate) {
98
+			$success = $this->batch_generate_from_queue($messages_to_generate, true);
99 99
 		}
100 100
 
101
-		if ( $messages_to_send ) {
102
-			$sent = $this->batch_send_from_queue( $messages_to_send, true );
101
+		if ($messages_to_send) {
102
+			$sent = $this->batch_send_from_queue($messages_to_send, true);
103 103
 			//if there was messages to generate and it failed, then we override any success value for the sending process
104 104
 			//otherwise we just use the return from batch send.  The intent is that there is a simple response for success/fail.
105 105
 			//Either everything was successful or we consider it a fail.  To be clear, this is a limitation of doing
@@ -119,13 +119,13 @@  discard block
 block discarded – undo
119 119
 	 * @return bool|EE_Messages_Queue return false if nothing generated.  This returns a new EE_Message_Queue with
120 120
 	 *                                   generated messages.
121 121
 	 */
122
-	public function batch_generate_from_queue( $messages = array(), $clear_queue = false ) {
123
-		if ( $this->_build_queue_for_generation( $messages, $clear_queue ) ) {
122
+	public function batch_generate_from_queue($messages = array(), $clear_queue = false) {
123
+		if ($this->_build_queue_for_generation($messages, $clear_queue)) {
124 124
 			$new_queue = $this->_generator->generate();
125
-			if ( $new_queue instanceof EE_Messages_Queue ) {
125
+			if ($new_queue instanceof EE_Messages_Queue) {
126 126
 				//unlock queue
127 127
 				$this->_queue->unlock_queue();
128
-				$new_queue->initiate_request_by_priority( 'send' );
128
+				$new_queue->initiate_request_by_priority('send');
129 129
 				return $new_queue;
130 130
 			}
131 131
 		}
@@ -146,24 +146,24 @@  discard block
 block discarded – undo
146 146
 	 *
147 147
 	 * @return bool true means queue prepped, false means there was a lock so no generation please.
148 148
 	 */
149
-	protected function _build_queue_for_generation( $messages = array(), $clear_queue = false ) {
149
+	protected function _build_queue_for_generation($messages = array(), $clear_queue = false) {
150 150
 
151
-		if ( $clear_queue ) {
151
+		if ($clear_queue) {
152 152
 			$this->_init_queue_and_generator();
153 153
 		}
154 154
 
155
-		if ( $messages ) {
155
+		if ($messages) {
156 156
 			//if generation is locked then get out now because that means processing is already happening.
157
-			if ( $this->_queue->is_locked() ) {
157
+			if ($this->_queue->is_locked()) {
158 158
 				return false;
159 159
 			}
160 160
 
161 161
 			$this->_queue->lock_queue();
162
-			$messages = is_array( $messages ) ? $messages : array( $messages );
163
-			foreach ( $messages as $message ) {
164
-				if ( $message instanceof EE_Message ) {
162
+			$messages = is_array($messages) ? $messages : array($messages);
163
+			foreach ($messages as $message) {
164
+				if ($message instanceof EE_Message) {
165 165
 					$data = $message->all_extra_meta_array();
166
-					$this->_queue->add( $message, $data );
166
+					$this->_queue->add($message, $data);
167 167
 				}
168 168
 			}
169 169
 			return true;
@@ -181,22 +181,22 @@  discard block
 block discarded – undo
181 181
 	 *
182 182
 	 * @return bool true means queue prepped, false means there was a lock so no queue prepped.
183 183
 	 */
184
-	protected function _build_queue_for_sending( $messages, $clear_queue = false ) {
184
+	protected function _build_queue_for_sending($messages, $clear_queue = false) {
185 185
 		//if sending is locked then get out now because that means processing is already happening.
186
-		if ( $this->_queue->is_locked( EE_Messages_Queue::action_sending ) ) {
186
+		if ($this->_queue->is_locked(EE_Messages_Queue::action_sending)) {
187 187
 			return false;
188 188
 		}
189 189
 
190
-		$this->_queue->lock_queue( EE_Messages_Queue::action_sending );
190
+		$this->_queue->lock_queue(EE_Messages_Queue::action_sending);
191 191
 
192
-		if ( $clear_queue ) {
192
+		if ($clear_queue) {
193 193
 			$this->_init_queue_and_generator();
194 194
 		}
195 195
 
196
-		$messages = is_array( $messages ) ? $messages : array( $messages );
196
+		$messages = is_array($messages) ? $messages : array($messages);
197 197
 
198
-		foreach ( $messages as $message ) {
199
-			$this->_queue->add( $message );
198
+		foreach ($messages as $message) {
199
+			$this->_queue->add($message);
200 200
 		}
201 201
 		return true;
202 202
 	}
@@ -212,11 +212,11 @@  discard block
 block discarded – undo
212 212
 	 *
213 213
 	 * @return EE_Messages_Queue
214 214
 	 */
215
-	public function batch_send_from_queue( $messages = array(), $clear_queue = false ) {
215
+	public function batch_send_from_queue($messages = array(), $clear_queue = false) {
216 216
 
217
-		if ( $messages && $this->_build_queue_for_sending( $messages, $clear_queue ) ) {
217
+		if ($messages && $this->_build_queue_for_sending($messages, $clear_queue)) {
218 218
 			$this->_queue->execute();
219
-			$this->_queue->unlock_queue( EE_Messages_Queue::action_sending );
219
+			$this->_queue->unlock_queue(EE_Messages_Queue::action_sending);
220 220
 		} else {
221 221
 			//get messages to send and execute.
222 222
 			$this->_queue->get_to_send_batch_and_send();
@@ -239,10 +239,10 @@  discard block
 block discarded – undo
239 239
 	 * @param EE_Message_To_Generate[] $messages_to_generate
240 240
 	 * @return EE_Messages_Queue
241 241
 	 */
242
-	public function generate_and_return(  $messages_to_generate ) {
242
+	public function generate_and_return($messages_to_generate) {
243 243
 		$this->_init_queue_and_generator();
244
-		$this->_queue_for_generation_loop( $messages_to_generate );
245
-		return $this->_generator->generate( false );
244
+		$this->_queue_for_generation_loop($messages_to_generate);
245
+		return $this->_generator->generate(false);
246 246
 	}
247 247
 
248 248
 
@@ -253,8 +253,8 @@  discard block
 block discarded – undo
253 253
 	 * @param  bool     $persist    Indicate whether to instruct the generator to persist the generated queue (true) or not (false).
254 254
 	 * @return EE_Messages_Queue
255 255
 	 */
256
-	public function generate_queue( $persist = true ) {
257
-		return $this->_generator->generate( $persist );
256
+	public function generate_queue($persist = true) {
257
+		return $this->_generator->generate($persist);
258 258
 	}
259 259
 
260 260
 
@@ -267,9 +267,9 @@  discard block
 block discarded – undo
267 267
 	 * @param bool                   $test_send             Whether this item is for a test send or not.
268 268
 	 * @return  EE_Messages_Queue
269 269
 	 */
270
-	public function queue_for_generation( EE_Message_To_Generate $message_to_generate, $test_send = false ) {
271
-		if ( $message_to_generate->valid() ) {
272
-			$this->_generator->create_and_add_message_to_queue( $message_to_generate, $test_send );
270
+	public function queue_for_generation(EE_Message_To_Generate $message_to_generate, $test_send = false) {
271
+		if ($message_to_generate->valid()) {
272
+			$this->_generator->create_and_add_message_to_queue($message_to_generate, $test_send);
273 273
 		}
274 274
 	}
275 275
 
@@ -285,9 +285,9 @@  discard block
 block discarded – undo
285 285
 	 *
286 286
 	 * @param EE_Message_To_Generate[] $messages_to_generate
287 287
 	 */
288
-	public function batch_queue_for_generation_and_persist( $messages_to_generate ) {
288
+	public function batch_queue_for_generation_and_persist($messages_to_generate) {
289 289
 		$this->_init_queue_and_generator();
290
-		$this->_queue_for_generation_loop( $messages_to_generate );
290
+		$this->_queue_for_generation_loop($messages_to_generate);
291 291
 		$this->_queue->save();
292 292
 	}
293 293
 
@@ -303,9 +303,9 @@  discard block
 block discarded – undo
303 303
 	 *
304 304
 	 * @param EE_Message_To_Generate[]  $messages_to_generate
305 305
 	 */
306
-	public function batch_queue_for_generation_no_persist( $messages_to_generate ) {
306
+	public function batch_queue_for_generation_no_persist($messages_to_generate) {
307 307
 		$this->_init_queue_and_generator();
308
-		$this->_queue_for_generation_loop( $messages_to_generate );
308
+		$this->_queue_for_generation_loop($messages_to_generate);
309 309
 	}
310 310
 
311 311
 
@@ -317,15 +317,15 @@  discard block
 block discarded – undo
317 317
 	 *
318 318
 	 * @param EE_Message_To_Generate[] $messages_to_generate
319 319
 	 */
320
-	protected function _queue_for_generation_loop( $messages_to_generate ) {
320
+	protected function _queue_for_generation_loop($messages_to_generate) {
321 321
 		//make sure is in an array.
322
-		if ( ! is_array( $messages_to_generate ) ) {
323
-			$messages_to_generate = array( $messages_to_generate );
322
+		if ( ! is_array($messages_to_generate)) {
323
+			$messages_to_generate = array($messages_to_generate);
324 324
 		}
325 325
 
326
-		foreach ( $messages_to_generate as $message_to_generate ) {
327
-			if ( $message_to_generate instanceof EE_Message_To_Generate && $message_to_generate->valid() ) {
328
-				$this->queue_for_generation( $message_to_generate );
326
+		foreach ($messages_to_generate as $message_to_generate) {
327
+			if ($message_to_generate instanceof EE_Message_To_Generate && $message_to_generate->valid()) {
328
+				$this->queue_for_generation($message_to_generate);
329 329
 			}
330 330
 		}
331 331
 	}
@@ -340,10 +340,10 @@  discard block
 block discarded – undo
340 340
 	 * @param  EE_Message_To_Generate[]
341 341
 	 * @return EE_Messages_Queue
342 342
 	 */
343
-	public function generate_and_queue_for_sending( $messages_to_generate ) {
343
+	public function generate_and_queue_for_sending($messages_to_generate) {
344 344
 		$this->_init_queue_and_generator();
345
-		$this->_queue_for_generation_loop( $messages_to_generate );
346
-		return $this->_generator->generate( true );
345
+		$this->_queue_for_generation_loop($messages_to_generate);
346
+		return $this->_generator->generate(true);
347 347
 	}
348 348
 
349 349
 
@@ -357,10 +357,10 @@  discard block
 block discarded – undo
357 357
 	 * @param   bool                   $test_send                Whether this is a test send or not.
358 358
 	 * @return  EE_Messages_Queue | bool   false if unable to generate otherwise the generated queue.
359 359
 	 */
360
-	public function generate_for_preview( EE_Message_To_Generate $message_to_generate, $test_send = false ) {
361
-		if ( ! $message_to_generate->valid() ) {
360
+	public function generate_for_preview(EE_Message_To_Generate $message_to_generate, $test_send = false) {
361
+		if ( ! $message_to_generate->valid()) {
362 362
 			EE_Error::add_error(
363
-				__( 'Unable to generate preview because of invalid data', 'event_espresso' ),
363
+				__('Unable to generate preview because of invalid data', 'event_espresso'),
364 364
 				__FILE__,
365 365
 				__FUNCTION__,
366 366
 				__LINE__
@@ -368,14 +368,14 @@  discard block
 block discarded – undo
368 368
 			return false;
369 369
 		}
370 370
 		//just make sure preview is set on the $message_to_generate (in case client forgot)
371
-		$message_to_generate->set_preview( true );
371
+		$message_to_generate->set_preview(true);
372 372
 		$this->_init_queue_and_generator();
373
-		$this->queue_for_generation( $message_to_generate, $test_send );
374
-		$generated_queue = $this->_generator->generate( false );
375
-		if ( $generated_queue->execute( false ) ) {
373
+		$this->queue_for_generation($message_to_generate, $test_send);
374
+		$generated_queue = $this->_generator->generate(false);
375
+		if ($generated_queue->execute(false)) {
376 376
 			//the first queue item should be the preview
377 377
 			$generated_queue->get_message_repository()->rewind();
378
-			if ( ! $generated_queue->get_message_repository()->valid() ) {
378
+			if ( ! $generated_queue->get_message_repository()->valid()) {
379 379
 				return $generated_queue;
380 380
 			}
381 381
 			return $generated_queue;
@@ -392,15 +392,15 @@  discard block
 block discarded – undo
392 392
 	 * @param EE_Message_To_Generate $message_to_generate
393 393
 	 * @return bool true or false for success.
394 394
 	 */
395
-	public function queue_for_sending( EE_Message_To_Generate $message_to_generate ) {
396
-		if ( ! $message_to_generate->valid() ) {
395
+	public function queue_for_sending(EE_Message_To_Generate $message_to_generate) {
396
+		if ( ! $message_to_generate->valid()) {
397 397
 			return false;
398 398
 		}
399 399
 		$this->_init_queue_and_generator();
400 400
 		$message = $message_to_generate->get_EE_Message();
401
-		$this->_queue->add( $message );
402
-		if ( $message->send_now() ) {
403
-			$this->_queue->execute( false );
401
+		$this->_queue->add($message);
402
+		if ($message->send_now()) {
403
+			$this->_queue->execute(false);
404 404
 		} else {
405 405
 			$this->_queue->save();
406 406
 		}
@@ -413,12 +413,12 @@  discard block
 block discarded – undo
413 413
 	 * @param EE_Message_To_Generate $message_to_generate
414 414
 	 * @return EE_Messages_Queue | null
415 415
 	 */
416
-	public function generate_and_send_now( EE_Message_To_Generate $message_to_generate ) {
417
-		if ( ! $message_to_generate->valid() ) {
416
+	public function generate_and_send_now(EE_Message_To_Generate $message_to_generate) {
417
+		if ( ! $message_to_generate->valid()) {
418 418
 			return null;
419 419
 		}
420 420
 		// is there supposed to be a sending messenger for this message?
421
-		if ( $message_to_generate instanceof EEI_Has_Sending_Messenger ) {
421
+		if ($message_to_generate instanceof EEI_Has_Sending_Messenger) {
422 422
 			// make sure it's valid, but if it's not,
423 423
 			// then set the value of $sending_messenger to an EE_Error object
424 424
 			// so that downstream code can easily see that things went wrong.
@@ -434,14 +434,14 @@  discard block
 block discarded – undo
434 434
 			$sending_messenger = null;
435 435
 		}
436 436
 
437
-		if ( $message_to_generate->get_EE_Message()->STS_ID() === EEM_Message::status_idle ) {
437
+		if ($message_to_generate->get_EE_Message()->STS_ID() === EEM_Message::status_idle) {
438 438
 			$this->_init_queue_and_generator();
439
-			$this->_queue->add( $message_to_generate->get_EE_Message() );
440
-			$this->_queue->execute( false, $sending_messenger );
439
+			$this->_queue->add($message_to_generate->get_EE_Message());
440
+			$this->_queue->execute(false, $sending_messenger);
441 441
 			return $this->_queue;
442
-		} elseif ( $message_to_generate->get_EE_Message()->STS_ID() === EEM_Message::status_incomplete ) {
443
-			$generated_queue = $this->generate_and_return( array( $message_to_generate ) );
444
-			$generated_queue->execute( false, $sending_messenger );
442
+		} elseif ($message_to_generate->get_EE_Message()->STS_ID() === EEM_Message::status_incomplete) {
443
+			$generated_queue = $this->generate_and_return(array($message_to_generate));
444
+			$generated_queue->execute(false, $sending_messenger);
445 445
 			return $generated_queue;
446 446
 		}
447 447
 		return null;
@@ -458,13 +458,13 @@  discard block
 block discarded – undo
458 458
 	 * @param mixed  $data   The data being used for generation.
459 459
 	 * @param bool   $persist   Whether to persist the queued messages to the db or not.
460 460
 	 */
461
-	public function generate_for_all_active_messengers( $message_type, $data, $persist = true ) {
462
-		$messages_to_generate = $this->setup_mtgs_for_all_active_messengers( $message_type, $data );
463
-		if ( $persist ) {
464
-			$this->batch_queue_for_generation_and_persist( $messages_to_generate );
461
+	public function generate_for_all_active_messengers($message_type, $data, $persist = true) {
462
+		$messages_to_generate = $this->setup_mtgs_for_all_active_messengers($message_type, $data);
463
+		if ($persist) {
464
+			$this->batch_queue_for_generation_and_persist($messages_to_generate);
465 465
 			$this->_queue->initiate_request_by_priority();
466 466
 		} else {
467
-			$this->batch_queue_for_generation_no_persist( $messages_to_generate );
467
+			$this->batch_queue_for_generation_no_persist($messages_to_generate);
468 468
 		}
469 469
 	}
470 470
 
@@ -479,11 +479,11 @@  discard block
 block discarded – undo
479 479
 	 *
480 480
 	 * @return EE_Message_To_Generate[]
481 481
 	 */
482
-	public function setup_mtgs_for_all_active_messengers( $message_type, $data ) {
482
+	public function setup_mtgs_for_all_active_messengers($message_type, $data) {
483 483
 		$messages_to_generate = array();
484
-		foreach ( $this->_message_resource_manager->active_messengers() as $messenger_slug => $messenger_object  ) {
485
-			$message_to_generate = new EE_Message_To_Generate( $messenger_slug, $message_type, $data );
486
-			if ( $message_to_generate->valid() ) {
484
+		foreach ($this->_message_resource_manager->active_messengers() as $messenger_slug => $messenger_object) {
485
+			$message_to_generate = new EE_Message_To_Generate($messenger_slug, $message_type, $data);
486
+			if ($message_to_generate->valid()) {
487 487
 				$messages_to_generate[] = $message_to_generate;
488 488
 			}
489 489
 		}
@@ -498,29 +498,29 @@  discard block
 block discarded – undo
498 498
 	 * and send.
499 499
 	 * @param array $message_ids
500 500
 	 */
501
-	public function setup_messages_from_ids_and_send( $message_ids ) {
501
+	public function setup_messages_from_ids_and_send($message_ids) {
502 502
 		$this->_init_queue_and_generator();
503
-		$messages = EEM_Message::instance()->get_all( array(
503
+		$messages = EEM_Message::instance()->get_all(array(
504 504
 			array(
505
-				'MSG_ID' => array( 'IN', $message_ids ),
505
+				'MSG_ID' => array('IN', $message_ids),
506 506
 				'STS_ID' => array(
507 507
 					'IN',
508 508
 					array_merge(
509 509
 						EEM_Message::instance()->stati_indicating_sent(),
510
-						array( EEM_Message::status_retry )
510
+						array(EEM_Message::status_retry)
511 511
 					),
512 512
 				),
513 513
 			),
514 514
 		));
515 515
 		//set the Messages to resend.
516
-		foreach ( $messages as $message ) {
517
-			if ( $message instanceof EE_Message ) {
518
-				$message->set_STS_ID( EEM_Message::status_resend );
519
-				$this->_queue->add( $message );
516
+		foreach ($messages as $message) {
517
+			if ($message instanceof EE_Message) {
518
+				$message->set_STS_ID(EEM_Message::status_resend);
519
+				$this->_queue->add($message);
520 520
 			}
521 521
 		}
522 522
 
523
-		$this->_queue->initiate_request_by_priority( 'send' );
523
+		$this->_queue->initiate_request_by_priority('send');
524 524
 	}
525 525
 
526 526
 
@@ -534,23 +534,23 @@  discard block
 block discarded – undo
534 534
 	 *
535 535
 	 * @return EE_Message_To_Generate[]
536 536
 	 */
537
-	public function setup_messages_to_generate_from_registration_ids_in_request( $registration_ids_key = '_REG_ID' ) {
538
-		EE_Registry::instance()->load_core( 'Request_Handler' );
539
-		EE_Registry::instance()->load_helper( 'MSG_Template' );
537
+	public function setup_messages_to_generate_from_registration_ids_in_request($registration_ids_key = '_REG_ID') {
538
+		EE_Registry::instance()->load_core('Request_Handler');
539
+		EE_Registry::instance()->load_helper('MSG_Template');
540 540
 		$regs_to_send = array();
541
-		$regIDs = EE_Registry::instance()->REQ->get( $registration_ids_key );
542
-		if ( empty( $regIDs ) ) {
543
-			EE_Error::add_error( __('Something went wrong because we\'re missing the registration ID', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__ );
541
+		$regIDs = EE_Registry::instance()->REQ->get($registration_ids_key);
542
+		if (empty($regIDs)) {
543
+			EE_Error::add_error(__('Something went wrong because we\'re missing the registration ID', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
544 544
 			return false;
545 545
 		}
546 546
 
547 547
 		//make sure is an array
548
-		$regIDs = is_array( $regIDs ) ? $regIDs : array( $regIDs );
548
+		$regIDs = is_array($regIDs) ? $regIDs : array($regIDs);
549 549
 
550
-		foreach( $regIDs as $regID ) {
551
-			$reg = EEM_Registration::instance()->get_one_by_ID( $regID );
552
-			if ( ! $reg instanceof EE_Registration ) {
553
-				EE_Error::add_error( sprintf( __('Unable to retrieve a registration object for the given reg id (%s)', 'event_espresso'), $regID ) );
550
+		foreach ($regIDs as $regID) {
551
+			$reg = EEM_Registration::instance()->get_one_by_ID($regID);
552
+			if ( ! $reg instanceof EE_Registration) {
553
+				EE_Error::add_error(sprintf(__('Unable to retrieve a registration object for the given reg id (%s)', 'event_espresso'), $regID));
554 554
 				return false;
555 555
 			}
556 556
 			$regs_to_send[$reg->transaction_ID()][$reg->status_ID()][] = $reg;
@@ -558,13 +558,13 @@  discard block
 block discarded – undo
558 558
 
559 559
 		$messages_to_generate = array();
560 560
 
561
-		foreach ( $regs_to_send as $status_group ) {
562
-			foreach ( $status_group as $status_id => $registrations ) {
561
+		foreach ($regs_to_send as $status_group) {
562
+			foreach ($status_group as $status_id => $registrations) {
563 563
 				$messages_to_generate = array_merge(
564 564
 					$messages_to_generate,
565 565
 					$this->setup_mtgs_for_all_active_messengers(
566
-						EEH_MSG_Template::convert_reg_status_to_message_type( $status_id ),
567
-						array( $registrations, $status_id )
566
+						EEH_MSG_Template::convert_reg_status_to_message_type($status_id),
567
+						array($registrations, $status_id)
568 568
 					)
569 569
 				);
570 570
 			}
Please login to merge, or discard this patch.
core/db_models/fields/EE_Datetime_Field.php 1 patch
Indentation   +755 added lines, -755 removed lines patch added patch discarded remove patch
@@ -15,760 +15,760 @@
 block discarded – undo
15 15
 class EE_Datetime_Field extends EE_Model_Field_Base
16 16
 {
17 17
 
18
-    /**
19
-     * The pattern we're looking for is if only the characters 0-9 are found and there are only
20
-     * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
21
-     *
22
-     * @type string unix_timestamp_regex
23
-     */
24
-    const unix_timestamp_regex = '/[0-9]{10,}/';
25
-
26
-    /**
27
-     * @type string mysql_timestamp_format
28
-     */
29
-    const mysql_timestamp_format = 'Y-m-d H:i:s';
30
-
31
-    /**
32
-     * @type string mysql_date_format
33
-     */
34
-    const mysql_date_format = 'Y-m-d';
35
-
36
-    /**
37
-     * @type string mysql_time_format
38
-     */
39
-    const mysql_time_format = 'H:i:s';
40
-
41
-    /**
42
-     * Const for using in the default value. If the field's default is set to this,
43
-     * then we will return the time of calling `get_default_value()`, not
44
-     * just the current time at construction
45
-     */
46
-    const now = 'now';
47
-
48
-    /**
49
-     * The following properties hold the default formats for date and time.
50
-     * Defaults are set via the constructor and can be overridden on class instantiation.
51
-     * However they can also be overridden later by the set_format() method
52
-     * (and corresponding set_date_format, set_time_format methods);
53
-     */
54
-    /**
55
-     * @type string $_date_format
56
-     */
57
-    protected $_date_format = '';
58
-
59
-    /**
60
-     * @type string $_time_format
61
-     */
62
-    protected $_time_format = '';
63
-
64
-    /**
65
-     * @type string $_pretty_date_format
66
-     */
67
-    protected $_pretty_date_format = '';
68
-
69
-    /**
70
-     * @type string $_pretty_time_format
71
-     */
72
-    protected $_pretty_time_format = '';
73
-
74
-    /**
75
-     * @type DateTimeZone $_DateTimeZone
76
-     */
77
-    protected $_DateTimeZone;
78
-
79
-    /**
80
-     * @type DateTimeZone $_UTC_DateTimeZone
81
-     */
82
-    protected $_UTC_DateTimeZone;
83
-
84
-    /**
85
-     * @type DateTimeZone $_blog_DateTimeZone
86
-     */
87
-    protected $_blog_DateTimeZone;
88
-
89
-
90
-    /**
91
-     * This property holds how we want the output returned when getting a datetime string.  It is set for the
92
-     * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
93
-     * and time returned via getters.
94
-     *
95
-     * @var mixed (null|string)
96
-     */
97
-    protected $_date_time_output;
98
-
99
-
100
-    /**
101
-     * timezone string
102
-     * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
103
-     * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
104
-     * coming out of the object to be in.  Default timezone is the current WP timezone option setting
105
-     *
106
-     * @var string
107
-     */
108
-    protected $_timezone_string;
109
-
110
-
111
-    /**
112
-     * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
113
-     * offsets for comparison purposes).
114
-     *
115
-     * @var int
116
-     */
117
-    protected $_blog_offset;
118
-
119
-
120
-
121
-    /**
122
-     * @param string $table_column
123
-     * @param string $nice_name
124
-     * @param bool   $nullable
125
-     * @param string $default_value
126
-     * @param string $timezone_string
127
-     * @param string $date_format
128
-     * @param string $time_format
129
-     * @param string $pretty_date_format
130
-     * @param string $pretty_time_format
131
-     * @throws EE_Error
132
-     * @throws InvalidArgumentException
133
-     */
134
-    public function __construct(
135
-        $table_column,
136
-        $nice_name,
137
-        $nullable,
138
-        $default_value,
139
-        $timezone_string = '',
140
-        $date_format = '',
141
-        $time_format = '',
142
-        $pretty_date_format = '',
143
-        $pretty_time_format = ''
144
-    ) {
145
-
146
-        $this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
147
-        $this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
148
-        $this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
149
-        $this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
150
-
151
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
152
-        $this->set_timezone($timezone_string);
153
-        $this->setSchemaFormat('date-time');
154
-    }
155
-
156
-
157
-    /**
158
-     * @return DateTimeZone
159
-     * @throws \EE_Error
160
-     */
161
-    public function get_UTC_DateTimeZone()
162
-    {
163
-        return $this->_UTC_DateTimeZone instanceof DateTimeZone
164
-            ? $this->_UTC_DateTimeZone
165
-            : $this->_create_timezone_object_from_timezone_string('UTC');
166
-    }
167
-
168
-
169
-    /**
170
-     * @return DateTimeZone
171
-     * @throws \EE_Error
172
-     */
173
-    public function get_blog_DateTimeZone()
174
-    {
175
-        return $this->_blog_DateTimeZone instanceof DateTimeZone
176
-            ? $this->_blog_DateTimeZone
177
-            : $this->_create_timezone_object_from_timezone_string('');
178
-    }
179
-
180
-
181
-    /**
182
-     * this prepares any incoming date data and make sure its converted to a utc unix timestamp
183
-     *
184
-     * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
185
-     *                                                              timestamp
186
-     * @return DateTime
187
-     */
188
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
189
-    {
190
-        return $this->_get_date_object($value_inputted_for_field_on_model_object);
191
-    }
192
-
193
-
194
-    /**
195
-     * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
196
-     * getters need to know whether we're just returning the date or the time or both.  By default we return both.
197
-     *
198
-     * @param bool $pretty If we're returning the pretty formats or standard format string.
199
-     * @return string    The final assembled format string.
200
-     */
201
-    protected function _get_date_time_output($pretty = false)
202
-    {
203
-
204
-        switch ($this->_date_time_output) {
205
-            case 'time' :
206
-                return $pretty ? $this->_pretty_time_format : $this->_time_format;
207
-                break;
208
-
209
-            case 'date' :
210
-                return $pretty ? $this->_pretty_date_format : $this->_date_format;
211
-                break;
212
-
213
-            default :
214
-                return $pretty
215
-                    ? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
216
-                    : $this->_date_format . ' ' . $this->_time_format;
217
-        }
218
-    }
219
-
220
-
221
-    /**
222
-     * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
223
-     * returned (using the format properties)
224
-     *
225
-     * @param string $what acceptable values are 'time' or 'date'.
226
-     *                     Any other value will be set but will always result
227
-     *                     in both 'date' and 'time' being returned.
228
-     * @return void
229
-     */
230
-    public function set_date_time_output($what = null)
231
-    {
232
-        $this->_date_time_output = $what;
233
-    }
234
-
235
-
236
-    /**
237
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
238
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
239
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
240
-     * We also set some other properties in this method.
241
-     *
242
-     * @param string $timezone_string A valid timezone string as described by @link
243
-     *                                http://www.php.net/manual/en/timezones.php
244
-     * @return void
245
-     * @throws \EE_Error
246
-     */
247
-    public function set_timezone($timezone_string)
248
-    {
249
-        if (empty($timezone_string) && $this->_timezone_string !== null) {
250
-            // leave the timezone AS-IS if we already have one and
251
-            // the function arg didn't provide one
252
-            return;
253
-        }
254
-        $timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
255
-        $this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
256
-        $this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
257
-    }
258
-
259
-
260
-    /**
261
-     * _create_timezone_object_from_timezone_name
262
-     *
263
-     * @access protected
264
-     * @param string $timezone_string
265
-     * @return \DateTimeZone
266
-     * @throws \EE_Error
267
-     */
268
-    protected function _create_timezone_object_from_timezone_string($timezone_string = '')
269
-    {
270
-        return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
271
-    }
272
-
273
-
274
-    /**
275
-     * This just returns whatever is set for the current timezone.
276
-     *
277
-     * @access public
278
-     * @return string timezone string
279
-     */
280
-    public function get_timezone()
281
-    {
282
-        return $this->_timezone_string;
283
-    }
284
-
285
-
286
-    /**
287
-     * set the $_date_format property
288
-     *
289
-     * @access public
290
-     * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
291
-     * @param bool   $pretty Whether to set pretty format or not.
292
-     * @return void
293
-     */
294
-    public function set_date_format($format, $pretty = false)
295
-    {
296
-        if ($pretty) {
297
-            $this->_pretty_date_format = $format;
298
-        } else {
299
-            $this->_date_format = $format;
300
-        }
301
-    }
302
-
303
-
304
-    /**
305
-     * return the $_date_format property value.
306
-     *
307
-     * @param bool $pretty Whether to get pretty format or not.
308
-     * @return string
309
-     */
310
-    public function get_date_format($pretty = false)
311
-    {
312
-        return $pretty ? $this->_pretty_date_format : $this->_date_format;
313
-    }
314
-
315
-
316
-    /**
317
-     * set the $_time_format property
318
-     *
319
-     * @access public
320
-     * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
321
-     * @param bool   $pretty Whether to set pretty format or not.
322
-     * @return void
323
-     */
324
-    public function set_time_format($format, $pretty = false)
325
-    {
326
-        if ($pretty) {
327
-            $this->_pretty_time_format = $format;
328
-        } else {
329
-            $this->_time_format = $format;
330
-        }
331
-    }
332
-
333
-
334
-    /**
335
-     * return the $_time_format property value.
336
-     *
337
-     * @param bool $pretty Whether to get pretty format or not.
338
-     * @return string
339
-     */
340
-    public function get_time_format($pretty = false)
341
-    {
342
-        return $pretty ? $this->_pretty_time_format : $this->_time_format;
343
-    }
344
-
345
-
346
-    /**
347
-     * set the $_pretty_date_format property
348
-     *
349
-     * @access public
350
-     * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
351
-     * @return void
352
-     */
353
-    public function set_pretty_date_format($format)
354
-    {
355
-        $this->_pretty_date_format = $format;
356
-    }
357
-
358
-
359
-    /**
360
-     * set the $_pretty_time_format property
361
-     *
362
-     * @access public
363
-     * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
364
-     * @return void
365
-     */
366
-    public function set_pretty_time_format($format)
367
-    {
368
-        $this->_pretty_time_format = $format;
369
-    }
370
-
371
-
372
-    /**
373
-     * Only sets the time portion of the datetime.
374
-     *
375
-     * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
376
-     * @param DateTime        $current            current DateTime object for the datetime field
377
-     * @return DateTime
378
-     */
379
-    public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
380
-    {
381
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
382
-        // Otherwise parse the string.
383
-        if ($time_to_set_string instanceof DateTime) {
384
-            $parsed = array(
385
-                'hour'   => $time_to_set_string->format('H'),
386
-                'minute' => $time_to_set_string->format('i'),
387
-                'second' => $time_to_set_string->format('s'),
388
-            );
389
-        } else {
390
-            //parse incoming string
391
-            $parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
392
-        }
393
-
394
-        //make sure $current is in the correct timezone.
395
-        $current->setTimezone($this->_DateTimeZone);
396
-
397
-        return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
398
-    }
399
-
400
-
401
-    /**
402
-     * Only sets the date portion of the datetime.
403
-     *
404
-     * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
405
-     * @param DateTime        $current            current DateTime object for the datetime field
406
-     * @return DateTime
407
-     */
408
-    public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
409
-    {
410
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
411
-        // Otherwise parse the string.
412
-        if ($date_to_set_string instanceof DateTime) {
413
-            $parsed = array(
414
-                'year'  => $date_to_set_string->format('Y'),
415
-                'month' => $date_to_set_string->format('m'),
416
-                'day'   => $date_to_set_string->format('d'),
417
-            );
418
-        } else {
419
-            //parse incoming string
420
-            $parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
421
-        }
422
-
423
-        //make sure $current is in the correct timezone
424
-        $current->setTimezone($this->_DateTimeZone);
425
-
426
-        return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
427
-    }
428
-
429
-
430
-    /**
431
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
432
-     * datetime gets to this stage it should ALREADY be in UTC time
433
-     *
434
-     * @param  DateTime $DateTime
435
-     * @return string formatted date time for given timezone
436
-     * @throws \EE_Error
437
-     */
438
-    public function prepare_for_get($DateTime)
439
-    {
440
-        return $this->_prepare_for_display($DateTime);
441
-    }
442
-
443
-
444
-    /**
445
-     * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
446
-     * from the set wp timezone.  If so, then it returns the datetime string formatted via
447
-     * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
448
-     * abbreviation to the date_string.
449
-     *
450
-     * @param mixed $DateTime
451
-     * @param null  $schema
452
-     * @return string
453
-     * @throws \EE_Error
454
-     */
455
-    public function prepare_for_pretty_echoing($DateTime, $schema = null)
456
-    {
457
-        return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
458
-    }
459
-
460
-
461
-    /**
462
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
463
-     * timezone).
464
-     *
465
-     * @param DateTime    $DateTime
466
-     * @param bool|string $schema
467
-     * @return string
468
-     * @throws \EE_Error
469
-     */
470
-    protected function _prepare_for_display($DateTime, $schema = false)
471
-    {
472
-        if (! $DateTime instanceof DateTime) {
473
-            if ($this->_nullable) {
474
-                return '';
475
-            } else {
476
-                if (WP_DEBUG) {
477
-                    throw new EE_Error(
478
-                        sprintf(
479
-                            __(
480
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
481
-                                'event_espresso'
482
-                            ),
483
-                            $this->_nicename
484
-                        )
485
-                    );
486
-                } else {
487
-                    $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
488
-                    EE_Error::add_error(
489
-                        sprintf(
490
-                            __(
491
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
492
-                                'event_espresso'
493
-                            ),
494
-                            $this->_nicename
495
-                        )
496
-                    );
497
-                }
498
-            }
499
-        }
500
-        $format_string = $this->_get_date_time_output($schema);
501
-        //make sure datetime_value is in the correct timezone (in case that's been updated).
502
-        $DateTime->setTimezone($this->_DateTimeZone);
503
-        if ($schema) {
504
-            if ($this->_display_timezone()) {
505
-                //must be explicit because schema could equal true.
506
-                if ($schema === 'no_html') {
507
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
508
-                } else {
509
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
510
-                }
511
-            } else {
512
-                $timezone_string = '';
513
-            }
514
-
515
-            return $DateTime->format($format_string) . $timezone_string;
516
-        } else {
517
-            return $DateTime->format($format_string);
518
-        }
519
-    }
520
-
521
-
522
-    /**
523
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
524
-     * timezone).
525
-     *
526
-     * @param  mixed $datetime_value u
527
-     * @return string mysql timestamp in UTC
528
-     * @throws \EE_Error
529
-     */
530
-    public function prepare_for_use_in_db($datetime_value)
531
-    {
532
-        //we allow an empty value or DateTime object, but nothing else.
533
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
534
-            throw new EE_Error(
535
-            	sprintf(
536
-            	    __(
537
-            		    'The incoming value being prepared for setting in the database must either be empty or a php 
18
+	/**
19
+	 * The pattern we're looking for is if only the characters 0-9 are found and there are only
20
+	 * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
21
+	 *
22
+	 * @type string unix_timestamp_regex
23
+	 */
24
+	const unix_timestamp_regex = '/[0-9]{10,}/';
25
+
26
+	/**
27
+	 * @type string mysql_timestamp_format
28
+	 */
29
+	const mysql_timestamp_format = 'Y-m-d H:i:s';
30
+
31
+	/**
32
+	 * @type string mysql_date_format
33
+	 */
34
+	const mysql_date_format = 'Y-m-d';
35
+
36
+	/**
37
+	 * @type string mysql_time_format
38
+	 */
39
+	const mysql_time_format = 'H:i:s';
40
+
41
+	/**
42
+	 * Const for using in the default value. If the field's default is set to this,
43
+	 * then we will return the time of calling `get_default_value()`, not
44
+	 * just the current time at construction
45
+	 */
46
+	const now = 'now';
47
+
48
+	/**
49
+	 * The following properties hold the default formats for date and time.
50
+	 * Defaults are set via the constructor and can be overridden on class instantiation.
51
+	 * However they can also be overridden later by the set_format() method
52
+	 * (and corresponding set_date_format, set_time_format methods);
53
+	 */
54
+	/**
55
+	 * @type string $_date_format
56
+	 */
57
+	protected $_date_format = '';
58
+
59
+	/**
60
+	 * @type string $_time_format
61
+	 */
62
+	protected $_time_format = '';
63
+
64
+	/**
65
+	 * @type string $_pretty_date_format
66
+	 */
67
+	protected $_pretty_date_format = '';
68
+
69
+	/**
70
+	 * @type string $_pretty_time_format
71
+	 */
72
+	protected $_pretty_time_format = '';
73
+
74
+	/**
75
+	 * @type DateTimeZone $_DateTimeZone
76
+	 */
77
+	protected $_DateTimeZone;
78
+
79
+	/**
80
+	 * @type DateTimeZone $_UTC_DateTimeZone
81
+	 */
82
+	protected $_UTC_DateTimeZone;
83
+
84
+	/**
85
+	 * @type DateTimeZone $_blog_DateTimeZone
86
+	 */
87
+	protected $_blog_DateTimeZone;
88
+
89
+
90
+	/**
91
+	 * This property holds how we want the output returned when getting a datetime string.  It is set for the
92
+	 * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
93
+	 * and time returned via getters.
94
+	 *
95
+	 * @var mixed (null|string)
96
+	 */
97
+	protected $_date_time_output;
98
+
99
+
100
+	/**
101
+	 * timezone string
102
+	 * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
103
+	 * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
104
+	 * coming out of the object to be in.  Default timezone is the current WP timezone option setting
105
+	 *
106
+	 * @var string
107
+	 */
108
+	protected $_timezone_string;
109
+
110
+
111
+	/**
112
+	 * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
113
+	 * offsets for comparison purposes).
114
+	 *
115
+	 * @var int
116
+	 */
117
+	protected $_blog_offset;
118
+
119
+
120
+
121
+	/**
122
+	 * @param string $table_column
123
+	 * @param string $nice_name
124
+	 * @param bool   $nullable
125
+	 * @param string $default_value
126
+	 * @param string $timezone_string
127
+	 * @param string $date_format
128
+	 * @param string $time_format
129
+	 * @param string $pretty_date_format
130
+	 * @param string $pretty_time_format
131
+	 * @throws EE_Error
132
+	 * @throws InvalidArgumentException
133
+	 */
134
+	public function __construct(
135
+		$table_column,
136
+		$nice_name,
137
+		$nullable,
138
+		$default_value,
139
+		$timezone_string = '',
140
+		$date_format = '',
141
+		$time_format = '',
142
+		$pretty_date_format = '',
143
+		$pretty_time_format = ''
144
+	) {
145
+
146
+		$this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
147
+		$this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
148
+		$this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
149
+		$this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
150
+
151
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
152
+		$this->set_timezone($timezone_string);
153
+		$this->setSchemaFormat('date-time');
154
+	}
155
+
156
+
157
+	/**
158
+	 * @return DateTimeZone
159
+	 * @throws \EE_Error
160
+	 */
161
+	public function get_UTC_DateTimeZone()
162
+	{
163
+		return $this->_UTC_DateTimeZone instanceof DateTimeZone
164
+			? $this->_UTC_DateTimeZone
165
+			: $this->_create_timezone_object_from_timezone_string('UTC');
166
+	}
167
+
168
+
169
+	/**
170
+	 * @return DateTimeZone
171
+	 * @throws \EE_Error
172
+	 */
173
+	public function get_blog_DateTimeZone()
174
+	{
175
+		return $this->_blog_DateTimeZone instanceof DateTimeZone
176
+			? $this->_blog_DateTimeZone
177
+			: $this->_create_timezone_object_from_timezone_string('');
178
+	}
179
+
180
+
181
+	/**
182
+	 * this prepares any incoming date data and make sure its converted to a utc unix timestamp
183
+	 *
184
+	 * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
185
+	 *                                                              timestamp
186
+	 * @return DateTime
187
+	 */
188
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
189
+	{
190
+		return $this->_get_date_object($value_inputted_for_field_on_model_object);
191
+	}
192
+
193
+
194
+	/**
195
+	 * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
196
+	 * getters need to know whether we're just returning the date or the time or both.  By default we return both.
197
+	 *
198
+	 * @param bool $pretty If we're returning the pretty formats or standard format string.
199
+	 * @return string    The final assembled format string.
200
+	 */
201
+	protected function _get_date_time_output($pretty = false)
202
+	{
203
+
204
+		switch ($this->_date_time_output) {
205
+			case 'time' :
206
+				return $pretty ? $this->_pretty_time_format : $this->_time_format;
207
+				break;
208
+
209
+			case 'date' :
210
+				return $pretty ? $this->_pretty_date_format : $this->_date_format;
211
+				break;
212
+
213
+			default :
214
+				return $pretty
215
+					? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
216
+					: $this->_date_format . ' ' . $this->_time_format;
217
+		}
218
+	}
219
+
220
+
221
+	/**
222
+	 * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
223
+	 * returned (using the format properties)
224
+	 *
225
+	 * @param string $what acceptable values are 'time' or 'date'.
226
+	 *                     Any other value will be set but will always result
227
+	 *                     in both 'date' and 'time' being returned.
228
+	 * @return void
229
+	 */
230
+	public function set_date_time_output($what = null)
231
+	{
232
+		$this->_date_time_output = $what;
233
+	}
234
+
235
+
236
+	/**
237
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
238
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
239
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
240
+	 * We also set some other properties in this method.
241
+	 *
242
+	 * @param string $timezone_string A valid timezone string as described by @link
243
+	 *                                http://www.php.net/manual/en/timezones.php
244
+	 * @return void
245
+	 * @throws \EE_Error
246
+	 */
247
+	public function set_timezone($timezone_string)
248
+	{
249
+		if (empty($timezone_string) && $this->_timezone_string !== null) {
250
+			// leave the timezone AS-IS if we already have one and
251
+			// the function arg didn't provide one
252
+			return;
253
+		}
254
+		$timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
255
+		$this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
256
+		$this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
257
+	}
258
+
259
+
260
+	/**
261
+	 * _create_timezone_object_from_timezone_name
262
+	 *
263
+	 * @access protected
264
+	 * @param string $timezone_string
265
+	 * @return \DateTimeZone
266
+	 * @throws \EE_Error
267
+	 */
268
+	protected function _create_timezone_object_from_timezone_string($timezone_string = '')
269
+	{
270
+		return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
271
+	}
272
+
273
+
274
+	/**
275
+	 * This just returns whatever is set for the current timezone.
276
+	 *
277
+	 * @access public
278
+	 * @return string timezone string
279
+	 */
280
+	public function get_timezone()
281
+	{
282
+		return $this->_timezone_string;
283
+	}
284
+
285
+
286
+	/**
287
+	 * set the $_date_format property
288
+	 *
289
+	 * @access public
290
+	 * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
291
+	 * @param bool   $pretty Whether to set pretty format or not.
292
+	 * @return void
293
+	 */
294
+	public function set_date_format($format, $pretty = false)
295
+	{
296
+		if ($pretty) {
297
+			$this->_pretty_date_format = $format;
298
+		} else {
299
+			$this->_date_format = $format;
300
+		}
301
+	}
302
+
303
+
304
+	/**
305
+	 * return the $_date_format property value.
306
+	 *
307
+	 * @param bool $pretty Whether to get pretty format or not.
308
+	 * @return string
309
+	 */
310
+	public function get_date_format($pretty = false)
311
+	{
312
+		return $pretty ? $this->_pretty_date_format : $this->_date_format;
313
+	}
314
+
315
+
316
+	/**
317
+	 * set the $_time_format property
318
+	 *
319
+	 * @access public
320
+	 * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
321
+	 * @param bool   $pretty Whether to set pretty format or not.
322
+	 * @return void
323
+	 */
324
+	public function set_time_format($format, $pretty = false)
325
+	{
326
+		if ($pretty) {
327
+			$this->_pretty_time_format = $format;
328
+		} else {
329
+			$this->_time_format = $format;
330
+		}
331
+	}
332
+
333
+
334
+	/**
335
+	 * return the $_time_format property value.
336
+	 *
337
+	 * @param bool $pretty Whether to get pretty format or not.
338
+	 * @return string
339
+	 */
340
+	public function get_time_format($pretty = false)
341
+	{
342
+		return $pretty ? $this->_pretty_time_format : $this->_time_format;
343
+	}
344
+
345
+
346
+	/**
347
+	 * set the $_pretty_date_format property
348
+	 *
349
+	 * @access public
350
+	 * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
351
+	 * @return void
352
+	 */
353
+	public function set_pretty_date_format($format)
354
+	{
355
+		$this->_pretty_date_format = $format;
356
+	}
357
+
358
+
359
+	/**
360
+	 * set the $_pretty_time_format property
361
+	 *
362
+	 * @access public
363
+	 * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
364
+	 * @return void
365
+	 */
366
+	public function set_pretty_time_format($format)
367
+	{
368
+		$this->_pretty_time_format = $format;
369
+	}
370
+
371
+
372
+	/**
373
+	 * Only sets the time portion of the datetime.
374
+	 *
375
+	 * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
376
+	 * @param DateTime        $current            current DateTime object for the datetime field
377
+	 * @return DateTime
378
+	 */
379
+	public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
380
+	{
381
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
382
+		// Otherwise parse the string.
383
+		if ($time_to_set_string instanceof DateTime) {
384
+			$parsed = array(
385
+				'hour'   => $time_to_set_string->format('H'),
386
+				'minute' => $time_to_set_string->format('i'),
387
+				'second' => $time_to_set_string->format('s'),
388
+			);
389
+		} else {
390
+			//parse incoming string
391
+			$parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
392
+		}
393
+
394
+		//make sure $current is in the correct timezone.
395
+		$current->setTimezone($this->_DateTimeZone);
396
+
397
+		return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
398
+	}
399
+
400
+
401
+	/**
402
+	 * Only sets the date portion of the datetime.
403
+	 *
404
+	 * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
405
+	 * @param DateTime        $current            current DateTime object for the datetime field
406
+	 * @return DateTime
407
+	 */
408
+	public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
409
+	{
410
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
411
+		// Otherwise parse the string.
412
+		if ($date_to_set_string instanceof DateTime) {
413
+			$parsed = array(
414
+				'year'  => $date_to_set_string->format('Y'),
415
+				'month' => $date_to_set_string->format('m'),
416
+				'day'   => $date_to_set_string->format('d'),
417
+			);
418
+		} else {
419
+			//parse incoming string
420
+			$parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
421
+		}
422
+
423
+		//make sure $current is in the correct timezone
424
+		$current->setTimezone($this->_DateTimeZone);
425
+
426
+		return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
427
+	}
428
+
429
+
430
+	/**
431
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
432
+	 * datetime gets to this stage it should ALREADY be in UTC time
433
+	 *
434
+	 * @param  DateTime $DateTime
435
+	 * @return string formatted date time for given timezone
436
+	 * @throws \EE_Error
437
+	 */
438
+	public function prepare_for_get($DateTime)
439
+	{
440
+		return $this->_prepare_for_display($DateTime);
441
+	}
442
+
443
+
444
+	/**
445
+	 * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
446
+	 * from the set wp timezone.  If so, then it returns the datetime string formatted via
447
+	 * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
448
+	 * abbreviation to the date_string.
449
+	 *
450
+	 * @param mixed $DateTime
451
+	 * @param null  $schema
452
+	 * @return string
453
+	 * @throws \EE_Error
454
+	 */
455
+	public function prepare_for_pretty_echoing($DateTime, $schema = null)
456
+	{
457
+		return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
458
+	}
459
+
460
+
461
+	/**
462
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
463
+	 * timezone).
464
+	 *
465
+	 * @param DateTime    $DateTime
466
+	 * @param bool|string $schema
467
+	 * @return string
468
+	 * @throws \EE_Error
469
+	 */
470
+	protected function _prepare_for_display($DateTime, $schema = false)
471
+	{
472
+		if (! $DateTime instanceof DateTime) {
473
+			if ($this->_nullable) {
474
+				return '';
475
+			} else {
476
+				if (WP_DEBUG) {
477
+					throw new EE_Error(
478
+						sprintf(
479
+							__(
480
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
481
+								'event_espresso'
482
+							),
483
+							$this->_nicename
484
+						)
485
+					);
486
+				} else {
487
+					$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
488
+					EE_Error::add_error(
489
+						sprintf(
490
+							__(
491
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
492
+								'event_espresso'
493
+							),
494
+							$this->_nicename
495
+						)
496
+					);
497
+				}
498
+			}
499
+		}
500
+		$format_string = $this->_get_date_time_output($schema);
501
+		//make sure datetime_value is in the correct timezone (in case that's been updated).
502
+		$DateTime->setTimezone($this->_DateTimeZone);
503
+		if ($schema) {
504
+			if ($this->_display_timezone()) {
505
+				//must be explicit because schema could equal true.
506
+				if ($schema === 'no_html') {
507
+					$timezone_string = ' (' . $DateTime->format('T') . ')';
508
+				} else {
509
+					$timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
510
+				}
511
+			} else {
512
+				$timezone_string = '';
513
+			}
514
+
515
+			return $DateTime->format($format_string) . $timezone_string;
516
+		} else {
517
+			return $DateTime->format($format_string);
518
+		}
519
+	}
520
+
521
+
522
+	/**
523
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
524
+	 * timezone).
525
+	 *
526
+	 * @param  mixed $datetime_value u
527
+	 * @return string mysql timestamp in UTC
528
+	 * @throws \EE_Error
529
+	 */
530
+	public function prepare_for_use_in_db($datetime_value)
531
+	{
532
+		//we allow an empty value or DateTime object, but nothing else.
533
+		if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
534
+			throw new EE_Error(
535
+				sprintf(
536
+					__(
537
+						'The incoming value being prepared for setting in the database must either be empty or a php 
538 538
             		    DateTime object, instead of: %1$s %2$s',
539
-                        'event_espresso'
540
-	                ),
541
-                    '<br />',
542
-                    print_r($datetime_value, true)
543
-                )
544
-            );
545
-        }
546
-
547
-        if ($datetime_value instanceof DateTime) {
548
-            if ( ! $datetime_value instanceof DbSafeDateTime) {
549
-                $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
550
-            }
551
-
552
-            return $datetime_value->setTimezone($this->get_UTC_DateTimeZone())->format(
553
-                EE_Datetime_Field::mysql_timestamp_format
554
-            );
555
-        }
556
-
557
-        // if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
558
-        return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
559
-    }
560
-
561
-
562
-    /**
563
-     * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
564
-     * allowed)
565
-     *
566
-     * @param string $datetime_string mysql timestamp in UTC
567
-     * @return  mixed null | DateTime
568
-     * @throws \EE_Error
569
-     */
570
-    public function prepare_for_set_from_db($datetime_string)
571
-    {
572
-        //if $datetime_value is empty, and ! $this->_nullable, just use time()
573
-        if (empty($datetime_string) && $this->_nullable) {
574
-            return null;
575
-        }
576
-        // datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
577
-        if (empty($datetime_string)) {
578
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
579
-        } else {
580
-            $DateTime = DateTime::createFromFormat(
581
-                EE_Datetime_Field::mysql_timestamp_format,
582
-                $datetime_string,
583
-                $this->get_UTC_DateTimeZone()
584
-            );
585
-            if ($DateTime instanceof \DateTime) {
586
-                $DateTime = new DbSafeDateTime(
587
-                    $DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
588
-                    $this->get_UTC_DateTimeZone()
589
-                );
590
-            }
591
-        }
592
-
593
-        if (! $DateTime instanceof DbSafeDateTime) {
594
-            // if still no datetime object, then let's just use now
595
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
596
-        }
597
-        // THEN apply the field's set DateTimeZone
598
-        $DateTime->setTimezone($this->_DateTimeZone);
599
-
600
-        return $DateTime;
601
-    }
602
-
603
-
604
-    /**
605
-     * All this method does is determine if we're going to display the timezone string or not on any output.
606
-     * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
607
-     * If so, then true.
608
-     *
609
-     * @return bool true for yes false for no
610
-     * @throws \EE_Error
611
-     */
612
-    protected function _display_timezone()
613
-    {
614
-
615
-        // first let's do a comparison of timezone strings.
616
-        // If they match then we can get out without any further calculations
617
-        $blog_string = get_option('timezone_string');
618
-        if ($blog_string === $this->_timezone_string) {
619
-            return false;
620
-        }
621
-        // now we need to calc the offset for the timezone string so we can compare with the blog offset.
622
-        $this_offset = $this->get_timezone_offset($this->_DateTimeZone);
623
-        $blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
624
-        // now compare
625
-        return $blog_offset !== $this_offset;
626
-    }
627
-
628
-
629
-    /**
630
-     * This method returns a php DateTime object for setting on the EE_Base_Class model.
631
-     * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
632
-     * with.
633
-     *
634
-     * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
635
-     *                                                    in the format that is set on the date_field (or DateTime
636
-     *                                                    object)!
637
-     * @return DateTime
638
-     */
639
-    protected function _get_date_object($date_string)
640
-    {
641
-        //first if this is an empty date_string and nullable is allowed, just return null.
642
-        if ($this->_nullable && empty($date_string)) {
643
-            return null;
644
-        }
645
-
646
-        // if incoming date
647
-        if ($date_string instanceof DateTime) {
648
-            $date_string->setTimezone($this->_DateTimeZone);
649
-
650
-            return $date_string;
651
-        }
652
-        // if empty date_string and made it here.
653
-        // Return a datetime object for now in the given timezone.
654
-        if (empty($date_string)) {
655
-            return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
656
-        }
657
-        // if $date_string is matches something that looks like a Unix timestamp let's just use it.
658
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
659
-            try {
660
-                // This is operating under the assumption that the incoming Unix timestamp
661
-                // is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
662
-                $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
663
-                $DateTime->setTimestamp($date_string);
664
-
665
-                return $DateTime;
666
-            } catch (Exception $e) {
667
-                // should be rare, but if things got fooled then let's just continue
668
-            }
669
-        }
670
-        //not a unix timestamp.  So we will use the set format on this object and set timezone to
671
-        //create the DateTime object.
672
-        $format = $this->_date_format . ' ' . $this->_time_format;
673
-        try {
674
-            $DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
675
-            if ($DateTime instanceof DateTime) {
676
-                $DateTime = new DbSafeDateTime(
677
-                    $DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
678
-                    $this->_DateTimeZone
679
-                );
680
-            }
681
-            if (! $DateTime instanceof DbSafeDateTime) {
682
-                throw new EE_Error(
683
-                    sprintf(
684
-                        __('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
685
-                        $date_string,
686
-                        $format
687
-                    )
688
-                );
689
-            }
690
-        } catch (Exception $e) {
691
-            // if we made it here then likely then something went really wrong.
692
-            // Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
693
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
694
-        }
695
-
696
-        return $DateTime;
697
-    }
698
-
699
-
700
-
701
-    /**
702
-     * get_timezone_transitions
703
-     *
704
-     * @param \DateTimeZone $DateTimeZone
705
-     * @param int           $time
706
-     * @param bool          $first_only
707
-     * @return mixed
708
-     */
709
-    public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
710
-    {
711
-        $time = is_int($time) || $time === null ? $time : strtotime($time);
712
-        $time = preg_match(EE_Datetime_Field::unix_timestamp_regex, $time) ? $time : time();
713
-        $transitions = $DateTimeZone->getTransitions($time);
714
-        return $first_only && ! isset($transitions['ts']) ? reset($transitions) : $transitions;
715
-    }
716
-
717
-
718
-
719
-    /**
720
-     * get_timezone_offset
721
-     *
722
-     * @param \DateTimeZone $DateTimeZone
723
-     * @param int           $time
724
-     * @return mixed
725
-     * @throws \DomainException
726
-     */
727
-    public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
728
-    {
729
-        $transitions = $this->get_timezone_transitions($DateTimeZone, $time);
730
-        if ( ! isset($transitions['offset'])) {
731
-            throw new DomainException();
732
-        }
733
-        return $transitions['offset'];
734
-    }
735
-
736
-
737
-    /**
738
-     * This will take an incoming timezone string and return the abbreviation for that timezone
739
-     *
740
-     * @param  string $timezone_string
741
-     * @return string           abbreviation
742
-     * @throws \EE_Error
743
-     */
744
-    public function get_timezone_abbrev($timezone_string)
745
-    {
746
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
747
-        $dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
748
-
749
-        return $dateTime->format('T');
750
-    }
751
-
752
-    /**
753
-     * Overrides the parent to allow for having a dynamic "now" value
754
-     *
755
-     * @return mixed
756
-     */
757
-    public function get_default_value()
758
-    {
759
-        if ($this->_default_value === EE_Datetime_Field::now) {
760
-            return time();
761
-        } else {
762
-            return parent::get_default_value();
763
-        }
764
-    }
765
-
766
-
767
-    public function getSchemaDescription()
768
-    {
769
-        return sprintf(
770
-            esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
771
-            $this->get_nicename()
772
-        );
773
-    }
539
+						'event_espresso'
540
+					),
541
+					'<br />',
542
+					print_r($datetime_value, true)
543
+				)
544
+			);
545
+		}
546
+
547
+		if ($datetime_value instanceof DateTime) {
548
+			if ( ! $datetime_value instanceof DbSafeDateTime) {
549
+				$datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
550
+			}
551
+
552
+			return $datetime_value->setTimezone($this->get_UTC_DateTimeZone())->format(
553
+				EE_Datetime_Field::mysql_timestamp_format
554
+			);
555
+		}
556
+
557
+		// if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
558
+		return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
559
+	}
560
+
561
+
562
+	/**
563
+	 * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
564
+	 * allowed)
565
+	 *
566
+	 * @param string $datetime_string mysql timestamp in UTC
567
+	 * @return  mixed null | DateTime
568
+	 * @throws \EE_Error
569
+	 */
570
+	public function prepare_for_set_from_db($datetime_string)
571
+	{
572
+		//if $datetime_value is empty, and ! $this->_nullable, just use time()
573
+		if (empty($datetime_string) && $this->_nullable) {
574
+			return null;
575
+		}
576
+		// datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
577
+		if (empty($datetime_string)) {
578
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
579
+		} else {
580
+			$DateTime = DateTime::createFromFormat(
581
+				EE_Datetime_Field::mysql_timestamp_format,
582
+				$datetime_string,
583
+				$this->get_UTC_DateTimeZone()
584
+			);
585
+			if ($DateTime instanceof \DateTime) {
586
+				$DateTime = new DbSafeDateTime(
587
+					$DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
588
+					$this->get_UTC_DateTimeZone()
589
+				);
590
+			}
591
+		}
592
+
593
+		if (! $DateTime instanceof DbSafeDateTime) {
594
+			// if still no datetime object, then let's just use now
595
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
596
+		}
597
+		// THEN apply the field's set DateTimeZone
598
+		$DateTime->setTimezone($this->_DateTimeZone);
599
+
600
+		return $DateTime;
601
+	}
602
+
603
+
604
+	/**
605
+	 * All this method does is determine if we're going to display the timezone string or not on any output.
606
+	 * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
607
+	 * If so, then true.
608
+	 *
609
+	 * @return bool true for yes false for no
610
+	 * @throws \EE_Error
611
+	 */
612
+	protected function _display_timezone()
613
+	{
614
+
615
+		// first let's do a comparison of timezone strings.
616
+		// If they match then we can get out without any further calculations
617
+		$blog_string = get_option('timezone_string');
618
+		if ($blog_string === $this->_timezone_string) {
619
+			return false;
620
+		}
621
+		// now we need to calc the offset for the timezone string so we can compare with the blog offset.
622
+		$this_offset = $this->get_timezone_offset($this->_DateTimeZone);
623
+		$blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
624
+		// now compare
625
+		return $blog_offset !== $this_offset;
626
+	}
627
+
628
+
629
+	/**
630
+	 * This method returns a php DateTime object for setting on the EE_Base_Class model.
631
+	 * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
632
+	 * with.
633
+	 *
634
+	 * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
635
+	 *                                                    in the format that is set on the date_field (or DateTime
636
+	 *                                                    object)!
637
+	 * @return DateTime
638
+	 */
639
+	protected function _get_date_object($date_string)
640
+	{
641
+		//first if this is an empty date_string and nullable is allowed, just return null.
642
+		if ($this->_nullable && empty($date_string)) {
643
+			return null;
644
+		}
645
+
646
+		// if incoming date
647
+		if ($date_string instanceof DateTime) {
648
+			$date_string->setTimezone($this->_DateTimeZone);
649
+
650
+			return $date_string;
651
+		}
652
+		// if empty date_string and made it here.
653
+		// Return a datetime object for now in the given timezone.
654
+		if (empty($date_string)) {
655
+			return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
656
+		}
657
+		// if $date_string is matches something that looks like a Unix timestamp let's just use it.
658
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
659
+			try {
660
+				// This is operating under the assumption that the incoming Unix timestamp
661
+				// is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
662
+				$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
663
+				$DateTime->setTimestamp($date_string);
664
+
665
+				return $DateTime;
666
+			} catch (Exception $e) {
667
+				// should be rare, but if things got fooled then let's just continue
668
+			}
669
+		}
670
+		//not a unix timestamp.  So we will use the set format on this object and set timezone to
671
+		//create the DateTime object.
672
+		$format = $this->_date_format . ' ' . $this->_time_format;
673
+		try {
674
+			$DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
675
+			if ($DateTime instanceof DateTime) {
676
+				$DateTime = new DbSafeDateTime(
677
+					$DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
678
+					$this->_DateTimeZone
679
+				);
680
+			}
681
+			if (! $DateTime instanceof DbSafeDateTime) {
682
+				throw new EE_Error(
683
+					sprintf(
684
+						__('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
685
+						$date_string,
686
+						$format
687
+					)
688
+				);
689
+			}
690
+		} catch (Exception $e) {
691
+			// if we made it here then likely then something went really wrong.
692
+			// Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
693
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
694
+		}
695
+
696
+		return $DateTime;
697
+	}
698
+
699
+
700
+
701
+	/**
702
+	 * get_timezone_transitions
703
+	 *
704
+	 * @param \DateTimeZone $DateTimeZone
705
+	 * @param int           $time
706
+	 * @param bool          $first_only
707
+	 * @return mixed
708
+	 */
709
+	public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
710
+	{
711
+		$time = is_int($time) || $time === null ? $time : strtotime($time);
712
+		$time = preg_match(EE_Datetime_Field::unix_timestamp_regex, $time) ? $time : time();
713
+		$transitions = $DateTimeZone->getTransitions($time);
714
+		return $first_only && ! isset($transitions['ts']) ? reset($transitions) : $transitions;
715
+	}
716
+
717
+
718
+
719
+	/**
720
+	 * get_timezone_offset
721
+	 *
722
+	 * @param \DateTimeZone $DateTimeZone
723
+	 * @param int           $time
724
+	 * @return mixed
725
+	 * @throws \DomainException
726
+	 */
727
+	public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
728
+	{
729
+		$transitions = $this->get_timezone_transitions($DateTimeZone, $time);
730
+		if ( ! isset($transitions['offset'])) {
731
+			throw new DomainException();
732
+		}
733
+		return $transitions['offset'];
734
+	}
735
+
736
+
737
+	/**
738
+	 * This will take an incoming timezone string and return the abbreviation for that timezone
739
+	 *
740
+	 * @param  string $timezone_string
741
+	 * @return string           abbreviation
742
+	 * @throws \EE_Error
743
+	 */
744
+	public function get_timezone_abbrev($timezone_string)
745
+	{
746
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
747
+		$dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
748
+
749
+		return $dateTime->format('T');
750
+	}
751
+
752
+	/**
753
+	 * Overrides the parent to allow for having a dynamic "now" value
754
+	 *
755
+	 * @return mixed
756
+	 */
757
+	public function get_default_value()
758
+	{
759
+		if ($this->_default_value === EE_Datetime_Field::now) {
760
+			return time();
761
+		} else {
762
+			return parent::get_default_value();
763
+		}
764
+	}
765
+
766
+
767
+	public function getSchemaDescription()
768
+	{
769
+		return sprintf(
770
+			esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
771
+			$this->get_nicename()
772
+		);
773
+	}
774 774
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Attendee.model.php 1 patch
Indentation   +399 added lines, -399 removed lines patch added patch discarded remove patch
@@ -17,413 +17,413 @@
 block discarded – undo
17 17
 class EEM_Attendee extends EEM_CPT_Base
18 18
 {
19 19
 
20
-    // private instance of the Attendee object
21
-    protected static $_instance = null;
20
+	// private instance of the Attendee object
21
+	protected static $_instance = null;
22 22
 
23
-    /**
24
-     * QST_system for questions are strings not integers now,
25
-     * so these constants are deprecated.
26
-     * Please instead use the EEM_Attendee::system_question_* constants
27
-     *
28
-     * @deprecated
29
-     */
30
-    const fname_question_id = 1;
23
+	/**
24
+	 * QST_system for questions are strings not integers now,
25
+	 * so these constants are deprecated.
26
+	 * Please instead use the EEM_Attendee::system_question_* constants
27
+	 *
28
+	 * @deprecated
29
+	 */
30
+	const fname_question_id = 1;
31 31
 
32
-    /**
33
-     * @deprecated
34
-     */
35
-    const lname_question_id = 2;
32
+	/**
33
+	 * @deprecated
34
+	 */
35
+	const lname_question_id = 2;
36 36
 
37 37
 
38
-    /**
39
-     * @deprecated
40
-     */
41
-    const email_question_id = 3;
38
+	/**
39
+	 * @deprecated
40
+	 */
41
+	const email_question_id = 3;
42 42
 
43 43
 
44
-    /**
45
-     * @deprecated
46
-     */
47
-    const address_question_id = 4;
44
+	/**
45
+	 * @deprecated
46
+	 */
47
+	const address_question_id = 4;
48 48
 
49 49
 
50
-    /**
51
-     * @deprecated
52
-     */
53
-    const address2_question_id = 5;
54
-
55
-
56
-    /**
57
-     * @deprecated
58
-     */
59
-    const city_question_id = 6;
60
-
61
-
62
-    /**
63
-     * @deprecated
64
-     */
65
-    const state_question_id = 7;
66
-
67
-
68
-    /**
69
-     * @deprecated
70
-     */
71
-    const country_question_id = 8;
72
-
73
-
74
-    /**
75
-     * @deprecated
76
-     */
77
-    const zip_question_id = 9;
78
-
79
-
80
-    /**
81
-     * @deprecated
82
-     */
83
-    const phone_question_id = 10;
84
-
85
-    /**
86
-     * When looking for questions that correspond to attendee fields,
87
-     * look for the question with this QST_system value.
88
-     * These replace the old constants like EEM_Attendee::*_question_id
89
-     */
90
-    const system_question_fname = 'fname';
91
-
92
-    const system_question_lname = 'lname';
93
-
94
-    const system_question_email = 'email';
95
-
96
-    const system_question_address = 'address';
97
-
98
-    const system_question_address2 = 'address2';
99
-
100
-    const system_question_city = 'city';
101
-
102
-    const system_question_state = 'state';
103
-
104
-    const system_question_country = 'country';
105
-
106
-    const system_question_zip = 'zip';
107
-
108
-    const system_question_phone = 'phone';
109
-
110
-    /**
111
-     * Keys are all the EEM_Attendee::system_question_* constants, which are
112
-     * also all the values of QST_system in the questions table, and values
113
-     * are their corresponding Attendee field names
114
-     *
115
-     * @var array
116
-     */
117
-    protected $_system_question_to_attendee_field_name = array(
118
-        EEM_Attendee::system_question_fname    => 'ATT_fname',
119
-        EEM_Attendee::system_question_lname    => 'ATT_lname',
120
-        EEM_Attendee::system_question_email    => 'ATT_email',
121
-        EEM_Attendee::system_question_address  => 'ATT_address',
122
-        EEM_Attendee::system_question_address2 => 'ATT_address2',
123
-        EEM_Attendee::system_question_city     => 'ATT_city',
124
-        EEM_Attendee::system_question_state    => 'STA_ID',
125
-        EEM_Attendee::system_question_country  => 'CNT_ISO',
126
-        EEM_Attendee::system_question_zip      => 'ATT_zip',
127
-        EEM_Attendee::system_question_phone    => 'ATT_phone',
128
-    );
129
-
130
-
131
-
132
-    /**
133
-     * EEM_Attendee constructor.
134
-     *
135
-     * @param null              $timezone
136
-     * @param ModelFieldFactory $model_field_factory
137
-     * @throws EE_Error
138
-     * @throws InvalidArgumentException
139
-     */
140
-    protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
141
-    {
142
-        $this->singular_item = esc_html__('Attendee', 'event_espresso');
143
-        $this->plural_item = esc_html__('Attendees', 'event_espresso');
144
-        $this->_tables = array(
145
-            'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
146
-            'Attendee_Meta' => new EE_Secondary_Table(
147
-                'esp_attendee_meta',
148
-                'ATTM_ID',
149
-                'ATT_ID'
150
-            ),
151
-        );
152
-        $this->_fields = array(
153
-            'Attendee_CPT'  => array(
154
-                'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
155
-                    'ID',
156
-                    esc_html__('Attendee ID', 'event_espresso')
157
-                ),
158
-                'ATT_full_name' => $model_field_factory->createPlainTextField(
159
-                    'post_title',
160
-                    esc_html__('Attendee Full Name', 'event_espresso'),
161
-                    false,
162
-                    esc_html__('Unknown', 'event_espresso')
163
-                ),
164
-                'ATT_bio'       => $model_field_factory->createPostContentField(
165
-                    'post_content',
166
-                    esc_html__('Attendee Biography', 'event_espresso'),
167
-                    false,
168
-                    esc_html__('No Biography Provided', 'event_espresso')
169
-                ),
170
-                'ATT_slug'      => $model_field_factory->createSlugField(
171
-                    'post_name',
172
-                    esc_html__('Attendee URL Slug', 'event_espresso')
173
-                ),
174
-                'ATT_created'   => $model_field_factory->createDatetimeField(
175
-                    'post_date',
176
-                    esc_html__('Time Attendee Created', 'event_espresso')
177
-                ),
178
-                'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
179
-                    'post_excerpt',
180
-                    esc_html__('Attendee Short Biography', 'event_espresso'),
181
-                    true,
182
-                    esc_html__('No Biography Provided', 'event_espresso')
183
-                ),
184
-                'ATT_modified'  => $model_field_factory->createDatetimeField(
185
-                    'post_modified',
186
-                    esc_html__('Time Attendee Last Modified', 'event_espresso')
187
-                ),
188
-                'ATT_author'    => $model_field_factory->createWpUserField(
189
-                    'post_author',
190
-                    esc_html__('Creator ID of the first Event attended', 'event_espresso'),
191
-                    false
192
-                ),
193
-                'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
194
-                    'post_parent',
195
-                    esc_html__('Parent Attendee (unused)', 'event_espresso'),
196
-                    false,
197
-                    0
198
-                ),
199
-                'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
200
-                'status'        => $model_field_factory->createWpPostStatusField(
201
-                    'post_status',
202
-                    esc_html__('Attendee Status', 'event_espresso'),
203
-                    false,
204
-                    'publish'
205
-                ),
206
-            ),
207
-            'Attendee_Meta' => array(
208
-                'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
209
-                    'ATTM_ID',
210
-                    esc_html__('Attendee Meta Row ID', 'event_espresso'),
211
-                    false
212
-                ),
213
-                'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
214
-                    'ATT_ID',
215
-                    esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
216
-                    false
217
-                ),
218
-                'ATT_fname'    => $model_field_factory->createPlainTextField(
219
-                    'ATT_fname',
220
-                    esc_html__('First Name', 'event_espresso')
221
-                ),
222
-                'ATT_lname'    => $model_field_factory->createPlainTextField(
223
-                    'ATT_lname',
224
-                    esc_html__('Last Name', 'event_espresso')
225
-                ),
226
-                'ATT_address'  => $model_field_factory->createPlainTextField(
227
-                    'ATT_address',
228
-                    esc_html__('Address Part 1', 'event_espresso')
229
-                ),
230
-                'ATT_address2' => $model_field_factory->createPlainTextField(
231
-                    'ATT_address2',
232
-                    esc_html__('Address Part 2', 'event_espresso')
233
-                ),
234
-                'ATT_city'     => $model_field_factory->createPlainTextField(
235
-                    'ATT_city',
236
-                    esc_html__('City', 'event_espresso')
237
-                ),
238
-                'STA_ID'       => $model_field_factory->createForeignKeyIntField(
239
-                    'STA_ID',
240
-                    esc_html__('State', 'event_espresso'),
241
-                    true,
242
-                    0,
243
-                    'State'
244
-                ),
245
-                'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
246
-                    'CNT_ISO',
247
-                    esc_html__('Country', 'event_espresso'),
248
-                    true,
249
-                    '',
250
-                    'Country'
251
-                ),
252
-                'ATT_zip'      => $model_field_factory->createPlainTextField(
253
-                    'ATT_zip',
254
-                    esc_html__('ZIP/Postal Code', 'event_espresso')
255
-                ),
256
-                'ATT_email'    => $model_field_factory->createEmailField(
257
-                    'ATT_email',
258
-                    esc_html__('Email Address', 'event_espresso')
259
-                ),
260
-                'ATT_phone'    => $model_field_factory->createPlainTextField(
261
-                    'ATT_phone',
262
-                    esc_html__('Phone', 'event_espresso')
263
-                ),
264
-            ),
265
-        );
266
-        $this->_model_relations = array(
267
-            'Registration'      => new EE_Has_Many_Relation(),
268
-            'State'             => new EE_Belongs_To_Relation(),
269
-            'Country'           => new EE_Belongs_To_Relation(),
270
-            'Event'             => new EE_HABTM_Relation('Registration', false),
271
-            'WP_User'           => new EE_Belongs_To_Relation(),
272
-            'Message'           => new EE_Has_Many_Any_Relation(false),
273
-            //allow deletion of attendees even if they have messages in the queue for them.
274
-            'Term_Relationship' => new EE_Has_Many_Relation(),
275
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
276
-        );
277
-        $this->_caps_slug = 'contacts';
278
-        parent::__construct($timezone);
279
-    }
280
-
281
-
282
-
283
-    /**
284
-     * Gets the name of the field on the attendee model corresponding to the system question string
285
-     * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
286
-     *
287
-     * @param string $system_question_string
288
-     * @return string|null if not found
289
-     */
290
-    public function get_attendee_field_for_system_question($system_question_string)
291
-    {
292
-        return isset($this->_system_question_to_attendee_field_name[$system_question_string])
293
-            ? $this->_system_question_to_attendee_field_name[$system_question_string]
294
-            : null;
295
-    }
296
-
297
-
298
-
299
-    /**
300
-     * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
301
-     *
302
-     * @return array
303
-     */
304
-    public function system_question_to_attendee_field_mapping()
305
-    {
306
-        return $this->_system_question_to_attendee_field_name;
307
-    }
308
-
309
-
310
-
311
-    /**
312
-     * Gets all the attendees for a transaction (by using the esp_registration as a join table)
313
-     *
314
-     * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
315
-     * @return EE_Attendee[]|EE_Base_Class[]
316
-     * @throws EE_Error
317
-     */
318
-    public function get_attendees_for_transaction($transaction_id_or_obj)
319
-    {
320
-        return $this->get_all(
321
-            array(
322
-                array(
323
-                    'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
324
-                        ? $transaction_id_or_obj->ID()
325
-                        : $transaction_id_or_obj,
326
-                ),
327
-            )
328
-        );
329
-    }
330
-
331
-
332
-
333
-    /**
334
-     * retrieve  a single attendee from db via their ID
335
-     *
336
-     * @param $ATT_ID
337
-     * @return mixed array on success, FALSE on fail
338
-     * @deprecated
339
-     */
340
-    public function get_attendee_by_ID($ATT_ID = false)
341
-    {
342
-        // retrieve a particular EE_Attendee
343
-        return $this->get_one_by_ID($ATT_ID);
344
-    }
345
-
346
-
347
-
348
-    /**
349
-     * retrieve  a single attendee from db via their ID
350
-     *
351
-     * @param array $where_cols_n_values
352
-     * @return mixed array on success, FALSE on fail
353
-     * @throws EE_Error
354
-     */
355
-    public function get_attendee($where_cols_n_values = array())
356
-    {
357
-        if (empty($where_cols_n_values)) {
358
-            return false;
359
-        }
360
-        $attendee = $this->get_all(array($where_cols_n_values));
361
-        if (! empty($attendee)) {
362
-            return array_shift($attendee);
363
-        }
364
-        return false;
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * Search for an existing Attendee record in the DB
371
-     *
372
-     * @param array $where_cols_n_values
373
-     * @return bool|mixed
374
-     * @throws EE_Error
375
-     */
376
-    public function find_existing_attendee($where_cols_n_values = null)
377
-    {
378
-        // search by combo of first and last names plus the email address
379
-        $attendee_data_keys = array(
380
-            'ATT_fname' => $this->_ATT_fname,
381
-            'ATT_lname' => $this->_ATT_lname,
382
-            'ATT_email' => $this->_ATT_email,
383
-        );
384
-        // no search params means attendee object already exists.
385
-        $where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
386
-            ? $where_cols_n_values
387
-            : $attendee_data_keys;
388
-        $valid_data = true;
389
-        // check for required values
390
-        $valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
391
-            ? $valid_data
392
-            : false;
393
-        $valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
394
-            ? $valid_data
395
-            : false;
396
-        $valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
397
-            ? $valid_data
398
-            : false;
399
-        if ($valid_data) {
400
-            $attendee = $this->get_attendee($where_cols_n_values);
401
-            if ($attendee instanceof EE_Attendee) {
402
-                return $attendee;
403
-            }
404
-        }
405
-        return false;
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * Takes an incoming array of EE_Registration ids
412
-     * and sends back a list of corresponding non duplicate EE_Attendee objects.
413
-     *
414
-     * @since  4.3.0
415
-     * @param  array $ids array of EE_Registration ids
416
-     * @return EE_Attendee[]|EE_Base_Class[]
417
-     * @throws EE_Error
418
-     */
419
-    public function get_array_of_contacts_from_reg_ids($ids)
420
-    {
421
-        $ids = (array)$ids;
422
-        $_where = array(
423
-            'Registration.REG_ID' => array('in', $ids),
424
-        );
425
-        return $this->get_all(array($_where));
426
-    }
50
+	/**
51
+	 * @deprecated
52
+	 */
53
+	const address2_question_id = 5;
54
+
55
+
56
+	/**
57
+	 * @deprecated
58
+	 */
59
+	const city_question_id = 6;
60
+
61
+
62
+	/**
63
+	 * @deprecated
64
+	 */
65
+	const state_question_id = 7;
66
+
67
+
68
+	/**
69
+	 * @deprecated
70
+	 */
71
+	const country_question_id = 8;
72
+
73
+
74
+	/**
75
+	 * @deprecated
76
+	 */
77
+	const zip_question_id = 9;
78
+
79
+
80
+	/**
81
+	 * @deprecated
82
+	 */
83
+	const phone_question_id = 10;
84
+
85
+	/**
86
+	 * When looking for questions that correspond to attendee fields,
87
+	 * look for the question with this QST_system value.
88
+	 * These replace the old constants like EEM_Attendee::*_question_id
89
+	 */
90
+	const system_question_fname = 'fname';
91
+
92
+	const system_question_lname = 'lname';
93
+
94
+	const system_question_email = 'email';
95
+
96
+	const system_question_address = 'address';
97
+
98
+	const system_question_address2 = 'address2';
99
+
100
+	const system_question_city = 'city';
101
+
102
+	const system_question_state = 'state';
103
+
104
+	const system_question_country = 'country';
105
+
106
+	const system_question_zip = 'zip';
107
+
108
+	const system_question_phone = 'phone';
109
+
110
+	/**
111
+	 * Keys are all the EEM_Attendee::system_question_* constants, which are
112
+	 * also all the values of QST_system in the questions table, and values
113
+	 * are their corresponding Attendee field names
114
+	 *
115
+	 * @var array
116
+	 */
117
+	protected $_system_question_to_attendee_field_name = array(
118
+		EEM_Attendee::system_question_fname    => 'ATT_fname',
119
+		EEM_Attendee::system_question_lname    => 'ATT_lname',
120
+		EEM_Attendee::system_question_email    => 'ATT_email',
121
+		EEM_Attendee::system_question_address  => 'ATT_address',
122
+		EEM_Attendee::system_question_address2 => 'ATT_address2',
123
+		EEM_Attendee::system_question_city     => 'ATT_city',
124
+		EEM_Attendee::system_question_state    => 'STA_ID',
125
+		EEM_Attendee::system_question_country  => 'CNT_ISO',
126
+		EEM_Attendee::system_question_zip      => 'ATT_zip',
127
+		EEM_Attendee::system_question_phone    => 'ATT_phone',
128
+	);
129
+
130
+
131
+
132
+	/**
133
+	 * EEM_Attendee constructor.
134
+	 *
135
+	 * @param null              $timezone
136
+	 * @param ModelFieldFactory $model_field_factory
137
+	 * @throws EE_Error
138
+	 * @throws InvalidArgumentException
139
+	 */
140
+	protected function __construct($timezone = null, ModelFieldFactory $model_field_factory)
141
+	{
142
+		$this->singular_item = esc_html__('Attendee', 'event_espresso');
143
+		$this->plural_item = esc_html__('Attendees', 'event_espresso');
144
+		$this->_tables = array(
145
+			'Attendee_CPT'  => new EE_Primary_Table('posts', 'ID'),
146
+			'Attendee_Meta' => new EE_Secondary_Table(
147
+				'esp_attendee_meta',
148
+				'ATTM_ID',
149
+				'ATT_ID'
150
+			),
151
+		);
152
+		$this->_fields = array(
153
+			'Attendee_CPT'  => array(
154
+				'ATT_ID'        => $model_field_factory->createPrimaryKeyIntField(
155
+					'ID',
156
+					esc_html__('Attendee ID', 'event_espresso')
157
+				),
158
+				'ATT_full_name' => $model_field_factory->createPlainTextField(
159
+					'post_title',
160
+					esc_html__('Attendee Full Name', 'event_espresso'),
161
+					false,
162
+					esc_html__('Unknown', 'event_espresso')
163
+				),
164
+				'ATT_bio'       => $model_field_factory->createPostContentField(
165
+					'post_content',
166
+					esc_html__('Attendee Biography', 'event_espresso'),
167
+					false,
168
+					esc_html__('No Biography Provided', 'event_espresso')
169
+				),
170
+				'ATT_slug'      => $model_field_factory->createSlugField(
171
+					'post_name',
172
+					esc_html__('Attendee URL Slug', 'event_espresso')
173
+				),
174
+				'ATT_created'   => $model_field_factory->createDatetimeField(
175
+					'post_date',
176
+					esc_html__('Time Attendee Created', 'event_espresso')
177
+				),
178
+				'ATT_short_bio' => $model_field_factory->createSimpleHtmlField(
179
+					'post_excerpt',
180
+					esc_html__('Attendee Short Biography', 'event_espresso'),
181
+					true,
182
+					esc_html__('No Biography Provided', 'event_espresso')
183
+				),
184
+				'ATT_modified'  => $model_field_factory->createDatetimeField(
185
+					'post_modified',
186
+					esc_html__('Time Attendee Last Modified', 'event_espresso')
187
+				),
188
+				'ATT_author'    => $model_field_factory->createWpUserField(
189
+					'post_author',
190
+					esc_html__('Creator ID of the first Event attended', 'event_espresso'),
191
+					false
192
+				),
193
+				'ATT_parent'    => $model_field_factory->createDbOnlyIntField(
194
+					'post_parent',
195
+					esc_html__('Parent Attendee (unused)', 'event_espresso'),
196
+					false,
197
+					0
198
+				),
199
+				'post_type'     => $model_field_factory->createWpPostTypeField('espresso_attendees'),
200
+				'status'        => $model_field_factory->createWpPostStatusField(
201
+					'post_status',
202
+					esc_html__('Attendee Status', 'event_espresso'),
203
+					false,
204
+					'publish'
205
+				),
206
+			),
207
+			'Attendee_Meta' => array(
208
+				'ATTM_ID'      => $model_field_factory->createDbOnlyIntField(
209
+					'ATTM_ID',
210
+					esc_html__('Attendee Meta Row ID', 'event_espresso'),
211
+					false
212
+				),
213
+				'ATT_ID_fk'    => $model_field_factory->createDbOnlyIntField(
214
+					'ATT_ID',
215
+					esc_html__('Foreign Key to Attendee in Post Table', 'event_espresso'),
216
+					false
217
+				),
218
+				'ATT_fname'    => $model_field_factory->createPlainTextField(
219
+					'ATT_fname',
220
+					esc_html__('First Name', 'event_espresso')
221
+				),
222
+				'ATT_lname'    => $model_field_factory->createPlainTextField(
223
+					'ATT_lname',
224
+					esc_html__('Last Name', 'event_espresso')
225
+				),
226
+				'ATT_address'  => $model_field_factory->createPlainTextField(
227
+					'ATT_address',
228
+					esc_html__('Address Part 1', 'event_espresso')
229
+				),
230
+				'ATT_address2' => $model_field_factory->createPlainTextField(
231
+					'ATT_address2',
232
+					esc_html__('Address Part 2', 'event_espresso')
233
+				),
234
+				'ATT_city'     => $model_field_factory->createPlainTextField(
235
+					'ATT_city',
236
+					esc_html__('City', 'event_espresso')
237
+				),
238
+				'STA_ID'       => $model_field_factory->createForeignKeyIntField(
239
+					'STA_ID',
240
+					esc_html__('State', 'event_espresso'),
241
+					true,
242
+					0,
243
+					'State'
244
+				),
245
+				'CNT_ISO'      => $model_field_factory->createForeignKeyStringField(
246
+					'CNT_ISO',
247
+					esc_html__('Country', 'event_espresso'),
248
+					true,
249
+					'',
250
+					'Country'
251
+				),
252
+				'ATT_zip'      => $model_field_factory->createPlainTextField(
253
+					'ATT_zip',
254
+					esc_html__('ZIP/Postal Code', 'event_espresso')
255
+				),
256
+				'ATT_email'    => $model_field_factory->createEmailField(
257
+					'ATT_email',
258
+					esc_html__('Email Address', 'event_espresso')
259
+				),
260
+				'ATT_phone'    => $model_field_factory->createPlainTextField(
261
+					'ATT_phone',
262
+					esc_html__('Phone', 'event_espresso')
263
+				),
264
+			),
265
+		);
266
+		$this->_model_relations = array(
267
+			'Registration'      => new EE_Has_Many_Relation(),
268
+			'State'             => new EE_Belongs_To_Relation(),
269
+			'Country'           => new EE_Belongs_To_Relation(),
270
+			'Event'             => new EE_HABTM_Relation('Registration', false),
271
+			'WP_User'           => new EE_Belongs_To_Relation(),
272
+			'Message'           => new EE_Has_Many_Any_Relation(false),
273
+			//allow deletion of attendees even if they have messages in the queue for them.
274
+			'Term_Relationship' => new EE_Has_Many_Relation(),
275
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
276
+		);
277
+		$this->_caps_slug = 'contacts';
278
+		parent::__construct($timezone);
279
+	}
280
+
281
+
282
+
283
+	/**
284
+	 * Gets the name of the field on the attendee model corresponding to the system question string
285
+	 * which should be one of the keys from EEM_Attendee::_system_question_to_attendee_field_name
286
+	 *
287
+	 * @param string $system_question_string
288
+	 * @return string|null if not found
289
+	 */
290
+	public function get_attendee_field_for_system_question($system_question_string)
291
+	{
292
+		return isset($this->_system_question_to_attendee_field_name[$system_question_string])
293
+			? $this->_system_question_to_attendee_field_name[$system_question_string]
294
+			: null;
295
+	}
296
+
297
+
298
+
299
+	/**
300
+	 * Gets mapping from esp_question.QST_system values to their corresponding attendee field names
301
+	 *
302
+	 * @return array
303
+	 */
304
+	public function system_question_to_attendee_field_mapping()
305
+	{
306
+		return $this->_system_question_to_attendee_field_name;
307
+	}
308
+
309
+
310
+
311
+	/**
312
+	 * Gets all the attendees for a transaction (by using the esp_registration as a join table)
313
+	 *
314
+	 * @param EE_Transaction /int $transaction_id_or_obj EE_Transaction or its ID
315
+	 * @return EE_Attendee[]|EE_Base_Class[]
316
+	 * @throws EE_Error
317
+	 */
318
+	public function get_attendees_for_transaction($transaction_id_or_obj)
319
+	{
320
+		return $this->get_all(
321
+			array(
322
+				array(
323
+					'Registration.Transaction.TXN_ID' => $transaction_id_or_obj instanceof EE_Transaction
324
+						? $transaction_id_or_obj->ID()
325
+						: $transaction_id_or_obj,
326
+				),
327
+			)
328
+		);
329
+	}
330
+
331
+
332
+
333
+	/**
334
+	 * retrieve  a single attendee from db via their ID
335
+	 *
336
+	 * @param $ATT_ID
337
+	 * @return mixed array on success, FALSE on fail
338
+	 * @deprecated
339
+	 */
340
+	public function get_attendee_by_ID($ATT_ID = false)
341
+	{
342
+		// retrieve a particular EE_Attendee
343
+		return $this->get_one_by_ID($ATT_ID);
344
+	}
345
+
346
+
347
+
348
+	/**
349
+	 * retrieve  a single attendee from db via their ID
350
+	 *
351
+	 * @param array $where_cols_n_values
352
+	 * @return mixed array on success, FALSE on fail
353
+	 * @throws EE_Error
354
+	 */
355
+	public function get_attendee($where_cols_n_values = array())
356
+	{
357
+		if (empty($where_cols_n_values)) {
358
+			return false;
359
+		}
360
+		$attendee = $this->get_all(array($where_cols_n_values));
361
+		if (! empty($attendee)) {
362
+			return array_shift($attendee);
363
+		}
364
+		return false;
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * Search for an existing Attendee record in the DB
371
+	 *
372
+	 * @param array $where_cols_n_values
373
+	 * @return bool|mixed
374
+	 * @throws EE_Error
375
+	 */
376
+	public function find_existing_attendee($where_cols_n_values = null)
377
+	{
378
+		// search by combo of first and last names plus the email address
379
+		$attendee_data_keys = array(
380
+			'ATT_fname' => $this->_ATT_fname,
381
+			'ATT_lname' => $this->_ATT_lname,
382
+			'ATT_email' => $this->_ATT_email,
383
+		);
384
+		// no search params means attendee object already exists.
385
+		$where_cols_n_values = is_array($where_cols_n_values) && ! empty($where_cols_n_values)
386
+			? $where_cols_n_values
387
+			: $attendee_data_keys;
388
+		$valid_data = true;
389
+		// check for required values
390
+		$valid_data = isset($where_cols_n_values['ATT_fname']) && ! empty($where_cols_n_values['ATT_fname'])
391
+			? $valid_data
392
+			: false;
393
+		$valid_data = isset($where_cols_n_values['ATT_lname']) && ! empty($where_cols_n_values['ATT_lname'])
394
+			? $valid_data
395
+			: false;
396
+		$valid_data = isset($where_cols_n_values['ATT_email']) && ! empty($where_cols_n_values['ATT_email'])
397
+			? $valid_data
398
+			: false;
399
+		if ($valid_data) {
400
+			$attendee = $this->get_attendee($where_cols_n_values);
401
+			if ($attendee instanceof EE_Attendee) {
402
+				return $attendee;
403
+			}
404
+		}
405
+		return false;
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * Takes an incoming array of EE_Registration ids
412
+	 * and sends back a list of corresponding non duplicate EE_Attendee objects.
413
+	 *
414
+	 * @since  4.3.0
415
+	 * @param  array $ids array of EE_Registration ids
416
+	 * @return EE_Attendee[]|EE_Base_Class[]
417
+	 * @throws EE_Error
418
+	 */
419
+	public function get_array_of_contacts_from_reg_ids($ids)
420
+	{
421
+		$ids = (array)$ids;
422
+		$_where = array(
423
+			'Registration.REG_ID' => array('in', $ids),
424
+		);
425
+		return $this->get_all(array($_where));
426
+	}
427 427
 
428 428
 
429 429
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Event.model.php 3 patches
Unused Use Statements   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@
 block discarded – undo
1
-<?php use EventEspresso\core\services\orm\ModelFieldFactory;
1
+<?php 
2 2
 
3 3
 if (! defined('EVENT_ESPRESSO_VERSION')) {
4 4
     exit('No direct script access allowed');
Please login to merge, or discard this patch.
Indentation   +767 added lines, -767 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\orm\ModelFieldFactory;
2 2
 
3 3
 if (! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('No direct script access allowed');
4
+	exit('No direct script access allowed');
5 5
 }
6 6
 require_once(EE_MODELS . 'EEM_CPT_Base.model.php');
7 7
 
@@ -18,772 +18,772 @@  discard block
 block discarded – undo
18 18
 class EEM_Event extends EEM_CPT_Base
19 19
 {
20 20
 
21
-    /**
22
-     * constant used by status(), indicating that no more tickets can be purchased for any of the datetimes for the
23
-     * event
24
-     */
25
-    const sold_out = 'sold_out';
26
-
27
-    /**
28
-     * constant used by status(), indicating that upcoming event dates have been postponed (may be pushed to a later
29
-     * date)
30
-     */
31
-    const postponed = 'postponed';
32
-
33
-    /**
34
-     * constant used by status(), indicating that the event will no longer occur
35
-     */
36
-    const cancelled = 'cancelled';
37
-
38
-
39
-    /**
40
-     * @var string
41
-     */
42
-    protected static $_default_reg_status;
43
-
44
-
45
-    /**
46
-     * This is the default for the additional limit field.
47
-     * @var int
48
-     */
49
-    protected static $_default_additional_limit = 10;
50
-
51
-
52
-    /**
53
-     * private instance of the Event object
54
-     *
55
-     * @var EEM_Event
56
-     */
57
-    protected static $_instance;
58
-
59
-
60
-
61
-
62
-    /**
63
-     * Adds a relationship to Term_Taxonomy for each CPT_Base
64
-     *
65
-     * @param string $timezone
66
-     * @throws \EE_Error
67
-     */
68
-    protected function __construct($timezone = null)
69
-    {
70
-        EE_Registry::instance()->load_model('Registration');
71
-        $this->singular_item = esc_html__('Event', 'event_espresso');
72
-        $this->plural_item = esc_html__('Events', 'event_espresso');
73
-        // to remove Cancelled events from the frontend, copy the following filter to your functions.php file
74
-        // add_filter( 'AFEE__EEM_Event__construct___custom_stati__cancelled__Public', '__return_false' );
75
-        // to remove Postponed events from the frontend, copy the following filter to your functions.php file
76
-        // add_filter( 'AFEE__EEM_Event__construct___custom_stati__postponed__Public', '__return_false' );
77
-        // to remove Sold Out events from the frontend, copy the following filter to your functions.php file
78
-        //	add_filter( 'AFEE__EEM_Event__construct___custom_stati__sold_out__Public', '__return_false' );
79
-        $this->_custom_stati = apply_filters(
80
-            'AFEE__EEM_Event__construct___custom_stati',
81
-            array(
82
-                EEM_Event::cancelled => array(
83
-                    'label'  => esc_html__('Cancelled', 'event_espresso'),
84
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__cancelled__Public', true),
85
-                ),
86
-                EEM_Event::postponed => array(
87
-                    'label'  => esc_html__('Postponed', 'event_espresso'),
88
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__postponed__Public', true),
89
-                ),
90
-                EEM_Event::sold_out  => array(
91
-                    'label'  => esc_html__('Sold Out', 'event_espresso'),
92
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__sold_out__Public', true),
93
-                ),
94
-            )
95
-        );
96
-        self::$_default_reg_status = empty(self::$_default_reg_status) ? EEM_Registration::status_id_pending_payment
97
-            : self::$_default_reg_status;
98
-        $this->_tables = array(
99
-            'Event_CPT'  => new EE_Primary_Table('posts', 'ID'),
100
-            'Event_Meta' => new EE_Secondary_Table('esp_event_meta', 'EVTM_ID', 'EVT_ID'),
101
-        );
102
-        $this->_fields = array(
103
-            'Event_CPT'  => array(
104
-                'EVT_ID'         => new EE_Primary_Key_Int_Field('ID',
105
-                    esc_html__('Post ID for Event', 'event_espresso')),
106
-                'EVT_name'       => new EE_Plain_Text_Field('post_title', esc_html__('Event Name', 'event_espresso'),
107
-                    false,
108
-                    ''),
109
-                'EVT_desc'       => new EE_Post_Content_Field('post_content',
110
-                    esc_html__('Event Description', 'event_espresso'),
111
-                    false, ''),
112
-                'EVT_slug'       => new EE_Slug_Field('post_name', esc_html__('Event Slug', 'event_espresso'), false,
113
-                    ''),
114
-                'EVT_created'    => new EE_Datetime_Field('post_date',
115
-                    esc_html__('Date/Time Event Created', 'event_espresso'),
116
-                    false, EE_Datetime_Field::now),
117
-                'EVT_short_desc' => new EE_Simple_HTML_Field('post_excerpt',
118
-                    esc_html__('Event Short Description', 'event_espresso'), false, ''),
119
-                'EVT_modified'   => new EE_Datetime_Field('post_modified',
120
-                    esc_html__('Date/Time Event Modified', 'event_espresso'), false, EE_Datetime_Field::now),
121
-                'EVT_wp_user'    => new EE_WP_User_Field('post_author',
122
-                    esc_html__('Event Creator ID', 'event_espresso'),
123
-                    false),
124
-                'parent'         => new EE_Integer_Field('post_parent', esc_html__('Event Parent ID', 'event_espresso'),
125
-                    false,
126
-                    0),
127
-                'EVT_order'      => new EE_Integer_Field('menu_order', esc_html__('Event Menu Order', 'event_espresso'),
128
-                    false,
129
-                    1),
130
-                'post_type'      => new EE_WP_Post_Type_Field('espresso_events'),
131
-                // EE_Plain_Text_Field( 'post_type', esc_html__( 'Event Post Type', 'event_espresso' ), FALSE, 'espresso_events' ),
132
-                'status'         => new EE_WP_Post_Status_Field('post_status',
133
-                    esc_html__('Event Status', 'event_espresso'),
134
-                    false, 'draft', $this->_custom_stati),
135
-            ),
136
-            'Event_Meta' => array(
137
-                'EVTM_ID'                         => new EE_DB_Only_Float_Field('EVTM_ID',
138
-                    esc_html__('Event Meta Row ID', 'event_espresso'), false),
139
-                'EVT_ID_fk'                       => new EE_DB_Only_Int_Field('EVT_ID',
140
-                    esc_html__('Foreign key to Event ID from Event Meta table', 'event_espresso'), false),
141
-                'EVT_display_desc'                => new EE_Boolean_Field('EVT_display_desc',
142
-                    esc_html__('Display Description Flag', 'event_espresso'), false, 1),
143
-                'EVT_display_ticket_selector'     => new EE_Boolean_Field('EVT_display_ticket_selector',
144
-                    esc_html__('Display Ticket Selector Flag', 'event_espresso'), false, 1),
145
-                'EVT_visible_on'                  => new EE_Datetime_Field('EVT_visible_on',
146
-                    esc_html__('Event Visible Date', 'event_espresso'), true, EE_Datetime_Field::now),
147
-                'EVT_additional_limit'            => new EE_Integer_Field(
148
-                    'EVT_additional_limit',
149
-                    esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
150
-                    true,
151
-                    self::$_default_additional_limit
152
-                ),
153
-                'EVT_default_registration_status' => new EE_Enum_Text_Field(
154
-                    'EVT_default_registration_status',
155
-                    esc_html__('Default Registration Status on this Event', 'event_espresso'), false,
156
-                    EEM_Event::$_default_reg_status, EEM_Registration::reg_status_array()
157
-                ),
158
-                'EVT_member_only'                 => new EE_Boolean_Field('EVT_member_only',
159
-                    esc_html__('Member-Only Event Flag', 'event_espresso'), false, false),
160
-                'EVT_phone'                       => new EE_Plain_Text_Field('EVT_phone',
161
-                    esc_html__('Event Phone Number', 'event_espresso'), false),
162
-                'EVT_allow_overflow'              => new EE_Boolean_Field('EVT_allow_overflow',
163
-                    esc_html__('Allow Overflow on Event', 'event_espresso'), false, false),
164
-                'EVT_timezone_string'             => new EE_Plain_Text_Field('EVT_timezone_string',
165
-                    esc_html__('Timezone (name) for Event times', 'event_espresso'), false),
166
-                'EVT_external_URL'                => new EE_Plain_Text_Field('EVT_external_URL',
167
-                    esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso'), true),
168
-                'EVT_donations'                   => new EE_Boolean_Field('EVT_donations',
169
-                    esc_html__('Accept Donations?', 'event_espresso'), false, false),
170
-            ),
171
-        );
172
-        $this->_model_relations = array(
173
-            'Registration'           => new EE_Has_Many_Relation(),
174
-            'Datetime'               => new EE_Has_Many_Relation(),
175
-            'Question_Group'         => new EE_HABTM_Relation('Event_Question_Group'),
176
-            'Venue'                  => new EE_HABTM_Relation('Event_Venue'),
177
-            'Term_Relationship'      => new EE_Has_Many_Relation(),
178
-            'Term_Taxonomy'          => new EE_HABTM_Relation('Term_Relationship'),
179
-            'Message_Template_Group' => new EE_HABTM_Relation('Event_Message_Template'),
180
-            'Attendee'               => new EE_HABTM_Relation('Registration'),
181
-            'WP_User'                => new EE_Belongs_To_Relation(),
182
-        );
183
-        //this model is generally available for reading
184
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
185
-        parent::__construct($timezone);
186
-    }
187
-
188
-
189
-
190
-    /**
191
-     * @param string $default_reg_status
192
-     */
193
-    public static function set_default_reg_status($default_reg_status)
194
-    {
195
-        self::$_default_reg_status = $default_reg_status;
196
-        // if EEM_Event has already been instantiated,
197
-        // then we need to reset the `EVT_default_reg_status` field to use the new default.
198
-        if (self::$_instance instanceof EEM_Event) {
199
-            $default_reg_status = new EE_Enum_Text_Field(
200
-                'EVT_default_registration_status',
201
-                esc_html__('Default Registration Status on this Event', 'event_espresso'),
202
-                false,
203
-                $default_reg_status,
204
-                EEM_Registration::reg_status_array()
205
-            );
206
-            $default_reg_status->_construct_finalize(
207
-                'Event_Meta',
208
-                'EVT_default_registration_status',
209
-                'EEM_Event'
210
-            );
211
-            self::$_instance->_fields['Event_Meta']['EVT_default_registration_status'] = $default_reg_status;
212
-        }
213
-    }
214
-
215
-
216
-    /**
217
-     * Used to override the default for the additional limit field.
218
-     * @param $additional_limit
219
-     */
220
-    public static function set_default_additional_limit($additional_limit)
221
-    {
222
-        self::$_default_additional_limit = (int) $additional_limit;
223
-        if (self::$_instance instanceof EEM_Event) {
224
-            self::$_instance->_fields['Event_Meta']['EVT_additional_limit'] = new EE_Integer_Field(
225
-                'EVT_additional_limit',
226
-                __('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
227
-                true,
228
-                self::$_default_additional_limit
229
-            );
230
-            self::$_instance->_fields['Event_Meta']['EVT_additional_limit']->_construct_finalize(
231
-                'Event_Meta',
232
-                'EVT_additional_limit',
233
-                'EEM_Event'
234
-            );
235
-        }
236
-    }
237
-
238
-
239
-    /**
240
-     * Return what is currently set as the default additional limit for the event.
241
-     * @return int
242
-     */
243
-    public static function get_default_additional_limit()
244
-    {
245
-        return apply_filters('FHEE__EEM_Event__get_default_additional_limit', self::$_default_additional_limit);
246
-    }
247
-
248
-
249
-    /**
250
-     * get_question_groups
251
-     *
252
-     * @return array
253
-     * @throws \EE_Error
254
-     */
255
-    public function get_all_question_groups()
256
-    {
257
-        return EE_Registry::instance()->load_model('Question_Group')->get_all(
258
-            array(
259
-                array('QSG_deleted' => false),
260
-                'order_by' => array('QSG_order' => 'ASC'),
261
-            )
262
-        );
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * get_question_groups
269
-     *
270
-     * @param int $EVT_ID
271
-     * @return array|bool
272
-     * @throws \EE_Error
273
-     */
274
-    public function get_all_event_question_groups($EVT_ID = 0)
275
-    {
276
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
277
-            EE_Error::add_error(
278
-                esc_html__(
279
-                    'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
280
-                    'event_espresso'
281
-                ),
282
-                __FILE__, __FUNCTION__, __LINE__
283
-            );
284
-            return false;
285
-        }
286
-        return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
287
-            array(
288
-                array('EVT_ID' => $EVT_ID),
289
-            )
290
-        );
291
-    }
292
-
293
-
294
-
295
-    /**
296
-     * get_question_groups
297
-     *
298
-     * @param int     $EVT_ID
299
-     * @param boolean $for_primary_attendee
300
-     * @return array|bool
301
-     * @throws \EE_Error
302
-     */
303
-    public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
304
-    {
305
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
306
-            EE_Error::add_error(
307
-                esc_html__(
308
-                    'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
309
-                    'event_espresso'
310
-                ),
311
-                __FILE__, __FUNCTION__, __LINE__
312
-            );
313
-            return false;
314
-        }
315
-        return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
316
-            array(
317
-                array(
318
-                    'EVT_ID'      => $EVT_ID,
319
-                    'EQG_primary' => $for_primary_attendee,
320
-                ),
321
-            )
322
-        );
323
-    }
324
-
325
-
326
-
327
-    /**
328
-     * get_question_groups
329
-     *
330
-     * @param int             $EVT_ID
331
-     * @param EE_Registration $registration
332
-     * @return array|bool
333
-     * @throws \EE_Error
334
-     */
335
-    public function get_question_groups_for_event($EVT_ID = 0, EE_Registration $registration)
336
-    {
337
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
338
-            EE_Error::add_error(
339
-                esc_html__(
340
-                    'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
341
-                    'event_espresso'
342
-                ),
343
-                __FILE__, __FUNCTION__, __LINE__
344
-            );
345
-            return false;
346
-        }
347
-        $where_params = array(
348
-            'Event_Question_Group.EVT_ID'      => $EVT_ID,
349
-            'Event_Question_Group.EQG_primary' => $registration->count() === 1 ? true : false,
350
-            'QSG_deleted'                      => false,
351
-        );
352
-        return EE_Registry::instance()->load_model('Question_Group')->get_all(
353
-            array(
354
-                $where_params,
355
-                'order_by' => array('QSG_order' => 'ASC'),
356
-            )
357
-        );
358
-    }
359
-
360
-
361
-
362
-    /**
363
-     * get_question_target_db_column
364
-     *
365
-     * @param string $QSG_IDs csv list of $QSG IDs
366
-     * @return array|bool
367
-     * @throws \EE_Error
368
-     */
369
-    public function get_questions_in_groups($QSG_IDs = '')
370
-    {
371
-        if (empty($QSG_IDs)) {
372
-            EE_Error::add_error(
373
-                esc_html__('An error occurred. No Question Group IDs were received.', 'event_espresso'),
374
-                __FILE__, __FUNCTION__, __LINE__
375
-            );
376
-            return false;
377
-        }
378
-        return EE_Registry::instance()->load_model('Question')->get_all(
379
-            array(
380
-                array(
381
-                    'Question_Group.QSG_ID' => array('IN', $QSG_IDs),
382
-                    'QST_deleted'           => false,
383
-                    'QST_admin_only'        => is_admin(),
384
-                ),
385
-                'order_by' => 'QST_order',
386
-            )
387
-        );
388
-    }
389
-
390
-
391
-
392
-    /**
393
-     * get_options_for_question
394
-     *
395
-     * @param string $QST_IDs csv list of $QST IDs
396
-     * @return array|bool
397
-     * @throws \EE_Error
398
-     */
399
-    public function get_options_for_question($QST_IDs)
400
-    {
401
-        if (empty($QST_IDs)) {
402
-            EE_Error::add_error(
403
-                esc_html__('An error occurred. No Question IDs were received.', 'event_espresso'),
404
-                __FILE__, __FUNCTION__, __LINE__
405
-            );
406
-            return false;
407
-        }
408
-        return EE_Registry::instance()->load_model('Question_Option')->get_all(
409
-            array(
410
-                array(
411
-                    'Question.QST_ID' => array('IN', $QST_IDs),
412
-                    'QSO_deleted'     => false,
413
-                ),
414
-                'order_by' => 'QSO_ID',
415
-            )
416
-        );
417
-    }
418
-
419
-
420
-
421
-
422
-
423
-
424
-
425
-    /**
426
-     * Gets all events that are published
427
-     * and have event start time earlier than now and an event end time later than now
428
-     *
429
-     * @param  array $query_params An array of query params to further filter on
430
-     *                             (note that status and DTT_EVT_start and DTT_EVT_end will be overridden)
431
-     * @param bool   $count        whether to return the count or not (default FALSE)
432
-     * @return EE_Event[]|int
433
-     * @throws \EE_Error
434
-     */
435
-    public function get_active_events($query_params, $count = false)
436
-    {
437
-        if (array_key_exists(0, $query_params)) {
438
-            $where_params = $query_params[0];
439
-            unset($query_params[0]);
440
-        } else {
441
-            $where_params = array();
442
-        }
443
-        // if we have count make sure we don't include group by
444
-        if ($count && isset($query_params['group_by'])) {
445
-            unset($query_params['group_by']);
446
-        }
447
-        // let's add specific query_params for active_events
448
-        // keep in mind this will override any sent status in the query AND any date queries.
449
-        $where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
450
-        //if already have where params for DTT_EVT_start or DTT_EVT_end then append these conditions
451
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
452
-            $where_params['Datetime.DTT_EVT_start******'] = array(
453
-                '<',
454
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
455
-            );
456
-        } else {
457
-            $where_params['Datetime.DTT_EVT_start'] = array(
458
-                '<',
459
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
460
-            );
461
-        }
462
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
463
-            $where_params['Datetime.DTT_EVT_end*****'] = array(
464
-                '>',
465
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
466
-            );
467
-        } else {
468
-            $where_params['Datetime.DTT_EVT_end'] = array(
469
-                '>',
470
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
471
-            );
472
-        }
473
-        $query_params[0] = $where_params;
474
-        // don't use $query_params with count()
475
-        // because we don't want to include additional query clauses like "GROUP BY"
476
-        return $count
477
-            ? $this->count(array($where_params), 'EVT_ID', true)
478
-            : $this->get_all($query_params);
479
-    }
480
-
481
-
482
-
483
-    /**
484
-     * get all events that are published and have an event start time later than now
485
-     *
486
-     * @param  array $query_params An array of query params to further filter on
487
-     *                             (Note that status and DTT_EVT_start will be overridden)
488
-     * @param bool   $count        whether to return the count or not (default FALSE)
489
-     * @return EE_Event[]|int
490
-     * @throws \EE_Error
491
-     */
492
-    public function get_upcoming_events($query_params, $count = false)
493
-    {
494
-        if (array_key_exists(0, $query_params)) {
495
-            $where_params = $query_params[0];
496
-            unset($query_params[0]);
497
-        } else {
498
-            $where_params = array();
499
-        }
500
-        // if we have count make sure we don't include group by
501
-        if ($count && isset($query_params['group_by'])) {
502
-            unset($query_params['group_by']);
503
-        }
504
-        // let's add specific query_params for active_events
505
-        // keep in mind this will override any sent status in the query AND any date queries.
506
-        $where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
507
-        // if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
508
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
509
-            $where_params['Datetime.DTT_EVT_start*****'] = array(
510
-                '>',
511
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
512
-            );
513
-        } else {
514
-            $where_params['Datetime.DTT_EVT_start'] = array(
515
-                '>',
516
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
517
-            );
518
-        }
519
-        $query_params[0] = $where_params;
520
-        // don't use $query_params with count()
521
-        // because we don't want to include additional query clauses like "GROUP BY"
522
-        return $count
523
-            ? $this->count(array($where_params), 'EVT_ID', true)
524
-            : $this->get_all($query_params);
525
-    }
526
-
527
-
528
-
529
-    /**
530
-     * Gets all events that are published
531
-     * and have an event end time later than now
532
-     *
533
-     * @param  array $query_params An array of query params to further filter on
534
-     *                             (note that status and DTT_EVT_end will be overridden)
535
-     * @param bool   $count        whether to return the count or not (default FALSE)
536
-     * @return EE_Event[]|int
537
-     * @throws \EE_Error
538
-     */
539
-    public function get_active_and_upcoming_events($query_params, $count = false)
540
-    {
541
-        if (array_key_exists(0, $query_params)) {
542
-            $where_params = $query_params[0];
543
-            unset($query_params[0]);
544
-        } else {
545
-            $where_params = array();
546
-        }
547
-        // if we have count make sure we don't include group by
548
-        if ($count && isset($query_params['group_by'])) {
549
-            unset($query_params['group_by']);
550
-        }
551
-        // let's add specific query_params for active_events
552
-        // keep in mind this will override any sent status in the query AND any date queries.
553
-        $where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
554
-        // add where params for DTT_EVT_end
555
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
556
-            $where_params['Datetime.DTT_EVT_end*****'] = array(
557
-                '>',
558
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
559
-            );
560
-        } else {
561
-            $where_params['Datetime.DTT_EVT_end'] = array(
562
-                '>',
563
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
564
-            );
565
-        }
566
-        $query_params[0] = $where_params;
567
-        // don't use $query_params with count()
568
-        // because we don't want to include additional query clauses like "GROUP BY"
569
-        return $count
570
-            ? $this->count(array($where_params), 'EVT_ID', true)
571
-            : $this->get_all($query_params);
572
-    }
573
-
574
-
575
-
576
-    /**
577
-     * This only returns events that are expired.
578
-     * They may still be published but all their datetimes have expired.
579
-     *
580
-     * @param  array $query_params An array of query params to further filter on
581
-     *                             (note that status and DTT_EVT_end will be overridden)
582
-     * @param bool   $count        whether to return the count or not (default FALSE)
583
-     * @return EE_Event[]|int
584
-     * @throws \EE_Error
585
-     */
586
-    public function get_expired_events($query_params, $count = false)
587
-    {
588
-        $where_params = isset($query_params[0]) ? $query_params[0] : array();
589
-        // if we have count make sure we don't include group by
590
-        if ($count && isset($query_params['group_by'])) {
591
-            unset($query_params['group_by']);
592
-        }
593
-        // let's add specific query_params for active_events
594
-        // keep in mind this will override any sent status in the query AND any date queries.
595
-        if (isset($where_params['status'])) {
596
-            unset($where_params['status']);
597
-        }
598
-        $exclude_query = $query_params;
599
-        if (isset($exclude_query[0])) {
600
-            unset($exclude_query[0]);
601
-        }
602
-        $exclude_query[0] = array(
603
-            'Datetime.DTT_EVT_end' => array(
604
-                '>',
605
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
606
-            ),
607
-        );
608
-        // first get all events that have datetimes where its not expired.
609
-        $event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Event_CPT.ID');
610
-        $event_ids = array_keys($event_ids);
611
-        // if we have any additional query_params, let's add them to the 'AND' condition
612
-        $and_condition = array(
613
-            'Datetime.DTT_EVT_end' => array('<', EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end')),
614
-            'EVT_ID'               => array('NOT IN', $event_ids),
615
-        );
616
-        if (isset($where_params['OR'])) {
617
-            $and_condition['OR'] = $where_params['OR'];
618
-            unset($where_params['OR']);
619
-        }
620
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
621
-            $and_condition['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
622
-            unset($where_params['Datetime.DTT_EVT_end']);
623
-        }
624
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
625
-            $and_condition['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
626
-            unset($where_params['Datetime.DTT_EVT_start']);
627
-        }
628
-        // merge remaining $where params with the and conditions.
629
-        $where_params['AND'] = array_merge($and_condition, $where_params);
630
-        $query_params[0] = $where_params;
631
-        // don't use $query_params with count()
632
-        // because we don't want to include additional query clauses like "GROUP BY"
633
-        return $count
634
-            ? $this->count(array($where_params), 'EVT_ID', true)
635
-            : $this->get_all($query_params);
636
-    }
637
-
638
-
639
-
640
-    /**
641
-     * This basically just returns the events that do not have the publish status.
642
-     *
643
-     * @param  array   $query_params An array of query params to further filter on
644
-     *                               (note that status will be overwritten)
645
-     * @param  boolean $count        whether to return the count or not (default FALSE)
646
-     * @return EE_Event[]|int
647
-     * @throws \EE_Error
648
-     */
649
-    public function get_inactive_events($query_params, $count = false)
650
-    {
651
-        $where_params = isset($query_params[0]) ? $query_params[0] : array();
652
-        // let's add in specific query_params for inactive events.
653
-        if (isset($where_params['status'])) {
654
-            unset($where_params['status']);
655
-        }
656
-        // if we have count make sure we don't include group by
657
-        if ($count && isset($query_params['group_by'])) {
658
-            unset($query_params['group_by']);
659
-        }
660
-        // if we have any additional query_params, let's add them to the 'AND' condition
661
-        $where_params['AND']['status'] = array('!=', 'publish');
662
-        if (isset($where_params['OR'])) {
663
-            $where_params['AND']['OR'] = $where_params['OR'];
664
-            unset($where_params['OR']);
665
-        }
666
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
667
-            $where_params['AND']['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
668
-            unset($where_params['Datetime.DTT_EVT_end']);
669
-        }
670
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
671
-            $where_params['AND']['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
672
-            unset($where_params['Datetime.DTT_EVT_start']);
673
-        }
674
-        $query_params[0] = $where_params;
675
-        // don't use $query_params with count()
676
-        // because we don't want to include additional query clauses like "GROUP BY"
677
-        return $count
678
-            ? $this->count(array($where_params), 'EVT_ID', true)
679
-            : $this->get_all($query_params);
680
-    }
681
-
682
-
683
-
684
-    /**
685
-     * This is just injecting into the parent add_relationship_to so we do special handling on price relationships
686
-     * because we don't want to override any existing global default prices but instead insert NEW prices that get
687
-     * attached to the event. See parent for param descriptions
688
-     *
689
-     * @param        $id_or_obj
690
-     * @param        $other_model_id_or_obj
691
-     * @param string $relationName
692
-     * @param array  $where_query
693
-     * @return EE_Base_Class
694
-     * @throws EE_Error
695
-     */
696
-    public function add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
697
-    {
698
-        if ($relationName === 'Price') {
699
-            //let's get the PRC object for the given ID to make sure that we aren't dealing with a default
700
-            $prc_chk = $this->get_related_model_obj($relationName)->ensure_is_obj($other_model_id_or_obj);
701
-            //if EVT_ID = 0, then this is a default
702
-            if ((int) $prc_chk->get('EVT_ID') === 0) {
703
-                //let's set the prc_id as 0 so we force an insert on the add_relation_to carried out by relation
704
-                $prc_chk->set('PRC_ID', 0);
705
-            }
706
-            //run parent
707
-            return parent::add_relationship_to($id_or_obj, $prc_chk, $relationName, $where_query);
708
-        }
709
-        //otherwise carry on as normal
710
-        return parent::add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query);
711
-    }
712
-
713
-
714
-
715
-    /******************** DEPRECATED METHODS ********************/
716
-
717
-
718
-
719
-    /**
720
-     * _get_question_target_db_column
721
-     *
722
-     * @deprecated as of 4.8.32.rc.001. Instead consider using
723
-     *             EE_Registration_Custom_Questions_Form located in
724
-     *             admin_pages/registrations/form_sections/EE_Registration_Custom_Questions_Form.form.php
725
-     * @access     public
726
-     * @param    EE_Registration $registration (so existing answers for registration are included)
727
-     * @param    int             $EVT_ID       so all question groups are included for event (not just answers from
728
-     *                                         registration).
729
-     * @throws EE_Error
730
-     * @return    array
731
-     */
732
-    public function assemble_array_of_groups_questions_and_options(EE_Registration $registration, $EVT_ID = 0)
733
-    {
734
-        if (empty($EVT_ID)) {
735
-            throw new EE_Error(__('An error occurred. No EVT_ID is included.  Needed to know which question groups to retrieve.',
736
-                'event_espresso'));
737
-        }
738
-        $questions = array();
739
-        // get all question groups for event
740
-        $qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
741
-        if (! empty($qgs)) {
742
-            foreach ($qgs as $qg) {
743
-                $qsts = $qg->questions();
744
-                $questions[$qg->ID()] = $qg->model_field_array();
745
-                $questions[$qg->ID()]['QSG_questions'] = array();
746
-                foreach ($qsts as $qst) {
747
-                    if ($qst->is_system_question()) {
748
-                        continue;
749
-                    }
750
-                    $answer = EEM_Answer::instance()->get_one(array(
751
-                        array(
752
-                            'QST_ID' => $qst->ID(),
753
-                            'REG_ID' => $registration->ID(),
754
-                        ),
755
-                    ));
756
-                    $answer = $answer instanceof EE_Answer ? $answer : EEM_Answer::instance()->create_default_object();
757
-                    $qst_name = $qstn_id = $qst->ID();
758
-                    $ans_id = $answer->ID();
759
-                    $qst_name = ! empty($ans_id) ? '[' . $qst_name . '][' . $ans_id . ']' : '[' . $qst_name . ']';
760
-                    $input_name = '';
761
-                    $input_id = sanitize_key($qst->display_text());
762
-                    $input_class = '';
763
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()] = $qst->model_field_array();
764
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_name'] = 'qstn'
765
-                                                                                           . $input_name
766
-                                                                                           . $qst_name;
767
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_id'] = $input_id . '-' . $qstn_id;
768
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_class'] = $input_class;
769
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_options'] = array();
770
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['qst_obj'] = $qst;
771
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['ans_obj'] = $answer;
772
-                    //leave responses as-is, don't convert stuff into html entities please!
773
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['htmlentities'] = false;
774
-                    if ($qst->type() == 'RADIO_BTN' || $qst->type() == 'CHECKBOX' || $qst->type() == 'DROPDOWN') {
775
-                        $QSOs = $qst->options(true, $answer->value());
776
-                        if (is_array($QSOs)) {
777
-                            foreach ($QSOs as $QSO_ID => $QSO) {
778
-                                $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_options'][$QSO_ID] = $QSO->model_field_array();
779
-                            }
780
-                        }
781
-                    }
782
-                }
783
-            }
784
-        }
785
-        return $questions;
786
-    }
21
+	/**
22
+	 * constant used by status(), indicating that no more tickets can be purchased for any of the datetimes for the
23
+	 * event
24
+	 */
25
+	const sold_out = 'sold_out';
26
+
27
+	/**
28
+	 * constant used by status(), indicating that upcoming event dates have been postponed (may be pushed to a later
29
+	 * date)
30
+	 */
31
+	const postponed = 'postponed';
32
+
33
+	/**
34
+	 * constant used by status(), indicating that the event will no longer occur
35
+	 */
36
+	const cancelled = 'cancelled';
37
+
38
+
39
+	/**
40
+	 * @var string
41
+	 */
42
+	protected static $_default_reg_status;
43
+
44
+
45
+	/**
46
+	 * This is the default for the additional limit field.
47
+	 * @var int
48
+	 */
49
+	protected static $_default_additional_limit = 10;
50
+
51
+
52
+	/**
53
+	 * private instance of the Event object
54
+	 *
55
+	 * @var EEM_Event
56
+	 */
57
+	protected static $_instance;
58
+
59
+
60
+
61
+
62
+	/**
63
+	 * Adds a relationship to Term_Taxonomy for each CPT_Base
64
+	 *
65
+	 * @param string $timezone
66
+	 * @throws \EE_Error
67
+	 */
68
+	protected function __construct($timezone = null)
69
+	{
70
+		EE_Registry::instance()->load_model('Registration');
71
+		$this->singular_item = esc_html__('Event', 'event_espresso');
72
+		$this->plural_item = esc_html__('Events', 'event_espresso');
73
+		// to remove Cancelled events from the frontend, copy the following filter to your functions.php file
74
+		// add_filter( 'AFEE__EEM_Event__construct___custom_stati__cancelled__Public', '__return_false' );
75
+		// to remove Postponed events from the frontend, copy the following filter to your functions.php file
76
+		// add_filter( 'AFEE__EEM_Event__construct___custom_stati__postponed__Public', '__return_false' );
77
+		// to remove Sold Out events from the frontend, copy the following filter to your functions.php file
78
+		//	add_filter( 'AFEE__EEM_Event__construct___custom_stati__sold_out__Public', '__return_false' );
79
+		$this->_custom_stati = apply_filters(
80
+			'AFEE__EEM_Event__construct___custom_stati',
81
+			array(
82
+				EEM_Event::cancelled => array(
83
+					'label'  => esc_html__('Cancelled', 'event_espresso'),
84
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__cancelled__Public', true),
85
+				),
86
+				EEM_Event::postponed => array(
87
+					'label'  => esc_html__('Postponed', 'event_espresso'),
88
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__postponed__Public', true),
89
+				),
90
+				EEM_Event::sold_out  => array(
91
+					'label'  => esc_html__('Sold Out', 'event_espresso'),
92
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__sold_out__Public', true),
93
+				),
94
+			)
95
+		);
96
+		self::$_default_reg_status = empty(self::$_default_reg_status) ? EEM_Registration::status_id_pending_payment
97
+			: self::$_default_reg_status;
98
+		$this->_tables = array(
99
+			'Event_CPT'  => new EE_Primary_Table('posts', 'ID'),
100
+			'Event_Meta' => new EE_Secondary_Table('esp_event_meta', 'EVTM_ID', 'EVT_ID'),
101
+		);
102
+		$this->_fields = array(
103
+			'Event_CPT'  => array(
104
+				'EVT_ID'         => new EE_Primary_Key_Int_Field('ID',
105
+					esc_html__('Post ID for Event', 'event_espresso')),
106
+				'EVT_name'       => new EE_Plain_Text_Field('post_title', esc_html__('Event Name', 'event_espresso'),
107
+					false,
108
+					''),
109
+				'EVT_desc'       => new EE_Post_Content_Field('post_content',
110
+					esc_html__('Event Description', 'event_espresso'),
111
+					false, ''),
112
+				'EVT_slug'       => new EE_Slug_Field('post_name', esc_html__('Event Slug', 'event_espresso'), false,
113
+					''),
114
+				'EVT_created'    => new EE_Datetime_Field('post_date',
115
+					esc_html__('Date/Time Event Created', 'event_espresso'),
116
+					false, EE_Datetime_Field::now),
117
+				'EVT_short_desc' => new EE_Simple_HTML_Field('post_excerpt',
118
+					esc_html__('Event Short Description', 'event_espresso'), false, ''),
119
+				'EVT_modified'   => new EE_Datetime_Field('post_modified',
120
+					esc_html__('Date/Time Event Modified', 'event_espresso'), false, EE_Datetime_Field::now),
121
+				'EVT_wp_user'    => new EE_WP_User_Field('post_author',
122
+					esc_html__('Event Creator ID', 'event_espresso'),
123
+					false),
124
+				'parent'         => new EE_Integer_Field('post_parent', esc_html__('Event Parent ID', 'event_espresso'),
125
+					false,
126
+					0),
127
+				'EVT_order'      => new EE_Integer_Field('menu_order', esc_html__('Event Menu Order', 'event_espresso'),
128
+					false,
129
+					1),
130
+				'post_type'      => new EE_WP_Post_Type_Field('espresso_events'),
131
+				// EE_Plain_Text_Field( 'post_type', esc_html__( 'Event Post Type', 'event_espresso' ), FALSE, 'espresso_events' ),
132
+				'status'         => new EE_WP_Post_Status_Field('post_status',
133
+					esc_html__('Event Status', 'event_espresso'),
134
+					false, 'draft', $this->_custom_stati),
135
+			),
136
+			'Event_Meta' => array(
137
+				'EVTM_ID'                         => new EE_DB_Only_Float_Field('EVTM_ID',
138
+					esc_html__('Event Meta Row ID', 'event_espresso'), false),
139
+				'EVT_ID_fk'                       => new EE_DB_Only_Int_Field('EVT_ID',
140
+					esc_html__('Foreign key to Event ID from Event Meta table', 'event_espresso'), false),
141
+				'EVT_display_desc'                => new EE_Boolean_Field('EVT_display_desc',
142
+					esc_html__('Display Description Flag', 'event_espresso'), false, 1),
143
+				'EVT_display_ticket_selector'     => new EE_Boolean_Field('EVT_display_ticket_selector',
144
+					esc_html__('Display Ticket Selector Flag', 'event_espresso'), false, 1),
145
+				'EVT_visible_on'                  => new EE_Datetime_Field('EVT_visible_on',
146
+					esc_html__('Event Visible Date', 'event_espresso'), true, EE_Datetime_Field::now),
147
+				'EVT_additional_limit'            => new EE_Integer_Field(
148
+					'EVT_additional_limit',
149
+					esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
150
+					true,
151
+					self::$_default_additional_limit
152
+				),
153
+				'EVT_default_registration_status' => new EE_Enum_Text_Field(
154
+					'EVT_default_registration_status',
155
+					esc_html__('Default Registration Status on this Event', 'event_espresso'), false,
156
+					EEM_Event::$_default_reg_status, EEM_Registration::reg_status_array()
157
+				),
158
+				'EVT_member_only'                 => new EE_Boolean_Field('EVT_member_only',
159
+					esc_html__('Member-Only Event Flag', 'event_espresso'), false, false),
160
+				'EVT_phone'                       => new EE_Plain_Text_Field('EVT_phone',
161
+					esc_html__('Event Phone Number', 'event_espresso'), false),
162
+				'EVT_allow_overflow'              => new EE_Boolean_Field('EVT_allow_overflow',
163
+					esc_html__('Allow Overflow on Event', 'event_espresso'), false, false),
164
+				'EVT_timezone_string'             => new EE_Plain_Text_Field('EVT_timezone_string',
165
+					esc_html__('Timezone (name) for Event times', 'event_espresso'), false),
166
+				'EVT_external_URL'                => new EE_Plain_Text_Field('EVT_external_URL',
167
+					esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso'), true),
168
+				'EVT_donations'                   => new EE_Boolean_Field('EVT_donations',
169
+					esc_html__('Accept Donations?', 'event_espresso'), false, false),
170
+			),
171
+		);
172
+		$this->_model_relations = array(
173
+			'Registration'           => new EE_Has_Many_Relation(),
174
+			'Datetime'               => new EE_Has_Many_Relation(),
175
+			'Question_Group'         => new EE_HABTM_Relation('Event_Question_Group'),
176
+			'Venue'                  => new EE_HABTM_Relation('Event_Venue'),
177
+			'Term_Relationship'      => new EE_Has_Many_Relation(),
178
+			'Term_Taxonomy'          => new EE_HABTM_Relation('Term_Relationship'),
179
+			'Message_Template_Group' => new EE_HABTM_Relation('Event_Message_Template'),
180
+			'Attendee'               => new EE_HABTM_Relation('Registration'),
181
+			'WP_User'                => new EE_Belongs_To_Relation(),
182
+		);
183
+		//this model is generally available for reading
184
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
185
+		parent::__construct($timezone);
186
+	}
187
+
188
+
189
+
190
+	/**
191
+	 * @param string $default_reg_status
192
+	 */
193
+	public static function set_default_reg_status($default_reg_status)
194
+	{
195
+		self::$_default_reg_status = $default_reg_status;
196
+		// if EEM_Event has already been instantiated,
197
+		// then we need to reset the `EVT_default_reg_status` field to use the new default.
198
+		if (self::$_instance instanceof EEM_Event) {
199
+			$default_reg_status = new EE_Enum_Text_Field(
200
+				'EVT_default_registration_status',
201
+				esc_html__('Default Registration Status on this Event', 'event_espresso'),
202
+				false,
203
+				$default_reg_status,
204
+				EEM_Registration::reg_status_array()
205
+			);
206
+			$default_reg_status->_construct_finalize(
207
+				'Event_Meta',
208
+				'EVT_default_registration_status',
209
+				'EEM_Event'
210
+			);
211
+			self::$_instance->_fields['Event_Meta']['EVT_default_registration_status'] = $default_reg_status;
212
+		}
213
+	}
214
+
215
+
216
+	/**
217
+	 * Used to override the default for the additional limit field.
218
+	 * @param $additional_limit
219
+	 */
220
+	public static function set_default_additional_limit($additional_limit)
221
+	{
222
+		self::$_default_additional_limit = (int) $additional_limit;
223
+		if (self::$_instance instanceof EEM_Event) {
224
+			self::$_instance->_fields['Event_Meta']['EVT_additional_limit'] = new EE_Integer_Field(
225
+				'EVT_additional_limit',
226
+				__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
227
+				true,
228
+				self::$_default_additional_limit
229
+			);
230
+			self::$_instance->_fields['Event_Meta']['EVT_additional_limit']->_construct_finalize(
231
+				'Event_Meta',
232
+				'EVT_additional_limit',
233
+				'EEM_Event'
234
+			);
235
+		}
236
+	}
237
+
238
+
239
+	/**
240
+	 * Return what is currently set as the default additional limit for the event.
241
+	 * @return int
242
+	 */
243
+	public static function get_default_additional_limit()
244
+	{
245
+		return apply_filters('FHEE__EEM_Event__get_default_additional_limit', self::$_default_additional_limit);
246
+	}
247
+
248
+
249
+	/**
250
+	 * get_question_groups
251
+	 *
252
+	 * @return array
253
+	 * @throws \EE_Error
254
+	 */
255
+	public function get_all_question_groups()
256
+	{
257
+		return EE_Registry::instance()->load_model('Question_Group')->get_all(
258
+			array(
259
+				array('QSG_deleted' => false),
260
+				'order_by' => array('QSG_order' => 'ASC'),
261
+			)
262
+		);
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * get_question_groups
269
+	 *
270
+	 * @param int $EVT_ID
271
+	 * @return array|bool
272
+	 * @throws \EE_Error
273
+	 */
274
+	public function get_all_event_question_groups($EVT_ID = 0)
275
+	{
276
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
277
+			EE_Error::add_error(
278
+				esc_html__(
279
+					'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
280
+					'event_espresso'
281
+				),
282
+				__FILE__, __FUNCTION__, __LINE__
283
+			);
284
+			return false;
285
+		}
286
+		return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
287
+			array(
288
+				array('EVT_ID' => $EVT_ID),
289
+			)
290
+		);
291
+	}
292
+
293
+
294
+
295
+	/**
296
+	 * get_question_groups
297
+	 *
298
+	 * @param int     $EVT_ID
299
+	 * @param boolean $for_primary_attendee
300
+	 * @return array|bool
301
+	 * @throws \EE_Error
302
+	 */
303
+	public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
304
+	{
305
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
306
+			EE_Error::add_error(
307
+				esc_html__(
308
+					'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
309
+					'event_espresso'
310
+				),
311
+				__FILE__, __FUNCTION__, __LINE__
312
+			);
313
+			return false;
314
+		}
315
+		return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
316
+			array(
317
+				array(
318
+					'EVT_ID'      => $EVT_ID,
319
+					'EQG_primary' => $for_primary_attendee,
320
+				),
321
+			)
322
+		);
323
+	}
324
+
325
+
326
+
327
+	/**
328
+	 * get_question_groups
329
+	 *
330
+	 * @param int             $EVT_ID
331
+	 * @param EE_Registration $registration
332
+	 * @return array|bool
333
+	 * @throws \EE_Error
334
+	 */
335
+	public function get_question_groups_for_event($EVT_ID = 0, EE_Registration $registration)
336
+	{
337
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
338
+			EE_Error::add_error(
339
+				esc_html__(
340
+					'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
341
+					'event_espresso'
342
+				),
343
+				__FILE__, __FUNCTION__, __LINE__
344
+			);
345
+			return false;
346
+		}
347
+		$where_params = array(
348
+			'Event_Question_Group.EVT_ID'      => $EVT_ID,
349
+			'Event_Question_Group.EQG_primary' => $registration->count() === 1 ? true : false,
350
+			'QSG_deleted'                      => false,
351
+		);
352
+		return EE_Registry::instance()->load_model('Question_Group')->get_all(
353
+			array(
354
+				$where_params,
355
+				'order_by' => array('QSG_order' => 'ASC'),
356
+			)
357
+		);
358
+	}
359
+
360
+
361
+
362
+	/**
363
+	 * get_question_target_db_column
364
+	 *
365
+	 * @param string $QSG_IDs csv list of $QSG IDs
366
+	 * @return array|bool
367
+	 * @throws \EE_Error
368
+	 */
369
+	public function get_questions_in_groups($QSG_IDs = '')
370
+	{
371
+		if (empty($QSG_IDs)) {
372
+			EE_Error::add_error(
373
+				esc_html__('An error occurred. No Question Group IDs were received.', 'event_espresso'),
374
+				__FILE__, __FUNCTION__, __LINE__
375
+			);
376
+			return false;
377
+		}
378
+		return EE_Registry::instance()->load_model('Question')->get_all(
379
+			array(
380
+				array(
381
+					'Question_Group.QSG_ID' => array('IN', $QSG_IDs),
382
+					'QST_deleted'           => false,
383
+					'QST_admin_only'        => is_admin(),
384
+				),
385
+				'order_by' => 'QST_order',
386
+			)
387
+		);
388
+	}
389
+
390
+
391
+
392
+	/**
393
+	 * get_options_for_question
394
+	 *
395
+	 * @param string $QST_IDs csv list of $QST IDs
396
+	 * @return array|bool
397
+	 * @throws \EE_Error
398
+	 */
399
+	public function get_options_for_question($QST_IDs)
400
+	{
401
+		if (empty($QST_IDs)) {
402
+			EE_Error::add_error(
403
+				esc_html__('An error occurred. No Question IDs were received.', 'event_espresso'),
404
+				__FILE__, __FUNCTION__, __LINE__
405
+			);
406
+			return false;
407
+		}
408
+		return EE_Registry::instance()->load_model('Question_Option')->get_all(
409
+			array(
410
+				array(
411
+					'Question.QST_ID' => array('IN', $QST_IDs),
412
+					'QSO_deleted'     => false,
413
+				),
414
+				'order_by' => 'QSO_ID',
415
+			)
416
+		);
417
+	}
418
+
419
+
420
+
421
+
422
+
423
+
424
+
425
+	/**
426
+	 * Gets all events that are published
427
+	 * and have event start time earlier than now and an event end time later than now
428
+	 *
429
+	 * @param  array $query_params An array of query params to further filter on
430
+	 *                             (note that status and DTT_EVT_start and DTT_EVT_end will be overridden)
431
+	 * @param bool   $count        whether to return the count or not (default FALSE)
432
+	 * @return EE_Event[]|int
433
+	 * @throws \EE_Error
434
+	 */
435
+	public function get_active_events($query_params, $count = false)
436
+	{
437
+		if (array_key_exists(0, $query_params)) {
438
+			$where_params = $query_params[0];
439
+			unset($query_params[0]);
440
+		} else {
441
+			$where_params = array();
442
+		}
443
+		// if we have count make sure we don't include group by
444
+		if ($count && isset($query_params['group_by'])) {
445
+			unset($query_params['group_by']);
446
+		}
447
+		// let's add specific query_params for active_events
448
+		// keep in mind this will override any sent status in the query AND any date queries.
449
+		$where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
450
+		//if already have where params for DTT_EVT_start or DTT_EVT_end then append these conditions
451
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
452
+			$where_params['Datetime.DTT_EVT_start******'] = array(
453
+				'<',
454
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
455
+			);
456
+		} else {
457
+			$where_params['Datetime.DTT_EVT_start'] = array(
458
+				'<',
459
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
460
+			);
461
+		}
462
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
463
+			$where_params['Datetime.DTT_EVT_end*****'] = array(
464
+				'>',
465
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
466
+			);
467
+		} else {
468
+			$where_params['Datetime.DTT_EVT_end'] = array(
469
+				'>',
470
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
471
+			);
472
+		}
473
+		$query_params[0] = $where_params;
474
+		// don't use $query_params with count()
475
+		// because we don't want to include additional query clauses like "GROUP BY"
476
+		return $count
477
+			? $this->count(array($where_params), 'EVT_ID', true)
478
+			: $this->get_all($query_params);
479
+	}
480
+
481
+
482
+
483
+	/**
484
+	 * get all events that are published and have an event start time later than now
485
+	 *
486
+	 * @param  array $query_params An array of query params to further filter on
487
+	 *                             (Note that status and DTT_EVT_start will be overridden)
488
+	 * @param bool   $count        whether to return the count or not (default FALSE)
489
+	 * @return EE_Event[]|int
490
+	 * @throws \EE_Error
491
+	 */
492
+	public function get_upcoming_events($query_params, $count = false)
493
+	{
494
+		if (array_key_exists(0, $query_params)) {
495
+			$where_params = $query_params[0];
496
+			unset($query_params[0]);
497
+		} else {
498
+			$where_params = array();
499
+		}
500
+		// if we have count make sure we don't include group by
501
+		if ($count && isset($query_params['group_by'])) {
502
+			unset($query_params['group_by']);
503
+		}
504
+		// let's add specific query_params for active_events
505
+		// keep in mind this will override any sent status in the query AND any date queries.
506
+		$where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
507
+		// if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
508
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
509
+			$where_params['Datetime.DTT_EVT_start*****'] = array(
510
+				'>',
511
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
512
+			);
513
+		} else {
514
+			$where_params['Datetime.DTT_EVT_start'] = array(
515
+				'>',
516
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
517
+			);
518
+		}
519
+		$query_params[0] = $where_params;
520
+		// don't use $query_params with count()
521
+		// because we don't want to include additional query clauses like "GROUP BY"
522
+		return $count
523
+			? $this->count(array($where_params), 'EVT_ID', true)
524
+			: $this->get_all($query_params);
525
+	}
526
+
527
+
528
+
529
+	/**
530
+	 * Gets all events that are published
531
+	 * and have an event end time later than now
532
+	 *
533
+	 * @param  array $query_params An array of query params to further filter on
534
+	 *                             (note that status and DTT_EVT_end will be overridden)
535
+	 * @param bool   $count        whether to return the count or not (default FALSE)
536
+	 * @return EE_Event[]|int
537
+	 * @throws \EE_Error
538
+	 */
539
+	public function get_active_and_upcoming_events($query_params, $count = false)
540
+	{
541
+		if (array_key_exists(0, $query_params)) {
542
+			$where_params = $query_params[0];
543
+			unset($query_params[0]);
544
+		} else {
545
+			$where_params = array();
546
+		}
547
+		// if we have count make sure we don't include group by
548
+		if ($count && isset($query_params['group_by'])) {
549
+			unset($query_params['group_by']);
550
+		}
551
+		// let's add specific query_params for active_events
552
+		// keep in mind this will override any sent status in the query AND any date queries.
553
+		$where_params['status'] = array('IN', array('publish', EEM_Event::sold_out));
554
+		// add where params for DTT_EVT_end
555
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
556
+			$where_params['Datetime.DTT_EVT_end*****'] = array(
557
+				'>',
558
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
559
+			);
560
+		} else {
561
+			$where_params['Datetime.DTT_EVT_end'] = array(
562
+				'>',
563
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
564
+			);
565
+		}
566
+		$query_params[0] = $where_params;
567
+		// don't use $query_params with count()
568
+		// because we don't want to include additional query clauses like "GROUP BY"
569
+		return $count
570
+			? $this->count(array($where_params), 'EVT_ID', true)
571
+			: $this->get_all($query_params);
572
+	}
573
+
574
+
575
+
576
+	/**
577
+	 * This only returns events that are expired.
578
+	 * They may still be published but all their datetimes have expired.
579
+	 *
580
+	 * @param  array $query_params An array of query params to further filter on
581
+	 *                             (note that status and DTT_EVT_end will be overridden)
582
+	 * @param bool   $count        whether to return the count or not (default FALSE)
583
+	 * @return EE_Event[]|int
584
+	 * @throws \EE_Error
585
+	 */
586
+	public function get_expired_events($query_params, $count = false)
587
+	{
588
+		$where_params = isset($query_params[0]) ? $query_params[0] : array();
589
+		// if we have count make sure we don't include group by
590
+		if ($count && isset($query_params['group_by'])) {
591
+			unset($query_params['group_by']);
592
+		}
593
+		// let's add specific query_params for active_events
594
+		// keep in mind this will override any sent status in the query AND any date queries.
595
+		if (isset($where_params['status'])) {
596
+			unset($where_params['status']);
597
+		}
598
+		$exclude_query = $query_params;
599
+		if (isset($exclude_query[0])) {
600
+			unset($exclude_query[0]);
601
+		}
602
+		$exclude_query[0] = array(
603
+			'Datetime.DTT_EVT_end' => array(
604
+				'>',
605
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
606
+			),
607
+		);
608
+		// first get all events that have datetimes where its not expired.
609
+		$event_ids = $this->_get_all_wpdb_results($exclude_query, OBJECT_K, 'Event_CPT.ID');
610
+		$event_ids = array_keys($event_ids);
611
+		// if we have any additional query_params, let's add them to the 'AND' condition
612
+		$and_condition = array(
613
+			'Datetime.DTT_EVT_end' => array('<', EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end')),
614
+			'EVT_ID'               => array('NOT IN', $event_ids),
615
+		);
616
+		if (isset($where_params['OR'])) {
617
+			$and_condition['OR'] = $where_params['OR'];
618
+			unset($where_params['OR']);
619
+		}
620
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
621
+			$and_condition['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
622
+			unset($where_params['Datetime.DTT_EVT_end']);
623
+		}
624
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
625
+			$and_condition['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
626
+			unset($where_params['Datetime.DTT_EVT_start']);
627
+		}
628
+		// merge remaining $where params with the and conditions.
629
+		$where_params['AND'] = array_merge($and_condition, $where_params);
630
+		$query_params[0] = $where_params;
631
+		// don't use $query_params with count()
632
+		// because we don't want to include additional query clauses like "GROUP BY"
633
+		return $count
634
+			? $this->count(array($where_params), 'EVT_ID', true)
635
+			: $this->get_all($query_params);
636
+	}
637
+
638
+
639
+
640
+	/**
641
+	 * This basically just returns the events that do not have the publish status.
642
+	 *
643
+	 * @param  array   $query_params An array of query params to further filter on
644
+	 *                               (note that status will be overwritten)
645
+	 * @param  boolean $count        whether to return the count or not (default FALSE)
646
+	 * @return EE_Event[]|int
647
+	 * @throws \EE_Error
648
+	 */
649
+	public function get_inactive_events($query_params, $count = false)
650
+	{
651
+		$where_params = isset($query_params[0]) ? $query_params[0] : array();
652
+		// let's add in specific query_params for inactive events.
653
+		if (isset($where_params['status'])) {
654
+			unset($where_params['status']);
655
+		}
656
+		// if we have count make sure we don't include group by
657
+		if ($count && isset($query_params['group_by'])) {
658
+			unset($query_params['group_by']);
659
+		}
660
+		// if we have any additional query_params, let's add them to the 'AND' condition
661
+		$where_params['AND']['status'] = array('!=', 'publish');
662
+		if (isset($where_params['OR'])) {
663
+			$where_params['AND']['OR'] = $where_params['OR'];
664
+			unset($where_params['OR']);
665
+		}
666
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
667
+			$where_params['AND']['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
668
+			unset($where_params['Datetime.DTT_EVT_end']);
669
+		}
670
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
671
+			$where_params['AND']['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
672
+			unset($where_params['Datetime.DTT_EVT_start']);
673
+		}
674
+		$query_params[0] = $where_params;
675
+		// don't use $query_params with count()
676
+		// because we don't want to include additional query clauses like "GROUP BY"
677
+		return $count
678
+			? $this->count(array($where_params), 'EVT_ID', true)
679
+			: $this->get_all($query_params);
680
+	}
681
+
682
+
683
+
684
+	/**
685
+	 * This is just injecting into the parent add_relationship_to so we do special handling on price relationships
686
+	 * because we don't want to override any existing global default prices but instead insert NEW prices that get
687
+	 * attached to the event. See parent for param descriptions
688
+	 *
689
+	 * @param        $id_or_obj
690
+	 * @param        $other_model_id_or_obj
691
+	 * @param string $relationName
692
+	 * @param array  $where_query
693
+	 * @return EE_Base_Class
694
+	 * @throws EE_Error
695
+	 */
696
+	public function add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
697
+	{
698
+		if ($relationName === 'Price') {
699
+			//let's get the PRC object for the given ID to make sure that we aren't dealing with a default
700
+			$prc_chk = $this->get_related_model_obj($relationName)->ensure_is_obj($other_model_id_or_obj);
701
+			//if EVT_ID = 0, then this is a default
702
+			if ((int) $prc_chk->get('EVT_ID') === 0) {
703
+				//let's set the prc_id as 0 so we force an insert on the add_relation_to carried out by relation
704
+				$prc_chk->set('PRC_ID', 0);
705
+			}
706
+			//run parent
707
+			return parent::add_relationship_to($id_or_obj, $prc_chk, $relationName, $where_query);
708
+		}
709
+		//otherwise carry on as normal
710
+		return parent::add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query);
711
+	}
712
+
713
+
714
+
715
+	/******************** DEPRECATED METHODS ********************/
716
+
717
+
718
+
719
+	/**
720
+	 * _get_question_target_db_column
721
+	 *
722
+	 * @deprecated as of 4.8.32.rc.001. Instead consider using
723
+	 *             EE_Registration_Custom_Questions_Form located in
724
+	 *             admin_pages/registrations/form_sections/EE_Registration_Custom_Questions_Form.form.php
725
+	 * @access     public
726
+	 * @param    EE_Registration $registration (so existing answers for registration are included)
727
+	 * @param    int             $EVT_ID       so all question groups are included for event (not just answers from
728
+	 *                                         registration).
729
+	 * @throws EE_Error
730
+	 * @return    array
731
+	 */
732
+	public function assemble_array_of_groups_questions_and_options(EE_Registration $registration, $EVT_ID = 0)
733
+	{
734
+		if (empty($EVT_ID)) {
735
+			throw new EE_Error(__('An error occurred. No EVT_ID is included.  Needed to know which question groups to retrieve.',
736
+				'event_espresso'));
737
+		}
738
+		$questions = array();
739
+		// get all question groups for event
740
+		$qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
741
+		if (! empty($qgs)) {
742
+			foreach ($qgs as $qg) {
743
+				$qsts = $qg->questions();
744
+				$questions[$qg->ID()] = $qg->model_field_array();
745
+				$questions[$qg->ID()]['QSG_questions'] = array();
746
+				foreach ($qsts as $qst) {
747
+					if ($qst->is_system_question()) {
748
+						continue;
749
+					}
750
+					$answer = EEM_Answer::instance()->get_one(array(
751
+						array(
752
+							'QST_ID' => $qst->ID(),
753
+							'REG_ID' => $registration->ID(),
754
+						),
755
+					));
756
+					$answer = $answer instanceof EE_Answer ? $answer : EEM_Answer::instance()->create_default_object();
757
+					$qst_name = $qstn_id = $qst->ID();
758
+					$ans_id = $answer->ID();
759
+					$qst_name = ! empty($ans_id) ? '[' . $qst_name . '][' . $ans_id . ']' : '[' . $qst_name . ']';
760
+					$input_name = '';
761
+					$input_id = sanitize_key($qst->display_text());
762
+					$input_class = '';
763
+					$questions[$qg->ID()]['QSG_questions'][$qst->ID()] = $qst->model_field_array();
764
+					$questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_name'] = 'qstn'
765
+																						   . $input_name
766
+																						   . $qst_name;
767
+					$questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_id'] = $input_id . '-' . $qstn_id;
768
+					$questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_class'] = $input_class;
769
+					$questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_options'] = array();
770
+					$questions[$qg->ID()]['QSG_questions'][$qst->ID()]['qst_obj'] = $qst;
771
+					$questions[$qg->ID()]['QSG_questions'][$qst->ID()]['ans_obj'] = $answer;
772
+					//leave responses as-is, don't convert stuff into html entities please!
773
+					$questions[$qg->ID()]['QSG_questions'][$qst->ID()]['htmlentities'] = false;
774
+					if ($qst->type() == 'RADIO_BTN' || $qst->type() == 'CHECKBOX' || $qst->type() == 'DROPDOWN') {
775
+						$QSOs = $qst->options(true, $answer->value());
776
+						if (is_array($QSOs)) {
777
+							foreach ($QSOs as $QSO_ID => $QSO) {
778
+								$questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_options'][$QSO_ID] = $QSO->model_field_array();
779
+							}
780
+						}
781
+					}
782
+				}
783
+			}
784
+		}
785
+		return $questions;
786
+	}
787 787
 
788 788
 
789 789
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -1,9 +1,9 @@  discard block
 block discarded – undo
1 1
 <?php use EventEspresso\core\services\orm\ModelFieldFactory;
2 2
 
3
-if (! defined('EVENT_ESPRESSO_VERSION')) {
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4 4
     exit('No direct script access allowed');
5 5
 }
6
-require_once(EE_MODELS . 'EEM_CPT_Base.model.php');
6
+require_once(EE_MODELS.'EEM_CPT_Base.model.php');
7 7
 
8 8
 
9 9
 
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
      */
274 274
     public function get_all_event_question_groups($EVT_ID = 0)
275 275
     {
276
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
276
+        if ( ! isset($EVT_ID) || ! absint($EVT_ID)) {
277 277
             EE_Error::add_error(
278 278
                 esc_html__(
279 279
                     'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
      */
303 303
     public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
304 304
     {
305
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
305
+        if ( ! isset($EVT_ID) || ! absint($EVT_ID)) {
306 306
             EE_Error::add_error(
307 307
                 esc_html__(
308 308
                     'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
      */
335 335
     public function get_question_groups_for_event($EVT_ID = 0, EE_Registration $registration)
336 336
     {
337
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
337
+        if ( ! isset($EVT_ID) || ! absint($EVT_ID)) {
338 338
             EE_Error::add_error(
339 339
                 esc_html__(
340 340
                     'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
         $questions = array();
739 739
         // get all question groups for event
740 740
         $qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
741
-        if (! empty($qgs)) {
741
+        if ( ! empty($qgs)) {
742 742
             foreach ($qgs as $qg) {
743 743
                 $qsts = $qg->questions();
744 744
                 $questions[$qg->ID()] = $qg->model_field_array();
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
                     $answer = $answer instanceof EE_Answer ? $answer : EEM_Answer::instance()->create_default_object();
757 757
                     $qst_name = $qstn_id = $qst->ID();
758 758
                     $ans_id = $answer->ID();
759
-                    $qst_name = ! empty($ans_id) ? '[' . $qst_name . '][' . $ans_id . ']' : '[' . $qst_name . ']';
759
+                    $qst_name = ! empty($ans_id) ? '['.$qst_name.']['.$ans_id.']' : '['.$qst_name.']';
760 760
                     $input_name = '';
761 761
                     $input_id = sanitize_key($qst->display_text());
762 762
                     $input_class = '';
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
                     $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_name'] = 'qstn'
765 765
                                                                                            . $input_name
766 766
                                                                                            . $qst_name;
767
-                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_id'] = $input_id . '-' . $qstn_id;
767
+                    $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_id'] = $input_id.'-'.$qstn_id;
768 768
                     $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_input_class'] = $input_class;
769 769
                     $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['QST_options'] = array();
770 770
                     $questions[$qg->ID()]['QSG_questions'][$qst->ID()]['qst_obj'] = $qst;
Please login to merge, or discard this patch.
core/services/orm/ModelFieldFactory.php 3 patches
Doc Comments   +4 added lines, -5 removed lines patch added patch discarded remove patch
@@ -132,7 +132,6 @@  discard block
 block discarded – undo
132 132
     /**
133 133
      * @param string $table_column
134 134
      * @param string $nice_name
135
-     * @param string $timezone_string
136 135
      * @param bool   $nullable
137 136
      * @param string $default_value
138 137
      * @throws EE_Error
@@ -179,7 +178,7 @@  discard block
 block discarded – undo
179 178
      * @param string $table_column
180 179
      * @param string $nice_name
181 180
      * @param bool   $nullable
182
-     * @param null   $default_value
181
+     * @param integer   $default_value
183 182
      * @return EE_DB_Only_Int_Field
184 183
      */
185 184
     public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
@@ -295,7 +294,7 @@  discard block
 block discarded – undo
295 294
      * @param string $table_column
296 295
      * @param string $nice_name
297 296
      * @param bool   $nullable
298
-     * @param null   $default_value
297
+     * @param integer   $default_value
299 298
      * @param string $model_name
300 299
      * @return EE_Foreign_Key_Int_Field
301 300
      */
@@ -313,7 +312,7 @@  discard block
 block discarded – undo
313 312
      * @param string $table_column
314 313
      * @param string $nice_name
315 314
      * @param bool   $nullable
316
-     * @param null   $default_value
315
+     * @param string   $default_value
317 316
      * @param string $model_name
318 317
      * @return EE_Foreign_Key_String_Field
319 318
      */
@@ -564,7 +563,7 @@  discard block
 block discarded – undo
564 563
      * @param string $table_column
565 564
      * @param string $nice_name
566 565
      * @param bool   $nullable
567
-     * @param mixed  $default_value
566
+     * @param string  $default_value
568 567
      * @param array  $values        If additional stati are to be used other than the default WP statuses,
569 568
      *                              then they can be registered via this property.
570 569
      *                              The format of the array should be as follows:
Please login to merge, or discard this patch.
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -33,9 +33,6 @@
 block discarded – undo
33 33
 use EE_WP_Post_Status_Field;
34 34
 use EE_WP_Post_Type_Field;
35 35
 use EE_WP_User_Field;
36
-use EventEspresso\core\exceptions\InvalidDataTypeException;
37
-use EventEspresso\core\exceptions\InvalidInterfaceException;
38
-use EventEspresso\core\services\loaders\LoaderFactory;
39 36
 use EventEspresso\core\services\loaders\LoaderInterface;
40 37
 use InvalidArgumentException;
41 38
 
Please login to merge, or discard this patch.
Indentation   +570 added lines, -570 removed lines patch added patch discarded remove patch
@@ -53,576 +53,576 @@
 block discarded – undo
53 53
 class ModelFieldFactory
54 54
 {
55 55
 
56
-    /**
57
-     * @var LoaderInterface $loader
58
-     */
59
-    private $loader;
60
-
61
-
62
-
63
-    /**
64
-     * ModelFieldFactory constructor.
65
-     *
66
-     * @param LoaderInterface $loader
67
-     */
68
-    public function __construct(LoaderInterface $loader)
69
-    {
70
-        $this->loader = $loader;
71
-    }
72
-
73
-
74
-
75
-    /**
76
-     * @param string $table_column
77
-     * @param string $nice_name
78
-     * @param bool   $nullable
79
-     * @param null   $default_value
80
-     * @return EE_All_Caps_Text_Field
81
-     */
82
-    public function createAllCapsTextField($table_column, $nice_name, $nullable, $default_value = null)
83
-    {
84
-        return $this->loader->getNew(
85
-            'EE_All_Caps_Text_Field',
86
-            array($table_column, $nice_name, $nullable, $default_value)
87
-        );
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     * @param string $table_column
94
-     * @param string $nice_name
95
-     * @param bool   $nullable
96
-     * @param null   $default_value
97
-     * @param string $model_name
98
-     * @return EE_Any_Foreign_Model_Name_Field
99
-     */
100
-    public function createAnyForeignModelNameField(
101
-        $table_column,
102
-        $nice_name,
103
-        $nullable,
104
-        $default_value = null,
105
-        $model_name
106
-    ) {
107
-        return $this->loader->getNew(
108
-            'EE_Any_Foreign_Model_Name_Field',
109
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
110
-        );
111
-    }
112
-
113
-
114
-
115
-    /**
116
-     * @param string $table_column
117
-     * @param string $nice_name
118
-     * @param bool   $nullable
119
-     * @param null   $default_value
120
-     * @return EE_Boolean_Field
121
-     */
122
-    public function createBooleanField($table_column, $nice_name, $nullable, $default_value = null)
123
-    {
124
-        return $this->loader->getNew(
125
-            'EE_Boolean_Field',
126
-            array($table_column, $nice_name, $nullable, $default_value)
127
-        );
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * @param string $table_column
134
-     * @param string $nice_name
135
-     * @param string $timezone_string
136
-     * @param bool   $nullable
137
-     * @param string $default_value
138
-     * @throws EE_Error
139
-     * @throws InvalidArgumentException
140
-     * @return EE_Datetime_Field
141
-     */
142
-    public function createDatetimeField(
143
-        $table_column,
144
-        $nice_name,
145
-        $nullable = false,
146
-        $default_value = EE_Datetime_Field::now
147
-    ) {
148
-        return $this->loader->getNew(
149
-            'EE_Datetime_Field',
150
-            array(
151
-                $table_column,
152
-                $nice_name,
153
-                $nullable,
154
-                $default_value
155
-            )
156
-        );
157
-    }
158
-
159
-
160
-
161
-    /**
162
-     * @param string $table_column
163
-     * @param string $nice_name
164
-     * @param bool   $nullable
165
-     * @param null   $default_value
166
-     * @return EE_DB_Only_Float_Field
167
-     */
168
-    public function createDbOnlyFloatField($table_column, $nice_name, $nullable, $default_value = null)
169
-    {
170
-        return $this->loader->getNew(
171
-            'EE_DB_Only_Float_Field',
172
-            array($table_column, $nice_name, $nullable, $default_value)
173
-        );
174
-    }
175
-
176
-
177
-
178
-    /**
179
-     * @param string $table_column
180
-     * @param string $nice_name
181
-     * @param bool   $nullable
182
-     * @param null   $default_value
183
-     * @return EE_DB_Only_Int_Field
184
-     */
185
-    public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
186
-    {
187
-        return $this->loader->getNew(
188
-            'EE_DB_Only_Int_Field',
189
-            array($table_column, $nice_name, $nullable, $default_value)
190
-        );
191
-    }
192
-
193
-
194
-
195
-    /**
196
-     * @param string $table_column
197
-     * @param string $nice_name
198
-     * @param bool   $nullable
199
-     * @param null   $default_value
200
-     * @return EE_DB_Only_Text_Field
201
-     */
202
-    public function createDbOnlyTextField($table_column, $nice_name, $nullable, $default_value = null)
203
-    {
204
-        return $this->loader->getNew(
205
-            'EE_DB_Only_Text_Field',
206
-            array($table_column, $nice_name, $nullable, $default_value)
207
-        );
208
-    }
209
-
210
-
211
-
212
-    /**
213
-     * @param string $table_column
214
-     * @param string $nice_name
215
-     * @param bool   $nullable
216
-     * @param string $default_value
217
-     * @return EE_Email_Field
218
-     */
219
-    public function createEmailField($table_column, $nice_name, $nullable = true, $default_value = '')
220
-    {
221
-        return $this->loader->getNew(
222
-            'EE_Email_Field',
223
-            array($table_column, $nice_name, $nullable, $default_value)
224
-        );
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * @param string $table_column
231
-     * @param string $nice_name
232
-     * @param bool   $nullable
233
-     * @param null   $default_value
234
-     * @param array  $allowed_enum_values keys are values to be used in the DB,
235
-     *                                    values are how they should be displayed
236
-     * @return EE_Enum_Integer_Field
237
-     */
238
-    public function createEnumIntegerField(
239
-        $table_column,
240
-        $nice_name,
241
-        $nullable,
242
-        $default_value = null,
243
-        array $allowed_enum_values
244
-    ) {
245
-        return $this->loader->getNew(
246
-            'EE_Enum_Integer_Field',
247
-            array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
248
-        );
249
-    }
250
-
251
-
252
-
253
-    /**
254
-     * @param string $table_column
255
-     * @param string $nice_name
256
-     * @param bool   $nullable
257
-     * @param null   $default_value
258
-     * @param array  $allowed_enum_values keys are values to be used in the DB,
259
-     *                                    values are how they should be displayed
260
-     * @return EE_Enum_Text_Field
261
-     */
262
-    public function createEnumTextField(
263
-        $table_column,
264
-        $nice_name,
265
-        $nullable,
266
-        $default_value,
267
-        array $allowed_enum_values
268
-    ) {
269
-        return $this->loader->getNew(
270
-            'EE_Enum_Text_Field',
271
-            array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
272
-        );
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     * @param string $table_column
279
-     * @param string $nice_name
280
-     * @param bool   $nullable
281
-     * @param null   $default_value
282
-     * @return EE_Float_Field
283
-     */
284
-    public function createFloatField($table_column, $nice_name, $nullable, $default_value = null)
285
-    {
286
-        return $this->loader->getNew(
287
-            'EE_Float_Field',
288
-            array($table_column, $nice_name, $nullable, $default_value)
289
-        );
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * @param string $table_column
296
-     * @param string $nice_name
297
-     * @param bool   $nullable
298
-     * @param null   $default_value
299
-     * @param string $model_name
300
-     * @return EE_Foreign_Key_Int_Field
301
-     */
302
-    public function createForeignKeyIntField($table_column, $nice_name, $nullable, $default_value, $model_name)
303
-    {
304
-        return $this->loader->getNew(
305
-            'EE_Foreign_Key_Int_Field',
306
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
307
-        );
308
-    }
309
-
310
-
311
-
312
-    /**
313
-     * @param string $table_column
314
-     * @param string $nice_name
315
-     * @param bool   $nullable
316
-     * @param null   $default_value
317
-     * @param string $model_name
318
-     * @return EE_Foreign_Key_String_Field
319
-     */
320
-    public function createForeignKeyStringField(
321
-        $table_column,
322
-        $nice_name,
323
-        $nullable,
324
-        $default_value,
325
-        $model_name
326
-    ) {
327
-        return $this->loader->getNew(
328
-            'EE_Foreign_Key_String_Field',
329
-            array($table_column, $nice_name, $nullable, $default_value, $model_name)
330
-        );
331
-    }
332
-
333
-
334
-
335
-    /**
336
-     * @param string $table_column
337
-     * @param string $nice_name
338
-     * @param bool   $nullable
339
-     * @param null   $default_value
340
-     * @return EE_Full_HTML_Field
341
-     */
342
-    public function createFullHtmlField($table_column, $nice_name, $nullable, $default_value = null)
343
-    {
344
-        return $this->loader->getNew(
345
-            'EE_Full_HTML_Field',
346
-            array($table_column, $nice_name, $nullable, $default_value)
347
-        );
348
-    }
349
-
350
-
351
-
352
-    /**
353
-     * @param string $table_column
354
-     * @param string $nice_name
355
-     * @param bool   $nullable
356
-     * @param null   $default_value
357
-     * @return EE_Infinite_Integer_Field
358
-     */
359
-    public function createInfiniteIntegerField($table_column, $nice_name, $nullable, $default_value = null)
360
-    {
361
-        return $this->loader->getNew(
362
-            'EE_Infinite_Integer_Field',
363
-            array($table_column, $nice_name, $nullable, $default_value)
364
-        );
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * @param string $table_column
371
-     * @param string $nice_name
372
-     * @param bool   $nullable
373
-     * @param null   $default_value
374
-     * @return EE_Integer_Field
375
-     */
376
-    public function createIntegerField($table_column, $nice_name, $nullable, $default_value = null)
377
-    {
378
-        return $this->loader->getNew(
379
-            'EE_Integer_Field',
380
-            array($table_column, $nice_name, $nullable, $default_value)
381
-        );
382
-    }
383
-
384
-
385
-
386
-    /**
387
-     * @param string $table_column
388
-     * @param string $nice_name
389
-     * @param bool   $nullable
390
-     * @param null   $default_value
391
-     * @return EE_Maybe_Serialized_Simple_HTML_Field
392
-     */
393
-    public function createMaybeSerializedSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
394
-    {
395
-        return $this->loader->getNew(
396
-            'EE_Maybe_Serialized_Simple_HTML_Field',
397
-            array($table_column, $nice_name, $nullable, $default_value)
398
-        );
399
-    }
400
-
401
-
402
-
403
-    /**
404
-     * @param string $table_column
405
-     * @param string $nice_name
406
-     * @param bool   $nullable
407
-     * @param null   $default_value
408
-     * @return EE_Maybe_Serialized_Text_Field
409
-     */
410
-    public function createMaybeSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
411
-    {
412
-        return $this->loader->getNew(
413
-            'EE_Maybe_Serialized_Text_Field',
414
-            array($table_column, $nice_name, $nullable, $default_value)
415
-        );
416
-    }
417
-
418
-
419
-
420
-    /**
421
-     * @param string $table_column
422
-     * @param string $nice_name
423
-     * @param bool   $nullable
424
-     * @param null   $default_value
425
-     * @return EE_Money_Field
426
-     */
427
-    public function createMoneyField($table_column, $nice_name, $nullable, $default_value = null)
428
-    {
429
-        return $this->loader->getNew(
430
-            'EE_Money_Field',
431
-            array($table_column, $nice_name, $nullable, $default_value)
432
-        );
433
-    }
434
-
435
-
436
-
437
-    /**
438
-     * @param string $table_column
439
-     * @param string $nice_name
440
-     * @param bool   $nullable
441
-     * @param string $default_value
442
-     * @return EE_Plain_Text_Field
443
-     */
444
-    public function createPlainTextField($table_column, $nice_name, $nullable = true, $default_value = '')
445
-    {
446
-        return $this->loader->getNew(
447
-            'EE_Plain_Text_Field',
448
-            array($table_column, $nice_name, $nullable, $default_value)
449
-        );
450
-    }
451
-
452
-
453
-
454
-    /**
455
-     * @param string $table_column
456
-     * @param string $nice_name
457
-     * @param bool   $nullable
458
-     * @param null   $default_value
459
-     * @return EE_Post_Content_Field
460
-     */
461
-    public function createPostContentField($table_column, $nice_name, $nullable, $default_value = null)
462
-    {
463
-        return $this->loader->getNew(
464
-            'EE_Post_Content_Field',
465
-            array($table_column, $nice_name, $nullable, $default_value)
466
-        );
467
-    }
468
-
469
-
470
-
471
-    /**
472
-     * @param string $table_column
473
-     * @param string $nice_name
474
-     * @return EE_Primary_Key_Int_Field
475
-     */
476
-    public function createPrimaryKeyIntField($table_column, $nice_name)
477
-    {
478
-        return $this->loader->getNew('EE_Primary_Key_Int_Field', array($table_column, $nice_name));
479
-    }
480
-
481
-
482
-
483
-    /**
484
-     * @param string $table_column
485
-     * @param string $nice_name
486
-     * @return EE_Primary_Key_String_Field
487
-     */
488
-    public function createPrimaryKeyStringField($table_column, $nice_name)
489
-    {
490
-        return $this->loader->getNew('EE_Primary_Key_String_Field', array($table_column, $nice_name));
491
-    }
492
-
493
-
494
-
495
-    /**
496
-     * @param string $table_column
497
-     * @param string $nice_name
498
-     * @param bool   $nullable
499
-     * @param null   $default_value
500
-     * @return EE_Serialized_Text_Field
501
-     */
502
-    public function createSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
503
-    {
504
-        return $this->loader->getNew(
505
-            'EE_Serialized_Text_Field',
506
-            array($table_column, $nice_name, $nullable, $default_value)
507
-        );
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * @param string $table_column
514
-     * @param string $nice_name
515
-     * @param bool   $nullable
516
-     * @param null   $default_value
517
-     * @return EE_Simple_HTML_Field
518
-     */
519
-    public function createSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
520
-    {
521
-        return $this->loader->getNew(
522
-            'EE_Simple_HTML_Field',
523
-            array($table_column, $nice_name, $nullable, $default_value)
524
-        );
525
-    }
526
-
527
-
528
-
529
-    /**
530
-     * @param string $table_column
531
-     * @param string $nice_name
532
-     * @param bool   $nullable
533
-     * @param null   $default_value
534
-     * @return EE_Slug_Field
535
-     */
536
-    public function createSlugField($table_column, $nice_name, $nullable = false, $default_value = null)
537
-    {
538
-        return $this->loader->getNew(
539
-            'EE_Slug_Field',
540
-            array($table_column, $nice_name, $nullable, $default_value)
541
-        );
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * @param string $table_column
548
-     * @param string $nice_name
549
-     * @param bool   $nullable
550
-     * @param null   $default_value
551
-     * @return EE_Trashed_Flag_Field
552
-     */
553
-    public function createTrashedFlagField($table_column, $nice_name, $nullable, $default_value = null)
554
-    {
555
-        return $this->loader->getNew(
556
-            'EE_Trashed_Flag_Field',
557
-            array($table_column, $nice_name, $nullable, $default_value)
558
-        );
559
-    }
560
-
561
-
562
-
563
-    /**
564
-     * @param string $table_column
565
-     * @param string $nice_name
566
-     * @param bool   $nullable
567
-     * @param mixed  $default_value
568
-     * @param array  $values        If additional stati are to be used other than the default WP statuses,
569
-     *                              then they can be registered via this property.
570
-     *                              The format of the array should be as follows:
571
-     *  array(
572
-     *      'status_reference' => array(
573
-     *          'label' => __('Status Reference Label', 'event_espresso'),
574
-     *          'public' => true,                 // whether this status should be shown on the frontend of the site
575
-     *          'exclude_from_search' => false,   // whether this status should be excluded from wp searches
576
-     *          'show_in_admin_all_list' => true, // whether this status is included in queries
577
-     *                                               for the admin "all" view in list table views.
578
-     *          'show_in_admin_status_list' => true, // show in the list of statuses with post counts at the top
579
-     *                                                  of the admin list tables (i.e. Status Reference(2) )
580
-     *          'label_count' => _n_noop(
581
-     *              'Status Reference <span class="count">(%s)</span>',
582
-     *              'Status References <span class="count">(%s)</span>'
583
-     *          ),                                   // the text to display on the admin screen
584
-     *                                                  ( or you won't see your status count ).
585
-     *      )
586
-     *  )
587
-     * @link http://codex.wordpress.org/Function_Reference/register_post_status for more info
588
-     * @return EE_WP_Post_Status_Field
589
-     */
590
-    public function createWpPostStatusField(
591
-        $table_column,
592
-        $nice_name,
593
-        $nullable,
594
-        $default_value = null,
595
-        array $values = array()
596
-    ) {
597
-        return $this->loader->getNew(
598
-            'EE_WP_Post_Status_Field',
599
-            array($table_column, $nice_name, $nullable, $default_value, $values)
600
-        );
601
-    }
602
-
603
-
604
-
605
-    /**
606
-     * @param string $post_type
607
-     * @return EE_WP_Post_Type_Field
608
-     */
609
-    public function createWpPostTypeField($post_type)
610
-    {
611
-        return $this->loader->getNew('EE_WP_Post_Type_Field', array($post_type));
612
-    }
613
-
614
-
615
-
616
-    /**
617
-     * @param string $table_column
618
-     * @param string $nice_name
619
-     * @param bool   $nullable
620
-     * @return EE_WP_User_Field
621
-     */
622
-    public function createWpUserField($table_column, $nice_name, $nullable)
623
-    {
624
-        return $this->loader->getNew('EE_WP_User_Field', array($table_column, $nice_name, $nullable));
625
-    }
56
+	/**
57
+	 * @var LoaderInterface $loader
58
+	 */
59
+	private $loader;
60
+
61
+
62
+
63
+	/**
64
+	 * ModelFieldFactory constructor.
65
+	 *
66
+	 * @param LoaderInterface $loader
67
+	 */
68
+	public function __construct(LoaderInterface $loader)
69
+	{
70
+		$this->loader = $loader;
71
+	}
72
+
73
+
74
+
75
+	/**
76
+	 * @param string $table_column
77
+	 * @param string $nice_name
78
+	 * @param bool   $nullable
79
+	 * @param null   $default_value
80
+	 * @return EE_All_Caps_Text_Field
81
+	 */
82
+	public function createAllCapsTextField($table_column, $nice_name, $nullable, $default_value = null)
83
+	{
84
+		return $this->loader->getNew(
85
+			'EE_All_Caps_Text_Field',
86
+			array($table_column, $nice_name, $nullable, $default_value)
87
+		);
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 * @param string $table_column
94
+	 * @param string $nice_name
95
+	 * @param bool   $nullable
96
+	 * @param null   $default_value
97
+	 * @param string $model_name
98
+	 * @return EE_Any_Foreign_Model_Name_Field
99
+	 */
100
+	public function createAnyForeignModelNameField(
101
+		$table_column,
102
+		$nice_name,
103
+		$nullable,
104
+		$default_value = null,
105
+		$model_name
106
+	) {
107
+		return $this->loader->getNew(
108
+			'EE_Any_Foreign_Model_Name_Field',
109
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
110
+		);
111
+	}
112
+
113
+
114
+
115
+	/**
116
+	 * @param string $table_column
117
+	 * @param string $nice_name
118
+	 * @param bool   $nullable
119
+	 * @param null   $default_value
120
+	 * @return EE_Boolean_Field
121
+	 */
122
+	public function createBooleanField($table_column, $nice_name, $nullable, $default_value = null)
123
+	{
124
+		return $this->loader->getNew(
125
+			'EE_Boolean_Field',
126
+			array($table_column, $nice_name, $nullable, $default_value)
127
+		);
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * @param string $table_column
134
+	 * @param string $nice_name
135
+	 * @param string $timezone_string
136
+	 * @param bool   $nullable
137
+	 * @param string $default_value
138
+	 * @throws EE_Error
139
+	 * @throws InvalidArgumentException
140
+	 * @return EE_Datetime_Field
141
+	 */
142
+	public function createDatetimeField(
143
+		$table_column,
144
+		$nice_name,
145
+		$nullable = false,
146
+		$default_value = EE_Datetime_Field::now
147
+	) {
148
+		return $this->loader->getNew(
149
+			'EE_Datetime_Field',
150
+			array(
151
+				$table_column,
152
+				$nice_name,
153
+				$nullable,
154
+				$default_value
155
+			)
156
+		);
157
+	}
158
+
159
+
160
+
161
+	/**
162
+	 * @param string $table_column
163
+	 * @param string $nice_name
164
+	 * @param bool   $nullable
165
+	 * @param null   $default_value
166
+	 * @return EE_DB_Only_Float_Field
167
+	 */
168
+	public function createDbOnlyFloatField($table_column, $nice_name, $nullable, $default_value = null)
169
+	{
170
+		return $this->loader->getNew(
171
+			'EE_DB_Only_Float_Field',
172
+			array($table_column, $nice_name, $nullable, $default_value)
173
+		);
174
+	}
175
+
176
+
177
+
178
+	/**
179
+	 * @param string $table_column
180
+	 * @param string $nice_name
181
+	 * @param bool   $nullable
182
+	 * @param null   $default_value
183
+	 * @return EE_DB_Only_Int_Field
184
+	 */
185
+	public function createDbOnlyIntField($table_column, $nice_name, $nullable, $default_value = null)
186
+	{
187
+		return $this->loader->getNew(
188
+			'EE_DB_Only_Int_Field',
189
+			array($table_column, $nice_name, $nullable, $default_value)
190
+		);
191
+	}
192
+
193
+
194
+
195
+	/**
196
+	 * @param string $table_column
197
+	 * @param string $nice_name
198
+	 * @param bool   $nullable
199
+	 * @param null   $default_value
200
+	 * @return EE_DB_Only_Text_Field
201
+	 */
202
+	public function createDbOnlyTextField($table_column, $nice_name, $nullable, $default_value = null)
203
+	{
204
+		return $this->loader->getNew(
205
+			'EE_DB_Only_Text_Field',
206
+			array($table_column, $nice_name, $nullable, $default_value)
207
+		);
208
+	}
209
+
210
+
211
+
212
+	/**
213
+	 * @param string $table_column
214
+	 * @param string $nice_name
215
+	 * @param bool   $nullable
216
+	 * @param string $default_value
217
+	 * @return EE_Email_Field
218
+	 */
219
+	public function createEmailField($table_column, $nice_name, $nullable = true, $default_value = '')
220
+	{
221
+		return $this->loader->getNew(
222
+			'EE_Email_Field',
223
+			array($table_column, $nice_name, $nullable, $default_value)
224
+		);
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * @param string $table_column
231
+	 * @param string $nice_name
232
+	 * @param bool   $nullable
233
+	 * @param null   $default_value
234
+	 * @param array  $allowed_enum_values keys are values to be used in the DB,
235
+	 *                                    values are how they should be displayed
236
+	 * @return EE_Enum_Integer_Field
237
+	 */
238
+	public function createEnumIntegerField(
239
+		$table_column,
240
+		$nice_name,
241
+		$nullable,
242
+		$default_value = null,
243
+		array $allowed_enum_values
244
+	) {
245
+		return $this->loader->getNew(
246
+			'EE_Enum_Integer_Field',
247
+			array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
248
+		);
249
+	}
250
+
251
+
252
+
253
+	/**
254
+	 * @param string $table_column
255
+	 * @param string $nice_name
256
+	 * @param bool   $nullable
257
+	 * @param null   $default_value
258
+	 * @param array  $allowed_enum_values keys are values to be used in the DB,
259
+	 *                                    values are how they should be displayed
260
+	 * @return EE_Enum_Text_Field
261
+	 */
262
+	public function createEnumTextField(
263
+		$table_column,
264
+		$nice_name,
265
+		$nullable,
266
+		$default_value,
267
+		array $allowed_enum_values
268
+	) {
269
+		return $this->loader->getNew(
270
+			'EE_Enum_Text_Field',
271
+			array($table_column, $nice_name, $nullable, $default_value, $allowed_enum_values)
272
+		);
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 * @param string $table_column
279
+	 * @param string $nice_name
280
+	 * @param bool   $nullable
281
+	 * @param null   $default_value
282
+	 * @return EE_Float_Field
283
+	 */
284
+	public function createFloatField($table_column, $nice_name, $nullable, $default_value = null)
285
+	{
286
+		return $this->loader->getNew(
287
+			'EE_Float_Field',
288
+			array($table_column, $nice_name, $nullable, $default_value)
289
+		);
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * @param string $table_column
296
+	 * @param string $nice_name
297
+	 * @param bool   $nullable
298
+	 * @param null   $default_value
299
+	 * @param string $model_name
300
+	 * @return EE_Foreign_Key_Int_Field
301
+	 */
302
+	public function createForeignKeyIntField($table_column, $nice_name, $nullable, $default_value, $model_name)
303
+	{
304
+		return $this->loader->getNew(
305
+			'EE_Foreign_Key_Int_Field',
306
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
307
+		);
308
+	}
309
+
310
+
311
+
312
+	/**
313
+	 * @param string $table_column
314
+	 * @param string $nice_name
315
+	 * @param bool   $nullable
316
+	 * @param null   $default_value
317
+	 * @param string $model_name
318
+	 * @return EE_Foreign_Key_String_Field
319
+	 */
320
+	public function createForeignKeyStringField(
321
+		$table_column,
322
+		$nice_name,
323
+		$nullable,
324
+		$default_value,
325
+		$model_name
326
+	) {
327
+		return $this->loader->getNew(
328
+			'EE_Foreign_Key_String_Field',
329
+			array($table_column, $nice_name, $nullable, $default_value, $model_name)
330
+		);
331
+	}
332
+
333
+
334
+
335
+	/**
336
+	 * @param string $table_column
337
+	 * @param string $nice_name
338
+	 * @param bool   $nullable
339
+	 * @param null   $default_value
340
+	 * @return EE_Full_HTML_Field
341
+	 */
342
+	public function createFullHtmlField($table_column, $nice_name, $nullable, $default_value = null)
343
+	{
344
+		return $this->loader->getNew(
345
+			'EE_Full_HTML_Field',
346
+			array($table_column, $nice_name, $nullable, $default_value)
347
+		);
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * @param string $table_column
354
+	 * @param string $nice_name
355
+	 * @param bool   $nullable
356
+	 * @param null   $default_value
357
+	 * @return EE_Infinite_Integer_Field
358
+	 */
359
+	public function createInfiniteIntegerField($table_column, $nice_name, $nullable, $default_value = null)
360
+	{
361
+		return $this->loader->getNew(
362
+			'EE_Infinite_Integer_Field',
363
+			array($table_column, $nice_name, $nullable, $default_value)
364
+		);
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * @param string $table_column
371
+	 * @param string $nice_name
372
+	 * @param bool   $nullable
373
+	 * @param null   $default_value
374
+	 * @return EE_Integer_Field
375
+	 */
376
+	public function createIntegerField($table_column, $nice_name, $nullable, $default_value = null)
377
+	{
378
+		return $this->loader->getNew(
379
+			'EE_Integer_Field',
380
+			array($table_column, $nice_name, $nullable, $default_value)
381
+		);
382
+	}
383
+
384
+
385
+
386
+	/**
387
+	 * @param string $table_column
388
+	 * @param string $nice_name
389
+	 * @param bool   $nullable
390
+	 * @param null   $default_value
391
+	 * @return EE_Maybe_Serialized_Simple_HTML_Field
392
+	 */
393
+	public function createMaybeSerializedSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
394
+	{
395
+		return $this->loader->getNew(
396
+			'EE_Maybe_Serialized_Simple_HTML_Field',
397
+			array($table_column, $nice_name, $nullable, $default_value)
398
+		);
399
+	}
400
+
401
+
402
+
403
+	/**
404
+	 * @param string $table_column
405
+	 * @param string $nice_name
406
+	 * @param bool   $nullable
407
+	 * @param null   $default_value
408
+	 * @return EE_Maybe_Serialized_Text_Field
409
+	 */
410
+	public function createMaybeSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
411
+	{
412
+		return $this->loader->getNew(
413
+			'EE_Maybe_Serialized_Text_Field',
414
+			array($table_column, $nice_name, $nullable, $default_value)
415
+		);
416
+	}
417
+
418
+
419
+
420
+	/**
421
+	 * @param string $table_column
422
+	 * @param string $nice_name
423
+	 * @param bool   $nullable
424
+	 * @param null   $default_value
425
+	 * @return EE_Money_Field
426
+	 */
427
+	public function createMoneyField($table_column, $nice_name, $nullable, $default_value = null)
428
+	{
429
+		return $this->loader->getNew(
430
+			'EE_Money_Field',
431
+			array($table_column, $nice_name, $nullable, $default_value)
432
+		);
433
+	}
434
+
435
+
436
+
437
+	/**
438
+	 * @param string $table_column
439
+	 * @param string $nice_name
440
+	 * @param bool   $nullable
441
+	 * @param string $default_value
442
+	 * @return EE_Plain_Text_Field
443
+	 */
444
+	public function createPlainTextField($table_column, $nice_name, $nullable = true, $default_value = '')
445
+	{
446
+		return $this->loader->getNew(
447
+			'EE_Plain_Text_Field',
448
+			array($table_column, $nice_name, $nullable, $default_value)
449
+		);
450
+	}
451
+
452
+
453
+
454
+	/**
455
+	 * @param string $table_column
456
+	 * @param string $nice_name
457
+	 * @param bool   $nullable
458
+	 * @param null   $default_value
459
+	 * @return EE_Post_Content_Field
460
+	 */
461
+	public function createPostContentField($table_column, $nice_name, $nullable, $default_value = null)
462
+	{
463
+		return $this->loader->getNew(
464
+			'EE_Post_Content_Field',
465
+			array($table_column, $nice_name, $nullable, $default_value)
466
+		);
467
+	}
468
+
469
+
470
+
471
+	/**
472
+	 * @param string $table_column
473
+	 * @param string $nice_name
474
+	 * @return EE_Primary_Key_Int_Field
475
+	 */
476
+	public function createPrimaryKeyIntField($table_column, $nice_name)
477
+	{
478
+		return $this->loader->getNew('EE_Primary_Key_Int_Field', array($table_column, $nice_name));
479
+	}
480
+
481
+
482
+
483
+	/**
484
+	 * @param string $table_column
485
+	 * @param string $nice_name
486
+	 * @return EE_Primary_Key_String_Field
487
+	 */
488
+	public function createPrimaryKeyStringField($table_column, $nice_name)
489
+	{
490
+		return $this->loader->getNew('EE_Primary_Key_String_Field', array($table_column, $nice_name));
491
+	}
492
+
493
+
494
+
495
+	/**
496
+	 * @param string $table_column
497
+	 * @param string $nice_name
498
+	 * @param bool   $nullable
499
+	 * @param null   $default_value
500
+	 * @return EE_Serialized_Text_Field
501
+	 */
502
+	public function createSerializedTextField($table_column, $nice_name, $nullable, $default_value = null)
503
+	{
504
+		return $this->loader->getNew(
505
+			'EE_Serialized_Text_Field',
506
+			array($table_column, $nice_name, $nullable, $default_value)
507
+		);
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * @param string $table_column
514
+	 * @param string $nice_name
515
+	 * @param bool   $nullable
516
+	 * @param null   $default_value
517
+	 * @return EE_Simple_HTML_Field
518
+	 */
519
+	public function createSimpleHtmlField($table_column, $nice_name, $nullable, $default_value = null)
520
+	{
521
+		return $this->loader->getNew(
522
+			'EE_Simple_HTML_Field',
523
+			array($table_column, $nice_name, $nullable, $default_value)
524
+		);
525
+	}
526
+
527
+
528
+
529
+	/**
530
+	 * @param string $table_column
531
+	 * @param string $nice_name
532
+	 * @param bool   $nullable
533
+	 * @param null   $default_value
534
+	 * @return EE_Slug_Field
535
+	 */
536
+	public function createSlugField($table_column, $nice_name, $nullable = false, $default_value = null)
537
+	{
538
+		return $this->loader->getNew(
539
+			'EE_Slug_Field',
540
+			array($table_column, $nice_name, $nullable, $default_value)
541
+		);
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * @param string $table_column
548
+	 * @param string $nice_name
549
+	 * @param bool   $nullable
550
+	 * @param null   $default_value
551
+	 * @return EE_Trashed_Flag_Field
552
+	 */
553
+	public function createTrashedFlagField($table_column, $nice_name, $nullable, $default_value = null)
554
+	{
555
+		return $this->loader->getNew(
556
+			'EE_Trashed_Flag_Field',
557
+			array($table_column, $nice_name, $nullable, $default_value)
558
+		);
559
+	}
560
+
561
+
562
+
563
+	/**
564
+	 * @param string $table_column
565
+	 * @param string $nice_name
566
+	 * @param bool   $nullable
567
+	 * @param mixed  $default_value
568
+	 * @param array  $values        If additional stati are to be used other than the default WP statuses,
569
+	 *                              then they can be registered via this property.
570
+	 *                              The format of the array should be as follows:
571
+	 *  array(
572
+	 *      'status_reference' => array(
573
+	 *          'label' => __('Status Reference Label', 'event_espresso'),
574
+	 *          'public' => true,                 // whether this status should be shown on the frontend of the site
575
+	 *          'exclude_from_search' => false,   // whether this status should be excluded from wp searches
576
+	 *          'show_in_admin_all_list' => true, // whether this status is included in queries
577
+	 *                                               for the admin "all" view in list table views.
578
+	 *          'show_in_admin_status_list' => true, // show in the list of statuses with post counts at the top
579
+	 *                                                  of the admin list tables (i.e. Status Reference(2) )
580
+	 *          'label_count' => _n_noop(
581
+	 *              'Status Reference <span class="count">(%s)</span>',
582
+	 *              'Status References <span class="count">(%s)</span>'
583
+	 *          ),                                   // the text to display on the admin screen
584
+	 *                                                  ( or you won't see your status count ).
585
+	 *      )
586
+	 *  )
587
+	 * @link http://codex.wordpress.org/Function_Reference/register_post_status for more info
588
+	 * @return EE_WP_Post_Status_Field
589
+	 */
590
+	public function createWpPostStatusField(
591
+		$table_column,
592
+		$nice_name,
593
+		$nullable,
594
+		$default_value = null,
595
+		array $values = array()
596
+	) {
597
+		return $this->loader->getNew(
598
+			'EE_WP_Post_Status_Field',
599
+			array($table_column, $nice_name, $nullable, $default_value, $values)
600
+		);
601
+	}
602
+
603
+
604
+
605
+	/**
606
+	 * @param string $post_type
607
+	 * @return EE_WP_Post_Type_Field
608
+	 */
609
+	public function createWpPostTypeField($post_type)
610
+	{
611
+		return $this->loader->getNew('EE_WP_Post_Type_Field', array($post_type));
612
+	}
613
+
614
+
615
+
616
+	/**
617
+	 * @param string $table_column
618
+	 * @param string $nice_name
619
+	 * @param bool   $nullable
620
+	 * @return EE_WP_User_Field
621
+	 */
622
+	public function createWpUserField($table_column, $nice_name, $nullable)
623
+	{
624
+		return $this->loader->getNew('EE_WP_User_Field', array($table_column, $nice_name, $nullable));
625
+	}
626 626
 
627 627
 
628 628
 
Please login to merge, or discard this patch.
core/services/Benchmark.php 2 patches
Indentation   +297 added lines, -297 removed lines patch added patch discarded remove patch
@@ -17,303 +17,303 @@
 block discarded – undo
17 17
 class Benchmark
18 18
 {
19 19
 
20
-    /**
21
-     * array containing the start time for the timers
22
-     */
23
-    private static $start_times;
24
-
25
-    /**
26
-     * array containing all the timer'd times, which can be outputted via show_times()
27
-     */
28
-    private static $times = array();
29
-
30
-    /**
31
-     * @var array
32
-     */
33
-    protected static $memory_usage = array();
34
-
35
-
36
-
37
-    /**
38
-     * whether to benchmark code or not
39
-     */
40
-    public static function doNotRun()
41
-    {
42
-        return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
-    }
44
-
45
-
46
-
47
-    /**
48
-     * resetTimes
49
-     */
50
-    public static function resetTimes()
51
-    {
52
-        Benchmark::$times = array();
53
-    }
54
-
55
-
56
-
57
-    /**
58
-     * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
-     *
60
-     * @param null $timer_name
61
-     */
62
-    public static function startTimer($timer_name = null)
63
-    {
64
-        if (Benchmark::doNotRun()) {
65
-            return;
66
-        }
67
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
-        Benchmark::$start_times[$timer_name] = microtime(true);
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
-     *
76
-     * @param string $timer_name
77
-     */
78
-    public static function stopTimer($timer_name = '')
79
-    {
80
-        if (Benchmark::doNotRun()) {
81
-            return;
82
-        }
83
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
-        if (isset(Benchmark::$start_times[$timer_name])) {
85
-            $start_time = Benchmark::$start_times[$timer_name];
86
-            unset(Benchmark::$start_times[$timer_name]);
87
-        } else {
88
-            $start_time = array_pop(Benchmark::$start_times);
89
-        }
90
-        Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     * Measure the memory usage by PHP so far.
97
-     *
98
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
-     * @param bool    $formatted
101
-     * @return void
102
-     */
103
-    public static function measureMemory($label = 'memory usage', $output_now = false, $formatted = true)
104
-    {
105
-        if (Benchmark::doNotRun()) {
106
-            return;
107
-        }
108
-        $memory_used = Benchmark::convert(memory_get_peak_usage(true));
109
-        Benchmark::$memory_usage[$label] = $memory_used;
110
-        if ($output_now) {
111
-            echo $formatted
112
-                ? "<br>{$label} : {$memory_used}"
113
-                : "\n {$label} : {$memory_used}";
114
-        }
115
-    }
116
-
117
-
118
-
119
-    /**
120
-     * will display the benchmarking results at shutdown
121
-     *
122
-     * @param bool $formatted
123
-     * @return void
124
-     */
125
-    public static function displayResultsAtShutdown($formatted = true)
126
-    {
127
-        add_action(
128
-            'shutdown',
129
-            function () use ($formatted) {
130
-                Benchmark::displayResults(true, $formatted);
131
-            }
132
-        );
133
-    }
134
-
135
-
136
-
137
-    /**
138
-     * will display the benchmarking results at shutdown
139
-     *
140
-     * @param string $filepath
141
-     * @param bool   $formatted
142
-     * @param bool   $append
143
-     * @return void
144
-     */
145
-    public static function writeResultsAtShutdown($filepath = '', $formatted = true, $append = true)
146
-    {
147
-        add_action(
148
-            'shutdown',
149
-            function () use ($filepath, $formatted, $append) {
150
-                Benchmark::writeResultsToFile($filepath, $formatted, $append);
151
-            }
152
-        );
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     * @param bool $formatted
159
-     * @return string
160
-     */
161
-    private static function generateResults($formatted = true)
162
-    {
163
-        if (Benchmark::doNotRun()) {
164
-            return '';
165
-        }
166
-        $output = '';
167
-        if (! empty(Benchmark::$times)) {
168
-            $total = 0;
169
-            $output .= $formatted
170
-                ? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
171
-                : '';
172
-            foreach (Benchmark::$times as $timer_name => $total_time) {
173
-                $output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
174
-                $output .= $formatted ? '<br />'  : "\n";
175
-                $total += $total_time;
176
-            }
177
-            if($formatted) {
178
-                $output .= '<br />';
179
-                $output .= '<h4>TOTAL TIME</h4>';
180
-                $output .= Benchmark::formatTime('', $total, $formatted);
181
-                $output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
182
-                $output .= '<br />';
183
-                $output .= '<h5>Performance scale (from best to worse)</h5>';
184
-                $output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
185
-                $output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
186
-                $output .= '<span style="color:limegreen">Like...groovy!</span><br />';
187
-                $output .= '<span style="color:gold">Ruh Oh</span><br />';
188
-                $output .= '<span style="color:darkorange">Zoinks!</span><br />';
189
-                $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
190
-            }
191
-        }
192
-        if (! empty(Benchmark::$memory_usage)) {
193
-            $output .= $formatted
194
-                ? '<h5>Memory</h5>' . implode('<br />', Benchmark::$memory_usage)
195
-                : implode("\n", Benchmark::$memory_usage);
196
-        }
197
-        if (empty($output)) {
198
-            return '';
199
-        }
200
-        $output = $formatted
201
-            ? '<div style="border:1px solid #dddddd; background-color:#ffffff;'
202
-              . (is_admin()
203
-                ? ' margin:2em 2em 2em 180px;'
204
-                : ' margin:2em;')
205
-              . ' padding:2em;">'
206
-              . '<h4>BENCHMARKING</h4>'
207
-              . $output
208
-              . '</div>'
209
-            : $output;
210
-        return $output;
211
-    }
212
-
213
-
214
-
215
-    /**
216
-     * @param bool $echo
217
-     * @param bool $formatted
218
-     * @return string
219
-     */
220
-    public static function displayResults($echo = true, $formatted = true)
221
-    {
222
-        $results = Benchmark::generateResults($formatted);
223
-        if ($echo) {
224
-            echo $results;
225
-            $results = '';
226
-        }
227
-        return $results;
228
-    }
229
-
230
-
231
-
232
-    /**
233
-     * @param string $filepath
234
-     * @param bool   $formatted
235
-     * @param bool   $append
236
-     */
237
-    public static function writeResultsToFile($filepath = '', $formatted = true, $append = true)
238
-    {
239
-        $filepath = ! empty($filepath) && is_readable(dirname($filepath))
240
-            ? $filepath
241
-            : '';
242
-        if( empty($filepath)) {
243
-            $filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
244
-        }
245
-        file_put_contents(
246
-            $filepath,
247
-            "\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
248
-            $append ? FILE_APPEND | LOCK_EX : LOCK_EX
249
-        );
250
-    }
251
-
252
-
253
-
254
-    /**
255
-     * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
256
-     *
257
-     * @param int $size
258
-     * @return string
259
-     */
260
-    public static function convert($size)
261
-    {
262
-        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
263
-        return round(
264
-            $size / pow(1024, $i = floor(log($size, 1024))),
265
-            2
266
-        ) . ' ' . $unit[absint($i)];
267
-    }
268
-
269
-
270
-
271
-    /**
272
-     * @param string $timer_name
273
-     * @param float  $total_time
274
-     * @param bool   $formatted
275
-     * @return string
276
-     */
277
-    public static function formatTime($timer_name, $total_time, $formatted = true)
278
-    {
279
-        $total_time *= 1000;
280
-        switch ($total_time) {
281
-            case $total_time > 12500 :
282
-                $color = 'red';
283
-                $bold = 'bold';
284
-                break;
285
-            case $total_time > 2500 :
286
-                $color = 'darkorange';
287
-                $bold = 'bold';
288
-                break;
289
-            case $total_time > 500 :
290
-                $color = 'gold';
291
-                $bold = 'bold';
292
-                break;
293
-            case $total_time > 100 :
294
-                $color = 'limegreen';
295
-                $bold = 'normal';
296
-                break;
297
-            case $total_time > 20 :
298
-                $color = 'deepskyblue';
299
-                $bold = 'normal';
300
-                break;
301
-            default :
302
-                $color = 'mediumpurple';
303
-                $bold = 'normal';
304
-                break;
305
-        }
306
-        return $formatted
307
-            ? '<span style="min-width: 10px; margin:0 1em; color:'
308
-               . $color
309
-               . '; font-weight:'
310
-               . $bold
311
-               . '; font-size:1.2em;">'
312
-               . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
313
-               . '</span> '
314
-               . $timer_name
315
-            :  str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT);
316
-    }
20
+	/**
21
+	 * array containing the start time for the timers
22
+	 */
23
+	private static $start_times;
24
+
25
+	/**
26
+	 * array containing all the timer'd times, which can be outputted via show_times()
27
+	 */
28
+	private static $times = array();
29
+
30
+	/**
31
+	 * @var array
32
+	 */
33
+	protected static $memory_usage = array();
34
+
35
+
36
+
37
+	/**
38
+	 * whether to benchmark code or not
39
+	 */
40
+	public static function doNotRun()
41
+	{
42
+		return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
+	}
44
+
45
+
46
+
47
+	/**
48
+	 * resetTimes
49
+	 */
50
+	public static function resetTimes()
51
+	{
52
+		Benchmark::$times = array();
53
+	}
54
+
55
+
56
+
57
+	/**
58
+	 * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
+	 *
60
+	 * @param null $timer_name
61
+	 */
62
+	public static function startTimer($timer_name = null)
63
+	{
64
+		if (Benchmark::doNotRun()) {
65
+			return;
66
+		}
67
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
+		Benchmark::$start_times[$timer_name] = microtime(true);
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
+	 *
76
+	 * @param string $timer_name
77
+	 */
78
+	public static function stopTimer($timer_name = '')
79
+	{
80
+		if (Benchmark::doNotRun()) {
81
+			return;
82
+		}
83
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
+		if (isset(Benchmark::$start_times[$timer_name])) {
85
+			$start_time = Benchmark::$start_times[$timer_name];
86
+			unset(Benchmark::$start_times[$timer_name]);
87
+		} else {
88
+			$start_time = array_pop(Benchmark::$start_times);
89
+		}
90
+		Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 * Measure the memory usage by PHP so far.
97
+	 *
98
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
+	 * @param bool    $formatted
101
+	 * @return void
102
+	 */
103
+	public static function measureMemory($label = 'memory usage', $output_now = false, $formatted = true)
104
+	{
105
+		if (Benchmark::doNotRun()) {
106
+			return;
107
+		}
108
+		$memory_used = Benchmark::convert(memory_get_peak_usage(true));
109
+		Benchmark::$memory_usage[$label] = $memory_used;
110
+		if ($output_now) {
111
+			echo $formatted
112
+				? "<br>{$label} : {$memory_used}"
113
+				: "\n {$label} : {$memory_used}";
114
+		}
115
+	}
116
+
117
+
118
+
119
+	/**
120
+	 * will display the benchmarking results at shutdown
121
+	 *
122
+	 * @param bool $formatted
123
+	 * @return void
124
+	 */
125
+	public static function displayResultsAtShutdown($formatted = true)
126
+	{
127
+		add_action(
128
+			'shutdown',
129
+			function () use ($formatted) {
130
+				Benchmark::displayResults(true, $formatted);
131
+			}
132
+		);
133
+	}
134
+
135
+
136
+
137
+	/**
138
+	 * will display the benchmarking results at shutdown
139
+	 *
140
+	 * @param string $filepath
141
+	 * @param bool   $formatted
142
+	 * @param bool   $append
143
+	 * @return void
144
+	 */
145
+	public static function writeResultsAtShutdown($filepath = '', $formatted = true, $append = true)
146
+	{
147
+		add_action(
148
+			'shutdown',
149
+			function () use ($filepath, $formatted, $append) {
150
+				Benchmark::writeResultsToFile($filepath, $formatted, $append);
151
+			}
152
+		);
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 * @param bool $formatted
159
+	 * @return string
160
+	 */
161
+	private static function generateResults($formatted = true)
162
+	{
163
+		if (Benchmark::doNotRun()) {
164
+			return '';
165
+		}
166
+		$output = '';
167
+		if (! empty(Benchmark::$times)) {
168
+			$total = 0;
169
+			$output .= $formatted
170
+				? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
171
+				: '';
172
+			foreach (Benchmark::$times as $timer_name => $total_time) {
173
+				$output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
174
+				$output .= $formatted ? '<br />'  : "\n";
175
+				$total += $total_time;
176
+			}
177
+			if($formatted) {
178
+				$output .= '<br />';
179
+				$output .= '<h4>TOTAL TIME</h4>';
180
+				$output .= Benchmark::formatTime('', $total, $formatted);
181
+				$output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
182
+				$output .= '<br />';
183
+				$output .= '<h5>Performance scale (from best to worse)</h5>';
184
+				$output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
185
+				$output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
186
+				$output .= '<span style="color:limegreen">Like...groovy!</span><br />';
187
+				$output .= '<span style="color:gold">Ruh Oh</span><br />';
188
+				$output .= '<span style="color:darkorange">Zoinks!</span><br />';
189
+				$output .= '<span style="color:red">Like...HEEELLLP</span><br />';
190
+			}
191
+		}
192
+		if (! empty(Benchmark::$memory_usage)) {
193
+			$output .= $formatted
194
+				? '<h5>Memory</h5>' . implode('<br />', Benchmark::$memory_usage)
195
+				: implode("\n", Benchmark::$memory_usage);
196
+		}
197
+		if (empty($output)) {
198
+			return '';
199
+		}
200
+		$output = $formatted
201
+			? '<div style="border:1px solid #dddddd; background-color:#ffffff;'
202
+			  . (is_admin()
203
+				? ' margin:2em 2em 2em 180px;'
204
+				: ' margin:2em;')
205
+			  . ' padding:2em;">'
206
+			  . '<h4>BENCHMARKING</h4>'
207
+			  . $output
208
+			  . '</div>'
209
+			: $output;
210
+		return $output;
211
+	}
212
+
213
+
214
+
215
+	/**
216
+	 * @param bool $echo
217
+	 * @param bool $formatted
218
+	 * @return string
219
+	 */
220
+	public static function displayResults($echo = true, $formatted = true)
221
+	{
222
+		$results = Benchmark::generateResults($formatted);
223
+		if ($echo) {
224
+			echo $results;
225
+			$results = '';
226
+		}
227
+		return $results;
228
+	}
229
+
230
+
231
+
232
+	/**
233
+	 * @param string $filepath
234
+	 * @param bool   $formatted
235
+	 * @param bool   $append
236
+	 */
237
+	public static function writeResultsToFile($filepath = '', $formatted = true, $append = true)
238
+	{
239
+		$filepath = ! empty($filepath) && is_readable(dirname($filepath))
240
+			? $filepath
241
+			: '';
242
+		if( empty($filepath)) {
243
+			$filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
244
+		}
245
+		file_put_contents(
246
+			$filepath,
247
+			"\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
248
+			$append ? FILE_APPEND | LOCK_EX : LOCK_EX
249
+		);
250
+	}
251
+
252
+
253
+
254
+	/**
255
+	 * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
256
+	 *
257
+	 * @param int $size
258
+	 * @return string
259
+	 */
260
+	public static function convert($size)
261
+	{
262
+		$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
263
+		return round(
264
+			$size / pow(1024, $i = floor(log($size, 1024))),
265
+			2
266
+		) . ' ' . $unit[absint($i)];
267
+	}
268
+
269
+
270
+
271
+	/**
272
+	 * @param string $timer_name
273
+	 * @param float  $total_time
274
+	 * @param bool   $formatted
275
+	 * @return string
276
+	 */
277
+	public static function formatTime($timer_name, $total_time, $formatted = true)
278
+	{
279
+		$total_time *= 1000;
280
+		switch ($total_time) {
281
+			case $total_time > 12500 :
282
+				$color = 'red';
283
+				$bold = 'bold';
284
+				break;
285
+			case $total_time > 2500 :
286
+				$color = 'darkorange';
287
+				$bold = 'bold';
288
+				break;
289
+			case $total_time > 500 :
290
+				$color = 'gold';
291
+				$bold = 'bold';
292
+				break;
293
+			case $total_time > 100 :
294
+				$color = 'limegreen';
295
+				$bold = 'normal';
296
+				break;
297
+			case $total_time > 20 :
298
+				$color = 'deepskyblue';
299
+				$bold = 'normal';
300
+				break;
301
+			default :
302
+				$color = 'mediumpurple';
303
+				$bold = 'normal';
304
+				break;
305
+		}
306
+		return $formatted
307
+			? '<span style="min-width: 10px; margin:0 1em; color:'
308
+			   . $color
309
+			   . '; font-weight:'
310
+			   . $bold
311
+			   . '; font-size:1.2em;">'
312
+			   . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
313
+			   . '</span> '
314
+			   . $timer_name
315
+			:  str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT);
316
+	}
317 317
 
318 318
 
319 319
 
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
     {
127 127
         add_action(
128 128
             'shutdown',
129
-            function () use ($formatted) {
129
+            function() use ($formatted) {
130 130
                 Benchmark::displayResults(true, $formatted);
131 131
             }
132 132
         );
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
     {
147 147
         add_action(
148 148
             'shutdown',
149
-            function () use ($filepath, $formatted, $append) {
149
+            function() use ($filepath, $formatted, $append) {
150 150
                 Benchmark::writeResultsToFile($filepath, $formatted, $append);
151 151
             }
152 152
         );
@@ -164,17 +164,17 @@  discard block
 block discarded – undo
164 164
             return '';
165 165
         }
166 166
         $output = '';
167
-        if (! empty(Benchmark::$times)) {
167
+        if ( ! empty(Benchmark::$times)) {
168 168
             $total = 0;
169 169
             $output .= $formatted
170 170
                 ? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
171 171
                 : '';
172 172
             foreach (Benchmark::$times as $timer_name => $total_time) {
173 173
                 $output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
174
-                $output .= $formatted ? '<br />'  : "\n";
174
+                $output .= $formatted ? '<br />' : "\n";
175 175
                 $total += $total_time;
176 176
             }
177
-            if($formatted) {
177
+            if ($formatted) {
178 178
                 $output .= '<br />';
179 179
                 $output .= '<h4>TOTAL TIME</h4>';
180 180
                 $output .= Benchmark::formatTime('', $total, $formatted);
@@ -189,9 +189,9 @@  discard block
 block discarded – undo
189 189
                 $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
190 190
             }
191 191
         }
192
-        if (! empty(Benchmark::$memory_usage)) {
192
+        if ( ! empty(Benchmark::$memory_usage)) {
193 193
             $output .= $formatted
194
-                ? '<h5>Memory</h5>' . implode('<br />', Benchmark::$memory_usage)
194
+                ? '<h5>Memory</h5>'.implode('<br />', Benchmark::$memory_usage)
195 195
                 : implode("\n", Benchmark::$memory_usage);
196 196
         }
197 197
         if (empty($output)) {
@@ -239,12 +239,12 @@  discard block
 block discarded – undo
239 239
         $filepath = ! empty($filepath) && is_readable(dirname($filepath))
240 240
             ? $filepath
241 241
             : '';
242
-        if( empty($filepath)) {
243
-            $filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
242
+        if (empty($filepath)) {
243
+            $filepath = EVENT_ESPRESSO_UPLOAD_DIR.'logs/benchmarking-'.date('Y-m-d').'.html';
244 244
         }
245 245
         file_put_contents(
246 246
             $filepath,
247
-            "\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
247
+            "\n".date('Y-m-d H:i:s').Benchmark::generateResults($formatted),
248 248
             $append ? FILE_APPEND | LOCK_EX : LOCK_EX
249 249
         );
250 250
     }
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
         return round(
264 264
             $size / pow(1024, $i = floor(log($size, 1024))),
265 265
             2
266
-        ) . ' ' . $unit[absint($i)];
266
+        ).' '.$unit[absint($i)];
267 267
     }
268 268
 
269 269
 
Please login to merge, or discard this patch.
core/libraries/shortcodes/EE_Venue_Shortcodes.lib.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@
 block discarded – undo
157 157
     /**
158 158
      * This retrieves the EE_Venue from the available data object.
159 159
      *
160
-     * @return EE_Venue|null
160
+     * @return EE_Base_Class|null
161 161
      */
162 162
     private function _get_venue() {
163 163
 
Please login to merge, or discard this patch.
Indentation   +284 added lines, -284 removed lines patch added patch discarded remove patch
@@ -16,288 +16,288 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * Will hold the EE_Event if available
21
-     *
22
-     * @var EE_Event
23
-     */
24
-    protected $_event;
25
-
26
-    /**
27
-     * Will hold the EE_Venue if available
28
-     *
29
-     * @var EE_Venue
30
-     */
31
-    protected $_venue;
32
-
33
-
34
-    /**
35
-     * Initialize properties
36
-     */
37
-    protected function _init_props()
38
-    {
39
-        $this->label       = esc_html__('Venue Shortcodes', 'event_espresso');
40
-        $this->description = esc_html__('All shortcodes specific to venue related data', 'event_espresso');
41
-        $this->_shortcodes = array(
42
-            '[VENUE_TITLE]'             => esc_html__('The title for the event venue', 'event_espresso'),
43
-            '[VENUE_DESCRIPTION]'       => esc_html__('The description for the event venue', 'event_espresso'),
44
-            '[VENUE_URL]'               => esc_html__('A url to a webpage for the venue', 'event_espresso'),
45
-            '[VENUE_IMAGE]'             => esc_html__('An image representing the event venue', 'event_espresso'),
46
-            '[VENUE_PHONE]'             => esc_html__('The phone number for the venue', 'event_espresso'),
47
-            '[VENUE_ADDRESS]'           => esc_html__('The address for the venue', 'event_espresso'),
48
-            '[VENUE_ADDRESS2]'          => esc_html__('Address 2 for the venue', 'event_espresso'),
49
-            '[VENUE_CITY]'              => esc_html__('The city the venue is in', 'event_espresso'),
50
-            '[VENUE_STATE]'             => esc_html__('The state the venue is located in', 'event_espresso'),
51
-            '[VENUE_COUNTRY]'           => esc_html__('The country the venue is located in', 'event_espresso'),
52
-            '[VENUE_FORMATTED_ADDRESS]' => esc_html__(
53
-                'This just outputs the venue address in a semantic address format.',
54
-                'event_espresso'
55
-            ),
56
-            '[VENUE_ZIP]'               => esc_html__('The zip code for the venue address', 'event_espresso'),
57
-            '[VENUE_META_*]'            => esc_html__(
58
-                'This is a special dynamic shortcode. After the "*", add the exact name for your custom field, if there is a value set for that custom field within the venue then it will be output in place of this shortcode.', 
59
-                'event_espresso'
60
-            ),
61
-            '[GOOGLE_MAP_URL]'          => esc_html__(
62
-                'URL for the google map associated with the venue.', 
63
-                'event_espresso'
64
-            ),
65
-            '[GOOGLE_MAP_LINK]'         => esc_html__('Link to a google map for the venue', 'event_espresso'),
66
-            '[GOOGLE_MAP_IMAGE]'        => esc_html__('Google map for venue wrapped in image tags', 'event_espresso'),
67
-        );
68
-    }
69
-
70
-
71
-    /**
72
-     * Parse incoming shortcode
73
-     * @param string $shortcode
74
-     * @return string
75
-     */
76
-    protected function _parser($shortcode)
77
-    {
78
-        $this->_venue = $this->_get_venue();
79
-        //If there is no venue object by now then get out.
80
-        if ( ! $this->_venue instanceof EE_Venue )
81
-            return '';
82
-
83
-        switch ($shortcode) {
84
-            case '[VENUE_TITLE]':
85
-                return $this->_venue('title');
86
-                break;
87
-
88
-            case '[VENUE_DESCRIPTION]':
89
-                return $this->_venue('description');
90
-                break;
91
-
92
-            case '[VENUE_URL]':
93
-                return $this->_venue('url');
94
-                break;
95
-
96
-            case '[VENUE_IMAGE]':
97
-                return $this->_venue('image');
98
-                break;
99
-
100
-            case '[VENUE_PHONE]':
101
-                return $this->_venue('phone');
102
-                break;
103
-
104
-            case '[VENUE_ADDRESS]':
105
-                return $this->_venue('address');
106
-                break;
107
-
108
-            case '[VENUE_ADDRESS2]':
109
-                return $this->_venue('address2');
110
-                break;
111
-
112
-            case '[VENUE_CITY]':
113
-                return $this->_venue('city');
114
-                break;
115
-
116
-            case '[VENUE_COUNTRY]':
117
-                return $this->_venue('country');
118
-                break;
119
-
120
-            case '[VENUE_STATE]':
121
-                return $this->_venue('state');
122
-                break;
123
-
124
-            case '[VENUE_ZIP]':
125
-                return $this->_venue('zip');
126
-                break;
127
-
128
-            case '[VENUE_FORMATTED_ADDRESS]':
129
-                return $this->_venue('formatted_address');
130
-                break;
131
-
132
-            case '[GOOGLE_MAP_URL]':
133
-                return $this->_venue('gmap_url');
134
-                break;
135
-
136
-            case '[GOOGLE_MAP_LINK]':
137
-                return $this->_venue('gmap_link');
138
-                break;
139
-
140
-            case '[GOOGLE_MAP_IMAGE]':
141
-                return $this->_venue('gmap_link_img');
142
-                break;
143
-
144
-        }
145
-
146
-        if ( strpos( $shortcode, '[VENUE_META_*' ) !== false ) {
147
-            $shortcode = str_replace( '[VENUE_META_*', '', $shortcode );
148
-            $shortcode = trim( str_replace( ']', '', $shortcode ) );
149
-
150
-            //pull the meta value from the venue post
151
-            $venue_meta = $this->_venue->get_post_meta( $shortcode, true );
152
-
153
-            return ! empty( $venue_meta ) ? $venue_meta : '';
154
-
155
-        }
156
-    }
157
-    /**
158
-     * This retrieves the EE_Venue from the available data object.
159
-     *
160
-     * @return EE_Venue|null
161
-     */
162
-    private function _get_venue() {
163
-
164
-        //we need the EE_Event object to get the venue.
165
-        $this->_event = $this->_data instanceof EE_Event ? $this->_data : null;
166
-
167
-        //if no event, then let's see if there is a reg_obj.  If there IS, then we'll try and grab the event from the reg_obj instead.
168
-        if (empty($this->_event)) {
169
-            $aee = $this->_data instanceof EE_Messages_Addressee ? $this->_data : null;
170
-            $aee = $this->_extra_data instanceof EE_Messages_Addressee ? $this->_extra_data : $aee;
171
-
172
-            $this->_event = $aee instanceof EE_Messages_Addressee && $aee->reg_obj instanceof EE_Registration ? $aee->reg_obj->event() : null;
173
-
174
-            //if still empty do we have a ticket data item?
175
-            $this->_event = empty($this->_event)
176
-                            && $this->_data instanceof EE_Ticket
177
-                            && $this->_extra_data['data'] instanceof EE_Messages_Addressee
178
-                ? $this->_extra_data['data']->tickets[$this->_data->ID()]['EE_Event']
179
-                : $this->_event;
180
-
181
-            //if STILL empty event, let's try to get the first event in the list of events via EE_Messages_Addressee and use that.
182
-            $event        = $aee instanceof EE_Messages_Addressee ? reset($aee->events) : array();
183
-            $this->_event = empty($this->_event) && ! empty($events) ? $event : $this->_event;
184
-        }
185
-
186
-        //If we have an event object use it to pull the venue.
187
-        if ($this->_event instanceof EE_Event) {
188
-            return $this->_event->get_first_related('Venue');
189
-        } 
190
-
191
-        return null;
192
-    }
193
-
194
-    /**
195
-     * This retrieves the specified venue information
196
-     *
197
-     * @param string $field  What Venue field to retrieve
198
-     * @return string What was retrieved!
199
-     * @throws EE_Error
200
-     * @throws \EventEspresso\core\exceptions\EntityNotFoundException
201
-     */
202
-    private function _venue($field)
203
-    {
204
-
205
-        if (empty($this->_venue)) {
206
-            return '';
207
-        } //no venue so get out.
208
-
209
-        switch ($field) {
210
-            case 'title':
211
-                return $this->_venue->get('VNU_name');
212
-                break;
213
-
214
-            case 'description':
215
-                return $this->_venue->get('VNU_desc');
216
-                break;
217
-
218
-            case 'url':
219
-                $url = $this->_venue->get('VNU_url');
220
-                return empty($url) ? $this->_venue->get_permalink() : $url;
221
-                break;
222
-
223
-            case 'image':
224
-                return '<img src="' . $this->_venue->feature_image_url(array(200, 200,))
225
-                       . '" alt="' . sprintf(
226
-                           esc_attr__('%s Feature Image', 'event_espresso'),
227
-                           $this->_venue->get('VNU_name')
228
-                       ) . '" />';
229
-                break;
230
-
231
-            case 'phone':
232
-                return $this->_venue->get('VNU_phone');
233
-                break;
234
-
235
-            case 'address':
236
-                return $this->_venue->get('VNU_address');
237
-                break;
238
-
239
-            case 'address2':
240
-                return $this->_venue->get('VNU_address2');
241
-                break;
242
-
243
-            case 'city':
244
-                return $this->_venue->get('VNU_city');
245
-                break;
246
-
247
-            case 'state':
248
-                $state = $this->_venue->state_obj();
249
-                return is_object($state) ? $state->get('STA_name') : '';
250
-                break;
251
-
252
-            case 'country':
253
-                $country = $this->_venue->country_obj();
254
-                return is_object($country) ? $country->get('CNT_name') : '';
255
-                break;
256
-
257
-            case 'zip':
258
-                return $this->_venue->get('VNU_zip');
259
-                break;
260
-
261
-            case 'formatted_address':
262
-                return EEH_Address::format($this->_venue);
263
-                break;
264
-
265
-            case 'gmap_link':
266
-            case 'gmap_url':
267
-            case 'gmap_link_img':
268
-                $atts = $this->get_map_attributes($this->_venue, $field);
269
-                return EEH_Maps::google_map_link($atts);
270
-                break;
271
-        }
272
-        return '';
273
-    }
274
-
275
-
276
-    /**
277
-     * Generates the attributes for retrieving a google_map artifact.
278
-     * @param EE_Venue $venue
279
-     * @param string   $field
280
-     * @return array
281
-     * @throws EE_Error
282
-     */
283
-    protected function get_map_attributes(EE_Venue $venue, $field = 'gmap_link')
284
-    {
285
-        $state   = $venue->state_obj();
286
-        $country = $venue->country_obj();
287
-        $atts    = array(
288
-            'id'      => $venue->ID(),
289
-            'address' => $venue->get('VNU_address'),
290
-            'city'    => $venue->get('VNU_city'),
291
-            'state'   => is_object($state) ? $state->get('STA_name') : '',
292
-            'zip'     => $venue->get('VNU_zip'),
293
-            'country' => is_object($country) ? $country->get('CNT_name') : '',
294
-            'type'    => $field === 'gmap_link' ? 'url' : 'map',
295
-            'map_w'   => 200,
296
-            'map_h'   => 200,
297
-        );
298
-        if ($field === 'gmap_url') {
299
-            $atts['type'] = 'url_only';
300
-        }
301
-        return $atts;
302
-    }
19
+	/**
20
+	 * Will hold the EE_Event if available
21
+	 *
22
+	 * @var EE_Event
23
+	 */
24
+	protected $_event;
25
+
26
+	/**
27
+	 * Will hold the EE_Venue if available
28
+	 *
29
+	 * @var EE_Venue
30
+	 */
31
+	protected $_venue;
32
+
33
+
34
+	/**
35
+	 * Initialize properties
36
+	 */
37
+	protected function _init_props()
38
+	{
39
+		$this->label       = esc_html__('Venue Shortcodes', 'event_espresso');
40
+		$this->description = esc_html__('All shortcodes specific to venue related data', 'event_espresso');
41
+		$this->_shortcodes = array(
42
+			'[VENUE_TITLE]'             => esc_html__('The title for the event venue', 'event_espresso'),
43
+			'[VENUE_DESCRIPTION]'       => esc_html__('The description for the event venue', 'event_espresso'),
44
+			'[VENUE_URL]'               => esc_html__('A url to a webpage for the venue', 'event_espresso'),
45
+			'[VENUE_IMAGE]'             => esc_html__('An image representing the event venue', 'event_espresso'),
46
+			'[VENUE_PHONE]'             => esc_html__('The phone number for the venue', 'event_espresso'),
47
+			'[VENUE_ADDRESS]'           => esc_html__('The address for the venue', 'event_espresso'),
48
+			'[VENUE_ADDRESS2]'          => esc_html__('Address 2 for the venue', 'event_espresso'),
49
+			'[VENUE_CITY]'              => esc_html__('The city the venue is in', 'event_espresso'),
50
+			'[VENUE_STATE]'             => esc_html__('The state the venue is located in', 'event_espresso'),
51
+			'[VENUE_COUNTRY]'           => esc_html__('The country the venue is located in', 'event_espresso'),
52
+			'[VENUE_FORMATTED_ADDRESS]' => esc_html__(
53
+				'This just outputs the venue address in a semantic address format.',
54
+				'event_espresso'
55
+			),
56
+			'[VENUE_ZIP]'               => esc_html__('The zip code for the venue address', 'event_espresso'),
57
+			'[VENUE_META_*]'            => esc_html__(
58
+				'This is a special dynamic shortcode. After the "*", add the exact name for your custom field, if there is a value set for that custom field within the venue then it will be output in place of this shortcode.', 
59
+				'event_espresso'
60
+			),
61
+			'[GOOGLE_MAP_URL]'          => esc_html__(
62
+				'URL for the google map associated with the venue.', 
63
+				'event_espresso'
64
+			),
65
+			'[GOOGLE_MAP_LINK]'         => esc_html__('Link to a google map for the venue', 'event_espresso'),
66
+			'[GOOGLE_MAP_IMAGE]'        => esc_html__('Google map for venue wrapped in image tags', 'event_espresso'),
67
+		);
68
+	}
69
+
70
+
71
+	/**
72
+	 * Parse incoming shortcode
73
+	 * @param string $shortcode
74
+	 * @return string
75
+	 */
76
+	protected function _parser($shortcode)
77
+	{
78
+		$this->_venue = $this->_get_venue();
79
+		//If there is no venue object by now then get out.
80
+		if ( ! $this->_venue instanceof EE_Venue )
81
+			return '';
82
+
83
+		switch ($shortcode) {
84
+			case '[VENUE_TITLE]':
85
+				return $this->_venue('title');
86
+				break;
87
+
88
+			case '[VENUE_DESCRIPTION]':
89
+				return $this->_venue('description');
90
+				break;
91
+
92
+			case '[VENUE_URL]':
93
+				return $this->_venue('url');
94
+				break;
95
+
96
+			case '[VENUE_IMAGE]':
97
+				return $this->_venue('image');
98
+				break;
99
+
100
+			case '[VENUE_PHONE]':
101
+				return $this->_venue('phone');
102
+				break;
103
+
104
+			case '[VENUE_ADDRESS]':
105
+				return $this->_venue('address');
106
+				break;
107
+
108
+			case '[VENUE_ADDRESS2]':
109
+				return $this->_venue('address2');
110
+				break;
111
+
112
+			case '[VENUE_CITY]':
113
+				return $this->_venue('city');
114
+				break;
115
+
116
+			case '[VENUE_COUNTRY]':
117
+				return $this->_venue('country');
118
+				break;
119
+
120
+			case '[VENUE_STATE]':
121
+				return $this->_venue('state');
122
+				break;
123
+
124
+			case '[VENUE_ZIP]':
125
+				return $this->_venue('zip');
126
+				break;
127
+
128
+			case '[VENUE_FORMATTED_ADDRESS]':
129
+				return $this->_venue('formatted_address');
130
+				break;
131
+
132
+			case '[GOOGLE_MAP_URL]':
133
+				return $this->_venue('gmap_url');
134
+				break;
135
+
136
+			case '[GOOGLE_MAP_LINK]':
137
+				return $this->_venue('gmap_link');
138
+				break;
139
+
140
+			case '[GOOGLE_MAP_IMAGE]':
141
+				return $this->_venue('gmap_link_img');
142
+				break;
143
+
144
+		}
145
+
146
+		if ( strpos( $shortcode, '[VENUE_META_*' ) !== false ) {
147
+			$shortcode = str_replace( '[VENUE_META_*', '', $shortcode );
148
+			$shortcode = trim( str_replace( ']', '', $shortcode ) );
149
+
150
+			//pull the meta value from the venue post
151
+			$venue_meta = $this->_venue->get_post_meta( $shortcode, true );
152
+
153
+			return ! empty( $venue_meta ) ? $venue_meta : '';
154
+
155
+		}
156
+	}
157
+	/**
158
+	 * This retrieves the EE_Venue from the available data object.
159
+	 *
160
+	 * @return EE_Venue|null
161
+	 */
162
+	private function _get_venue() {
163
+
164
+		//we need the EE_Event object to get the venue.
165
+		$this->_event = $this->_data instanceof EE_Event ? $this->_data : null;
166
+
167
+		//if no event, then let's see if there is a reg_obj.  If there IS, then we'll try and grab the event from the reg_obj instead.
168
+		if (empty($this->_event)) {
169
+			$aee = $this->_data instanceof EE_Messages_Addressee ? $this->_data : null;
170
+			$aee = $this->_extra_data instanceof EE_Messages_Addressee ? $this->_extra_data : $aee;
171
+
172
+			$this->_event = $aee instanceof EE_Messages_Addressee && $aee->reg_obj instanceof EE_Registration ? $aee->reg_obj->event() : null;
173
+
174
+			//if still empty do we have a ticket data item?
175
+			$this->_event = empty($this->_event)
176
+							&& $this->_data instanceof EE_Ticket
177
+							&& $this->_extra_data['data'] instanceof EE_Messages_Addressee
178
+				? $this->_extra_data['data']->tickets[$this->_data->ID()]['EE_Event']
179
+				: $this->_event;
180
+
181
+			//if STILL empty event, let's try to get the first event in the list of events via EE_Messages_Addressee and use that.
182
+			$event        = $aee instanceof EE_Messages_Addressee ? reset($aee->events) : array();
183
+			$this->_event = empty($this->_event) && ! empty($events) ? $event : $this->_event;
184
+		}
185
+
186
+		//If we have an event object use it to pull the venue.
187
+		if ($this->_event instanceof EE_Event) {
188
+			return $this->_event->get_first_related('Venue');
189
+		} 
190
+
191
+		return null;
192
+	}
193
+
194
+	/**
195
+	 * This retrieves the specified venue information
196
+	 *
197
+	 * @param string $field  What Venue field to retrieve
198
+	 * @return string What was retrieved!
199
+	 * @throws EE_Error
200
+	 * @throws \EventEspresso\core\exceptions\EntityNotFoundException
201
+	 */
202
+	private function _venue($field)
203
+	{
204
+
205
+		if (empty($this->_venue)) {
206
+			return '';
207
+		} //no venue so get out.
208
+
209
+		switch ($field) {
210
+			case 'title':
211
+				return $this->_venue->get('VNU_name');
212
+				break;
213
+
214
+			case 'description':
215
+				return $this->_venue->get('VNU_desc');
216
+				break;
217
+
218
+			case 'url':
219
+				$url = $this->_venue->get('VNU_url');
220
+				return empty($url) ? $this->_venue->get_permalink() : $url;
221
+				break;
222
+
223
+			case 'image':
224
+				return '<img src="' . $this->_venue->feature_image_url(array(200, 200,))
225
+					   . '" alt="' . sprintf(
226
+						   esc_attr__('%s Feature Image', 'event_espresso'),
227
+						   $this->_venue->get('VNU_name')
228
+					   ) . '" />';
229
+				break;
230
+
231
+			case 'phone':
232
+				return $this->_venue->get('VNU_phone');
233
+				break;
234
+
235
+			case 'address':
236
+				return $this->_venue->get('VNU_address');
237
+				break;
238
+
239
+			case 'address2':
240
+				return $this->_venue->get('VNU_address2');
241
+				break;
242
+
243
+			case 'city':
244
+				return $this->_venue->get('VNU_city');
245
+				break;
246
+
247
+			case 'state':
248
+				$state = $this->_venue->state_obj();
249
+				return is_object($state) ? $state->get('STA_name') : '';
250
+				break;
251
+
252
+			case 'country':
253
+				$country = $this->_venue->country_obj();
254
+				return is_object($country) ? $country->get('CNT_name') : '';
255
+				break;
256
+
257
+			case 'zip':
258
+				return $this->_venue->get('VNU_zip');
259
+				break;
260
+
261
+			case 'formatted_address':
262
+				return EEH_Address::format($this->_venue);
263
+				break;
264
+
265
+			case 'gmap_link':
266
+			case 'gmap_url':
267
+			case 'gmap_link_img':
268
+				$atts = $this->get_map_attributes($this->_venue, $field);
269
+				return EEH_Maps::google_map_link($atts);
270
+				break;
271
+		}
272
+		return '';
273
+	}
274
+
275
+
276
+	/**
277
+	 * Generates the attributes for retrieving a google_map artifact.
278
+	 * @param EE_Venue $venue
279
+	 * @param string   $field
280
+	 * @return array
281
+	 * @throws EE_Error
282
+	 */
283
+	protected function get_map_attributes(EE_Venue $venue, $field = 'gmap_link')
284
+	{
285
+		$state   = $venue->state_obj();
286
+		$country = $venue->country_obj();
287
+		$atts    = array(
288
+			'id'      => $venue->ID(),
289
+			'address' => $venue->get('VNU_address'),
290
+			'city'    => $venue->get('VNU_city'),
291
+			'state'   => is_object($state) ? $state->get('STA_name') : '',
292
+			'zip'     => $venue->get('VNU_zip'),
293
+			'country' => is_object($country) ? $country->get('CNT_name') : '',
294
+			'type'    => $field === 'gmap_link' ? 'url' : 'map',
295
+			'map_w'   => 200,
296
+			'map_h'   => 200,
297
+		);
298
+		if ($field === 'gmap_url') {
299
+			$atts['type'] = 'url_only';
300
+		}
301
+		return $atts;
302
+	}
303 303
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
     {
78 78
         $this->_venue = $this->_get_venue();
79 79
         //If there is no venue object by now then get out.
80
-        if ( ! $this->_venue instanceof EE_Venue )
80
+        if ( ! $this->_venue instanceof EE_Venue)
81 81
             return '';
82 82
 
83 83
         switch ($shortcode) {
@@ -143,14 +143,14 @@  discard block
 block discarded – undo
143 143
 
144 144
         }
145 145
 
146
-        if ( strpos( $shortcode, '[VENUE_META_*' ) !== false ) {
147
-            $shortcode = str_replace( '[VENUE_META_*', '', $shortcode );
148
-            $shortcode = trim( str_replace( ']', '', $shortcode ) );
146
+        if (strpos($shortcode, '[VENUE_META_*') !== false) {
147
+            $shortcode = str_replace('[VENUE_META_*', '', $shortcode);
148
+            $shortcode = trim(str_replace(']', '', $shortcode));
149 149
 
150 150
             //pull the meta value from the venue post
151
-            $venue_meta = $this->_venue->get_post_meta( $shortcode, true );
151
+            $venue_meta = $this->_venue->get_post_meta($shortcode, true);
152 152
 
153
-            return ! empty( $venue_meta ) ? $venue_meta : '';
153
+            return ! empty($venue_meta) ? $venue_meta : '';
154 154
 
155 155
         }
156 156
     }
@@ -221,11 +221,11 @@  discard block
 block discarded – undo
221 221
                 break;
222 222
 
223 223
             case 'image':
224
-                return '<img src="' . $this->_venue->feature_image_url(array(200, 200,))
225
-                       . '" alt="' . sprintf(
224
+                return '<img src="'.$this->_venue->feature_image_url(array(200, 200,))
225
+                       . '" alt="'.sprintf(
226 226
                            esc_attr__('%s Feature Image', 'event_espresso'),
227 227
                            $this->_venue->get('VNU_name')
228
-                       ) . '" />';
228
+                       ).'" />';
229 229
                 break;
230 230
 
231 231
             case 'phone':
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -77,8 +77,9 @@
 block discarded – undo
77 77
     {
78 78
         $this->_venue = $this->_get_venue();
79 79
         //If there is no venue object by now then get out.
80
-        if ( ! $this->_venue instanceof EE_Venue )
81
-            return '';
80
+        if ( ! $this->_venue instanceof EE_Venue ) {
81
+                    return '';
82
+        }
82 83
 
83 84
         switch ($shortcode) {
84 85
             case '[VENUE_TITLE]':
Please login to merge, or discard this patch.