Completed
Branch FET-10724-event-editor-cleanup (955656)
by
unknown
149:38 queued 136:37
created

EED_Messages::process_resend()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 18
nc 9
nop 1
dl 0
loc 31
rs 8.439
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            = $mtgs + self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers($message_type,
472
                    array($registration->transaction(), null, $reg->status_ID()));
473
            $statuses_sent[] = $reg->status_ID();
474
        }
475
476
        $mtgs = $mtgs + self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers('registration_summary',
477
                array($registration->transaction(), null));
478
479
        //batch queue and initiate request
480
        self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
481
        self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
482
    }
483
484
485
    /**
486
     * This is a helper method used to very whether a registration notification should be sent or
487
     * not.  Prevents duplicate notifications going out for registration context notifications.
488
     *
489
     * @param EE_Registration $registration  [description]
490
     * @param array           $extra_details [description]
491
     * @return bool          true = send away, false = nope halt the presses.
492
     */
493
    protected static function _verify_registration_notification_send(
494
        EE_Registration $registration,
495
        $extra_details = array()
496
    ) {
497
        //self::log(
498
        //	__CLASS__, __FUNCTION__, __LINE__,
499
        //	$registration->transaction(),
500
        //	array( '$extra_details' => $extra_details )
501
        //);
502
        // currently only using this to send messages for the primary registrant
503
        if (! $registration->is_primary_registrant()) {
504
            return false;
505
        }
506
        // first we check if we're in admin and not doing front ajax
507
        if (is_admin() && ! EE_FRONT_AJAX) {
508
            //make sure appropriate admin params are set for sending messages
509
            if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
510
                //no messages sent please.
511
                return false;
512
            }
513
        } else {
514
            // frontend request (either regular or via AJAX)
515
            // TXN is NOT finalized ?
516
            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
517
                return false;
518
            }
519
            // return visit but nothing changed ???
520
            if (
521
                isset($extra_details['revisit'], $extra_details['status_updates']) &&
522
                $extra_details['revisit'] && ! $extra_details['status_updates']
523
            ) {
524
                return false;
525
            }
526
            // NOT sending messages && reg status is something other than "Not-Approved"
527
            if (
528
                ! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
529
                $registration->status_ID() !== EEM_Registration::status_id_not_approved
530
            ) {
531
                return false;
532
            }
533
        }
534
        // release the kraken
535
        return true;
536
    }
537
538
539
    /**
540
     * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
541
     * status id.
542
     *
543
     * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
544
     *                    or EEH_MSG_Template::convert_reg_status_to_message_type
545
     * @param string $reg_status
546
     * @return array
547
     */
548
    protected static function _get_reg_status_array($reg_status = '')
549
    {
550
        EE_Registry::instance()->load_helper('MSG_Template');
551
        return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
552
            ? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
553
            : EEH_MSG_Template::reg_status_to_message_type_array();
554
    }
555
556
557
    /**
558
     * Simply returns the payment message type for the given payment status.
559
     *
560
     * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
561
     *                   or EEH_MSG_Template::convert_payment_status_to_message_type
562
     * @param string $payment_status The payment status being matched.
563
     * @return string|bool The payment message type slug matching the status or false if no match.
564
     */
565
    protected static function _get_payment_message_type($payment_status)
566
    {
567
        EE_Registry::instance()->load_helper('MSG_Template');
568
        return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
569
            ? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
570
            : false;
571
    }
572
573
574
    /**
575
     * Message triggers for a resending already sent message(s) (via EE_Message list table)
576
     *
577
     * @access public
578
     * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
579
     * @return bool          success/fail
580
     */
581
    public static function process_resend($req_data)
582
    {
583
        self::_load_controller();
584
585
        //if $msgID in this request then skip to the new resend_message
586
        if (EE_Registry::instance()->REQ->get('MSG_ID')) {
587
            return self::resend_message();
588
        }
589
590
        //make sure any incoming request data is set on the REQ so that it gets picked up later.
591
        $req_data = (array)$req_data;
592
        foreach ($req_data as $request_key => $request_value) {
593
            EE_Registry::instance()->REQ->set($request_key, $request_value);
594
        }
595
596
        if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
597
            return false;
598
        }
599
600
        try {
601
            self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
602
            self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
603
        } catch (EE_Error $e) {
604
            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
605
            return false;
606
        }
607
        EE_Error::add_success(
608
            __('Messages have been successfully queued for generation and sending.', 'event_espresso')
609
        );
610
        return true; //everything got queued.
611
    }
