Completed
Branch FET-9222-rest-api-writes (8a2732)
by
unknown
55:53 queued 45:02
created

EED_Messages::preview_message()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 3
nop 4
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
1
<?php
2
defined('EVENT_ESPRESSO_VERSION') || exit('No direct access allowed.');
3
4
/**
5
 * Messages module.  Takes care of registering all the triggers for messages.
6
 *
7
 * @since          4.5.0
8
 * @package        Event Espresso
9
 * @subpackage     modules, messages
10
 * @author         Darren Ethier
11
 * ------------------------------------------------------------------------
12
 */
13
class EED_Messages extends EED_Module
14
{
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
                ?>
176
                <!DOCTYPE html>
177
                <html>
178
                <head></head>
179
                <body>
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
                    ); ?>
198
                </body>
199
                </html>
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');
0 ignored issues
show
Deprecated Code introduced by
The property EED_Messages::$_EEMSG has been deprecated with message: 4.9.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
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) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $messages of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
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) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $messages of type EE_Base_Class[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
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 View Code Duplication
            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
					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 View Code Duplication
            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 View Code Duplication
    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;
0 ignored issues
show
Deprecated Code introduced by
The property EED_Messages::$_EEMSG has been deprecated with message: 4.9.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1100
        self::$_message_resource_manager = null;
1101
        self::$_MSG_PROCESSOR            = null;
1102
        self::$_MSG_PATHS                = null;
1103
        self::$_TMP_PACKS                = array();
1104
    }
1105
1106
}
1107
// End of file EED_Messages.module.php
1108
// Location: /modules/messages/EED_Messages.module.php
1109