Completed
Branch master (19a9be)
by
unknown
08:32
created

EE_Messages_Scheduler::cleanup()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 9
nop 0
dl 0
loc 30
rs 8.8177
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This class is used for setting scheduled tasks related to the EE_messages system.
5
 *
6
 * @package    Event Espresso
7
 * @subpackage messages
8
 * @author     Darren Ethier
9
 * @since      4.9.0
10
 */
11
class EE_Messages_Scheduler extends EE_Base
12
{
13
14
    /**
15
     * Number of seconds between batch sends/generates on the cron job.
16
     * Defaults to 5 minutes in seconds.  If you want to change this interval, you can use the native WordPress
17
     * `cron_schedules` filter and modify the existing custom `ee_message_cron` schedule interval added.
18
     *
19
     * @type int
20
     */
21
    const message_cron_schedule = 300;
22
23
    /**
24
     * Constructor
25
     */
26
    public function __construct()
27
    {
28
        // register tasks (and make sure only registered once).
29
        if (! has_action('FHEE__EEH_Activation__get_cron_tasks', array($this, 'register_scheduled_tasks'))) {
30
            add_action('FHEE__EEH_Activation__get_cron_tasks', array($this, 'register_scheduled_tasks'), 10);
31
        }
32
33
        // register callbacks for scheduled events (but make sure they are set only once).
34
        if (! has_action(
35
            'AHEE__EE_Messages_Scheduler__generation',
36
            array('EE_Messages_Scheduler', 'batch_generation')
37
        )) {
38
            add_action('AHEE__EE_Messages_Scheduler__generation', array('EE_Messages_Scheduler', 'batch_generation'));
39
            add_action('AHEE__EE_Messages_Scheduler__sending', array('EE_Messages_Scheduler', 'batch_sending'));
40
            add_action('AHEE__EE_Messages_Scheduler__cleanup', array('EE_Messages_Scheduler', 'cleanup'));
41
        }
42
43
        // add custom schedules
44
        add_filter('cron_schedules', array($this, 'custom_schedules'));
45
    }
46
47
48
    /**
49
     * Add custom schedules for wp_cron
50
     *
51
     * @param $schedules
52
     */
53
    public function custom_schedules($schedules)
54
    {
55
        $schedules['ee_message_cron'] = array(
56
            'interval' => self::message_cron_schedule,
57
            'display'  => __(
58
                'This is the cron time interval for EE Message schedules (defaults to once every 5 minutes)',
59
                'event_espresso'
60
            ),
61
        );
62
        return $schedules;
63
    }
64
65
66
    /**
67
     * Callback for FHEE__EEH_Activation__get_cron_tasks that is used to retrieve scheduled Cron events to add and
68
     * remove.
69
     *
70
     * @param array $tasks already existing scheduled tasks
71
     * @return array
72
     */
73
    public function register_scheduled_tasks($tasks)
74
    {
75
        EE_Registry::instance()->load_helper('DTT_Helper');
76
        $tasks['AHEE__EE_Messages_Scheduler__generation'] = 'ee_message_cron';
77
        $tasks['AHEE__EE_Messages_Scheduler__sending']    = 'ee_message_cron';
78
        $tasks['AHEE__EE_Messages_Scheduler__cleanup'] = array( EEH_DTT_Helper::tomorrow(), 'daily');
79
        return $tasks;
80
    }
81
82
83
    /**
84
     * This initiates a non-blocking separate request to execute on a scheduled task.
85
     * Note: The EED_Messages module has the handlers for these requests.
86
     *
87
     * @param string $task The task the request is being generated for.
88
     */
89
    public static function initiate_scheduled_non_blocking_request($task)
90
    {
91
        if (apply_filters(
92
            'EE_Messages_Scheduler__initiate_scheduled_non_blocking_request__do_separate_request',
93
            true
94
        )) {
95
            $request_url  = add_query_arg(
96
                array_merge(
97
                    array('ee' => 'msg_cron_trigger'),
98
                    EE_Messages_Scheduler::get_request_params($task)
99
                ),
100
                site_url()
101
            );
102
            $request_args = array(
103
                'timeout'     => 300,
104
                'blocking'    => (defined('DOING_CRON') && DOING_CRON) || (defined('DOING_AJAX') && DOING_AJAX) ? true : false,
105
                'sslverify'   => false,
106
                'redirection' => 10,
107
            );
108
            $response     = wp_remote_get($request_url, $request_args);
109
            if (is_wp_error($response)) {
110
                trigger_error($response->get_error_message());
111
            }
112
        } else {
113
            EE_Messages_Scheduler::initiate_immediate_request_on_cron($task);
114
        }
115
    }
116
117
118
    /**
119
     * This returns
120
     * the request params used for a scheduled message task request.
121
     *
122
     * @param string $task The task the request is for.
123
     * @return array
124
     */
125
    public static function get_request_params($task)
126
    {
127
        // transient is used for flood control on msg_cron_trigger requests
128
        $transient_key = 'ee_trans_' . uniqid($task);
129
        set_transient($transient_key, 1, 5 * MINUTE_IN_SECONDS);
130
        return array(
131
            'type' => $task,
132
            'key'  => $transient_key,
133
        );
134
    }
135
136
137
    /**
138
     * This is used to execute an immediate call to the run_cron task performed by EED_Messages
139
     *
140
     * @param string $task The task the request is being generated for.
141
     */
142
    public static function initiate_immediate_request_on_cron($task)
143
    {
144
        $request_args = EE_Messages_Scheduler::get_request_params($task);
145
        // set those request args in the request so it gets picked up
146
        foreach ($request_args as $request_key => $request_value) {
147
            EE_Registry::instance()->REQ->set($request_key, $request_value);
148
        }
149
        EED_Messages::instance()->run_cron();
150
    }
151
152
153
    /**
154
     * Callback for scheduled AHEE__EE_Messages_Scheduler__generation wp cron event
155
     */
156 View Code Duplication
    public static function batch_generation()
157
    {
158
        /**
159
         * @see filter usage in EE_Messages_Queue::initiate_request_by_priority()
160
         */
161
        if (! apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
162
            || ! EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
163
        ) {
164
            EE_Messages_Scheduler::initiate_immediate_request_on_cron('generate');
165
        }
166
    }
167
168
169
    /**
170
     * Callback for scheduled AHEE__EE_Messages_Scheduler__sending
171
     */
172 View Code Duplication
    public static function batch_sending()
173
    {
174
        /**
175
         * @see filter usage in EE_Messages_Queue::initiate_request_by_priority()
176
         */
177
        if (! apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
178
            || ! EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
179
        ) {
180
            EE_Messages_Scheduler::initiate_immediate_request_on_cron('send');
181
        }
182
    }
183
184
185
    /**
186
     * This is the callback for the `AHEE__EE_Messages_Scheduler__cleanup` scheduled event action.
187
     * This runs once a day and if cleanup is active (set via messages settings), it will (by default) delete permanently
188
     * from the database messages that have a MSG_modified date older than 30 days.
189
     */
190
    public static function cleanup()
191
    {
192
        // First, confirm that the generation and sending EE_Messages_Scheduler crons are
193
        // set and reschedule them if they are not.
194
        $message_crons_to_check = array(
195
            'AHEE__EE_Messages_Scheduler__generation' => 'ee_message_cron',
196
            'AHEE__EE_Messages_Scheduler__sending'    => 'ee_message_cron',
197
        );
198
        foreach ($message_crons_to_check as $hook_name => $frequency) {
199
            if (! wp_next_scheduled($hook_name)) {
200
                wp_schedule_event(time(), $frequency, $hook_name);
201
            }
202
        }
203
204
        // check if user has cleanup turned on or if we're in maintenance mode.  If in maintenance mode we'll wait
205
        // until the next scheduled event.
206
        if (! EE_Registry::instance()->CFG->messages->delete_threshold
207
            || ! EE_Maintenance_Mode::instance()->models_can_query()
208
        ) {
209
            return;
210
        }
211
212
        /**
213
         * This filter switch allows other code (such as the EE_Worker_Queue add-on) to replace this with its own handling
214
         * of deleting messages.
215
         */
216
        if (apply_filters('FHEE__EE_Messages_Scheduler__cleanup__handle_cleanup_on_cron', true)) {
217
            EEM_Message::instance()->delete_old_messages(EE_Registry::instance()->CFG->messages->delete_threshold);
218
        }
219
    }
220
}
221