612
613
614
    /**
615
     * Message triggers for a resending already sent message(s) (via EE_Message list table)
616
     *
617
     * @return bool
618
     */
619
    public static function resend_message()
620
    {
621
        self::_load_controller();
622
623
        $msgID = EE_Registry::instance()->REQ->get('MSG_ID');
624
        if (! $msgID) {
625
            EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
626
                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
627
            return false;
628
        }
629
630
        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
631
632
        //setup success message.
633
        $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
634
        EE_Error::add_success(sprintf(
635
            _n(
636
                'There was %d message queued for resending.',
637
                'There were %d messages queued for resending.',
638
                $count_ready_for_resend,
639
                'event_espresso'
640
            ),
641
            $count_ready_for_resend
642
        ));
643
        return true;
644
    }
645
646
647
    /**
648
     * Message triggers for manual payment applied by admin
649
     *
650
     * @param  EE_Payment $payment EE_payment object
651
     * @return bool              success/fail
652
     */
653
    public static function process_admin_payment(EE_Payment $payment)
654
    {
655
        EE_Registry::instance()->load_helper('MSG_Template');
656
        //we need to get the transaction object
657
        $transaction = $payment->transaction();
658
        if ($transaction instanceof EE_Transaction) {
659
            $data         = array($transaction, $payment);
660
            $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
661
662
            //if payment amount is less than 0 then switch to payment_refund message type.
663
            $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
664
665
            //if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
666
            $message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
667
668
            self::_load_controller();
669
670
            self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
671
672
            //get count of queued for generation
673
            $count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
674
                EEM_Message::status_incomplete,
675
                EEM_Message::status_idle,
676
            ));
677
678
            if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
679
                add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
680
                return true;
681
            } else {
682
                $count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
683
                /**
684
                 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
685
                 * IMMEDIATE generation.
686
                 */
687
                if ($count_failed > 0) {
688
                    EE_Error::add_error(sprintf(
689
                        _n(
690
                            'The payment notification generation failed.',
691
                            '%d payment notifications failed being sent.',
692
                            $count_failed,
693
                            'event_espresso'
694
                        ),
695
                        $count_failed
696
                    ), __FILE__, __FUNCTION__, __LINE__);
697
698
                    return false;
699
                } else {
700
                    add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
701
                    return true;
702
                }
703
            }
704
        } else {
705
            EE_Error::add_error(
706
                'Unable to generate the payment notification because the given value for the transaction is invalid.',
707
                'event_espresso'
708
            );
709
            return false;
710
        }
711
    }
712
713
714
    /**
715
     * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
716
     *
717
     * @since   4.3.0
718
     * @param  EE_Registration[] $registrations an array of EE_Registration objects
719
     * @param  int               $grp_id        a specific message template group id.
720
     * @return void
721
     */
722
    public static function send_newsletter_message($registrations, $grp_id)
723
    {
724
        //make sure mtp is id and set it in the EE_Request Handler later messages setup.
725
        EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
726
        self::_load_controller();
727
        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
728
    }
729
730
731
    /**
732
     * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
733
     *
734
     * @since   4.3.0
735
     * @param    string          $registration_message_trigger_url
736
     * @param    EE_Registration $registration
737
     * @param string             $messenger
738
     * @param string             $message_type
739
     * @return    string
740
     */
741
    public static function registration_message_trigger_url(
742
        $registration_message_trigger_url,
743
        EE_Registration $registration,
744
        $messenger = 'html',
745
        $message_type = 'invoice'
746
    ) {
747
        // whitelist $messenger
748
        switch ($messenger) {
749
            case 'pdf' :
750
                $sending_messenger    = 'pdf';
751
                $generating_messenger = 'html';
752
                break;
753
            case 'html' :
754
            default :
755
                $sending_messenger    = 'html';
756
                $generating_messenger = 'html';
757
                break;
758
        }
759
        // whitelist $message_type
760
        switch ($message_type) {
761
            case 'receipt' :
762
                $message_type = 'receipt';
763
                break;
764
            case 'invoice' :
765
            default :
766
                $message_type = 'invoice';
767
                break;
768
        }
769
        // verify that both the messenger AND the message type are active
770
        if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
771
            //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?)
772
            $template_query_params = array(
773
                'MTP_is_active'    => true,
774
                'MTP_messenger'    => $generating_messenger,
775
                'MTP_message_type' => $message_type,
776
                'Event.EVT_ID'     => $registration->event_ID(),
777
            );
778
            //get the message template group.
779
            $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
780
            //if we don't have an EE_Message_Template_Group then return
781
            if (! $msg_template_group instanceof EE_Message_Template_Group) {
782
                // remove EVT_ID from query params so that global templates get picked up
783
                unset($template_query_params['Event.EVT_ID']);
784
                //get global template as the fallback
785
                $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
786
            }
787
            //if we don't have an EE_Message_Template_Group then return
788
            if (! $msg_template_group instanceof EE_Message_Template_Group) {
789
                return '';
790
            }
791
            // generate the URL
792
            $registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
793
                $sending_messenger,
794
                $generating_messenger,
795
                'purchaser',
796
                $message_type,
797
                $registration,
798
                $msg_template_group->ID(),
799
                $registration->transaction_ID()
800
            );
801
802
        }
803
        return $registration_message_trigger_url;
804
    }
805
806
807
    /**
808
     * Use to generate and return a message preview!
809
     *
810
     * @param  string $type      This should correspond with a valid message type
811
     * @param  string $context   This should correspond with a valid context for the message type
812
     * @param  string $messenger This should correspond with a valid messenger.
813
     * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
814
     *                           preview
815
     * @return string|bool          The body of the message or if send is requested, sends.
816
     */
817
    public static function preview_message($type, $context, $messenger, $send = false)
818
    {
819
        self::_load_controller();
820
        $mtg                     = new EE_Message_To_Generate(
821
            $messenger,
822
            $type,
823
            array(),
824
            $context,
825
            true
826
        );
827
        $generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
828
        if ($generated_preview_queue instanceof EE_Messages_Queue) {
829
            return $generated_preview_queue->get_message_repository()->current()->content();
830
        } else {
831
            return $generated_preview_queue;
832
        }
833
    }
834
835
836
    /**
837
     * This is a method that allows for sending a message using a messenger matching the string given and the provided
838
     * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
839
     * content found in the EE_Message objects in the queue.
840
     *
841
     * @since 4.9.0
842
     * @param string            $messenger            a string matching a valid active messenger in the system
843
     * @param string            $message_type         Although it seems contrary to the name of the method, a message
844
     *                                                type name is still required to send along the message type to the
845
     *                                                messenger because this is used for determining what specific
846
     *                                                variations might be loaded for the generated message.
847
     * @param EE_Messages_Queue $queue
848
     * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
849
     *                                                aggregate EE_Message object.
850
     * @return bool          success or fail.
851
     */
852
    public static function send_message_with_messenger_only(
853
        $messenger,
854
        $message_type,
855
        EE_Messages_Queue $queue,
856
        $custom_subject = ''
857
    ) {
858
        self::_load_controller();
859
        /** @type EE_Message_To_Generate_From_Queue $message_to_generate */
860
        $message_to_generate = EE_Registry::instance()->load_lib(
861
            'Message_To_Generate_From_Queue',
862
            array(
863
                $messenger,
864
                $message_type,
865
                $queue,
866
                $custom_subject,
867
            )
868
        );
869
        return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
870
    }
871
872
873
    /**
874
     * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
875
     *
876
     * @since 4.9.0
877
     * @param array $message_ids An array of message ids
878
     * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
879
     *              messages.
880
     */
881
    public static function generate_now($message_ids)
882
    {
883
        self::_load_controller();
884
        $messages        = EEM_Message::instance()->get_all(
885
            array(
886
                0 => array(
887
                    'MSG_ID' => array('IN', $message_ids),
888
                    'STS_ID' => EEM_Message::status_incomplete,
889
                ),
890
            )
891
        );
892
        $generated_queue = false;
893
        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...
894
            $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
895
        }
896
897
        if (! $generated_queue instanceof EE_Messages_Queue) {
898
            EE_Error::add_error(
899
                __('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.',
900
                    'event_espresso'),
901
                __FILE__, __FUNCTION__, __LINE__
902
            );
903
        }
904
        return $generated_queue;
905
    }
906
907
908
    /**
909
     * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
910
     * EEM_Message::status_idle
911
     *
912
     * @since 4.9.0
913
     * @param $message_ids
914
     * @return bool | EE_Messages_Queue  false if no messages sent.
915
     */
916
    public static function send_now($message_ids)
917
    {
918
        self::_load_controller();
919
        $messages   = EEM_Message::instance()->get_all(
920
            array(
921
                0 => array(
922
                    'MSG_ID' => array('IN', $message_ids),
923
                    'STS_ID' => array(
924
                        'IN',
925
                        array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
926
                    ),
927
                ),
928
            )
929
        );
930
        $sent_queue = false;
931
        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...
932
            $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
933
        }
934
935
        if (! $sent_queue instanceof EE_Messages_Queue) {
936
            EE_Error::add_error(
937
                __('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.',
938
                    'event_espresso'),
939
                __FILE__, __FUNCTION__, __LINE__
940
            );
941
        } else {
942
            //can count how many sent by using the messages in the queue
943
            $sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
944 View Code Duplication
            if ($sent_count > 0) {
945
                EE_Error::add_success(
946
                    sprintf(
947
                        _n(
948
                            'There was %d message successfully sent.',
949
                            'There were %d messages successfully sent.',
950
                            $sent_count,
951
                            'event_espresso'
952
                        ),
953
                        $sent_count
954
                    )
955
                );
956
            } else {
957
                EE_Error::overwrite_errors();
958
                EE_Error::add_error(
959
                    __('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.
960
					If there was an error, you can look at the messages in the message activity list table for any error messages.',
961
                        'event_espresso'),
962
                    __FILE__, __FUNCTION__, __LINE__
963
                );
964
            }
965
        }
966
        return $sent_queue;
967
    }
968
969
970
    /**
971
     * This will queue the incoming message ids for resending.
972
     * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
973
     *
974
     * @since 4.9.0
975
     * @param array $message_ids An array of EE_Message IDs
976
     * @return bool  true means messages were successfully queued for resending, false means none were queued for
977
     *               resending.
978
     */
979
    public static function queue_for_resending($message_ids)
980
    {
981
        self::_load_controller();
982
        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
983
984
        //get queue and count
985
        $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
986
987
        if (
988
            $queue_count > 0
989
        ) {
990
            EE_Error::add_success(
991
                sprintf(
992
                    _n(
993
                        '%d message successfully queued for resending.',
994
                        '%d messages successfully queued for resending.',
995
                        $queue_count,
996
                        'event_espresso'
997
                    ),
998
                    $queue_count
999
                )
1000
            );
1001
            /**
1002
             * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1003
             */
1004
        } elseif (
1005
            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1006
            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1007
        ) {
1008
            $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1009 View Code Duplication
            if ($queue_count > 0) {
1010
                EE_Error::add_success(
1011
                    sprintf(
1012
                        _n(
1013
                            '%d message successfully sent.',
1014
                            '%d messages successfully sent.',
1015
                            $queue_count,
1016
                            'event_espresso'
1017
                        ),
1018
                        $queue_count
1019
                    )
1020
                );
1021
            } else {
1022
                EE_Error::add_error(
1023
                    __('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.',
1024
                        'event_espresso'),
1025
                    __FILE__, __FUNCTION__, __LINE__
1026
                );
1027
            }
1028
        } else {
1029
            EE_Error::add_error(
1030
                __('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.',
1031
                    'event_espresso'),
1032
                __FILE__, __FUNCTION__, __LINE__
1033
            );
1034
        }
1035
        return (bool)$queue_count;
1036
    }
1037
1038
1039
    /**
1040
     * debug
1041
     *
1042
     * @param string          $class
1043
     * @param string          $func
1044
     * @param string          $line
1045
     * @param \EE_Transaction $transaction
1046
     * @param array           $info
1047
     * @param bool            $display_request
1048
     */
1049 View Code Duplication
    protected static function log(
1050
        $class = '',
1051
        $func = '',
1052
        $line = '',
1053
        EE_Transaction $transaction,
1054
        $info = array(),
1055
        $display_request = false
1056
    ) {
1057
        if (WP_DEBUG && false) {
1058
            if ($transaction instanceof EE_Transaction) {
1059
                // don't serialize objects
1060
                $info                  = EEH_Debug_Tools::strip_objects($info);
1061
                $info['TXN_status']    = $transaction->status_ID();
1062
                $info['TXN_reg_steps'] = $transaction->reg_steps();
1063
                if ($transaction->ID()) {
1064
                    $index = 'EE_Transaction: ' . $transaction->ID();
1065
                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1066
                }
1067
            }
1068
        }
1069
1070
    }
1071
1072
1073
    /**
1074
     *  Resets all the static properties in this class when called.
1075
     */
1076
    public static function reset()
1077
    {
1078
        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...
1079
        self::$_message_resource_manager = null;
1080
        self::$_MSG_PROCESSOR            = null;
1081
        self::$_MSG_PATHS                = null;
1082
        self::$_TMP_PACKS                = array();
1083
    }
1084
1085
}
1086
// End of file EED_Messages.module.php
1087
// Location: /modules/messages/EED_Messages.module.php
1088