Completed
Branch BUG-9951-10331-8793-pue-fixes (40e696)
by
unknown
27:52 queued 13:57
created

EEM_Message::delete_old_messages()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 63
Code Lines 25

Duplication

Lines 9
Ratio 14.29 %

Importance

Changes 0
Metric Value
cc 4
eloc 25
nc 4
nop 1
dl 9
loc 63
rs 8.8945
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
    exit('No direct script access allowed');
3
}
4
5
/**
6
 * Message Model
7
 *
8
 * @package            Event Espresso
9
 * @subpackage         models
10
 * @author             Darren Ethier
11
 */
12
class EEM_Message extends EEM_Base implements EEI_Query_Filter
13
{
14
15
    // private instance of the Message object
16
    protected static $_instance = null;
17
18
19
    /**
20
     * This priority indicates a message should be generated and sent ASAP
21
     *
22
     * @type int
23
     */
24
    const priority_high = 10;
25
26
27
    /**
28
     * This priority indicates a message should be generated ASAP and queued for sending.
29
     *
30
     * @type
31
     */
32
    const priority_medium = 20;
33
34
35
    /**
36
     * This priority indicates a message should be queued for generating.
37
     *
38
     * @type int
39
     */
40
    const priority_low = 30;
41
42
43
    /**
44
     * indicates this message was sent at the time modified
45
     */
46
    const status_sent = 'MSN';
47
48
49
    /**
50
     * indicates this message is waiting to be sent
51
     */
52
    const status_idle = 'MID';
53
54
55
    /**
56
     * indicates an attempt was a made to send this message
57
     * at the scheduled time, but it failed at the time modified.  This differs from MDO status in that it will ALWAYS
58
     * appear to the end user.
59
     */
60
    const status_failed = 'MFL';
61
62
63
    /**
64
     * indicates the message has been flagged for resending (at the time modified).
65
     */
66
    const status_resend = 'MRS';
67
68
69
    /**
70
     * indicates the message has been flagged for generation but has not been generated yet.  Messages always start as
71
     * this status when added to the queue.
72
     */
73
    const status_incomplete = 'MIC';
74
75
76
    /**
77
     * Indicates everything was generated fine for the message, however, the messenger was unable to send.
78
     * This status means that its possible to retry sending the message.
79
     */
80
    const status_retry = 'MRT';
81
82
83
    /**
84
     * This is used for more informational messages that may not indicate anything is broken but still cannot be
85
     * generated or sent correctly. An example of a message that would get flagged this way would be when a not
86
     * approved message was queued for generation, but at time of generation, the attached registration(s) are
87
     * approved. So the message queued for generation is no longer valid.  Messages for this status will only persist
88
     * in the db and be viewable in the message activity list table when the messages system is in debug mode.
89
     *
90
     * @see EEM_Message::debug()
91
     */
92
    const status_debug_only = 'MDO';
93
94
95
    /**
96
     * This status is given to messages it is processed by the messenger send method.
97
     * Messages with this status should rarely be seen in the Message List table, but if they are, that's usually
98
     * indicative of a PHP timeout or memory limit issue.
99
     */
100
    const status_messenger_executing = 'MEX';
101
102
103
    /**
104
     *    Private constructor to prevent direct creation.
105
     *
106
     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and
107
     *                         any incoming timezone data that gets saved).  Note this just sends the timezone info to
108
     *                         the date time model field objects.  Default is null (and will be assumed using the set
109
     *                         timezone in the 'timezone_string' wp option)
110
     * @return EEM_Message
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
111
     */
112
    protected function __construct($timezone = null)
113
    {
114
        $this->singular_item = __('Message', 'event_espresso');
115
        $this->plural_item   = __('Messages', 'event_espresso');
116
117
        //used for token generator
118
        EE_Registry::instance()->load_helper('URL');
119
120
        $this->_tables = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Message' => new \...sp_message', 'MSG_ID')) of type array<string,object<EE_P...ct<EE_Primary_Table>"}> is incompatible with the declared type array<integer,object<EE_Table_Base>> of property $_tables.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
121
            'Message' => new EE_Primary_Table('esp_message', 'MSG_ID'),
122
        );
123
124
        $allowed_priority = array(
125
            self::priority_high   => __('high', 'event_espresso'),
126
            self::priority_medium => __('medium', 'event_espresso'),
127
            self::priority_low    => __('low', 'event_espresso'),
128
        );
129
130
        $this->_fields          = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Message' => array..._Datetime_Field::now))) of type array<string,array<strin..._Datetime_Field>\"}>"}> is incompatible with the declared type array<integer,object<EE_Model_Field_Base>> of property $_fields.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
131
            'Message' => array(
132
                'MSG_ID'             => new EE_Primary_Key_Int_Field('MSG_ID', __('Message ID', 'event_espresso')),
133
                'MSG_token'          => new EE_Plain_Text_Field('MSG_token',
134
                    __('Unique Token used to represent this row in publicly viewable contexts (eg. a url).',
135
                        'event_espresso'), false, EEH_URL::generate_unique_token()),
136
                'GRP_ID'             => new EE_Foreign_Key_Int_Field('GRP_ID',
137
                    __('Foreign key to the EEM_Message_Template_Group table.', 'event_espresso'), true, 0,
138
                    'Message_Template_Group'),
139
                'TXN_ID'             => new EE_Foreign_Key_Int_Field('TXN_ID',
140
                    __('Foreign key to the related EE_Transaction.  This is required to give context for regenerating the specific message',
141
                        'event_espresso'), true, 0, 'Transaction'),
142
                'MSG_messenger'      => new EE_Plain_Text_Field('MSG_messenger',
143
                    __('Corresponds to the EE_messenger::name used to send this message. This will also be used to attempt any resending of the message.',
144
                        'event_espresso'), false, 'email'),
145
                'MSG_message_type'   => new EE_Plain_Text_Field('MSG_message_type',
146
                    __('Corresponds to the EE_message_type::name used to generate this message.', 'event_espresso'),
147
                    false, 'receipt'),
148
                'MSG_context'        => new EE_Plain_Text_Field('MSG_context', __('Context', 'event_espresso'), false),
149
                'MSG_recipient_ID'   => new EE_Foreign_Key_Int_Field('MSG_recipient_ID',
150
                    __('Recipient ID', 'event_espresso'), true, null, array('Registration', 'Attendee', 'WP_User')),
0 ignored issues
show
Documentation introduced by
array('Registration', 'Attendee', 'WP_User') is of type array<integer,string,{"0..."string","2":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
151
                'MSG_recipient_type' => new EE_Any_Foreign_Model_Name_Field('MSG_recipient_type',
152
                    __('Recipient Type', 'event_espresso'), true, null, array('Registration', 'Attendee', 'WP_User')),
0 ignored issues
show
Documentation introduced by
array('Registration', 'Attendee', 'WP_User') is of type array<integer,string,{"0..."string","2":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
153
                'MSG_content'        => new EE_Maybe_Serialized_Text_Field('MSG_content',
154
                    __('Content', 'event_espresso'), true, ''),
155
                'MSG_to'             => new EE_Maybe_Serialized_Text_Field('MSG_to', __('Address To', 'event_espresso'),
156
                    true),
157
                'MSG_from'           => new EE_Maybe_Serialized_Text_Field('MSG_from',
158
                    __('Address From', 'event_espresso'), true),
159
                'MSG_subject'        => new EE_Maybe_Serialized_Text_Field('MSG_subject',
160
                    __('Subject', 'event_espresso'), true, ''),
161
                'MSG_priority'       => new EE_Enum_Integer_Field('MSG_priority', __('Priority', 'event_espresso'),
162
                    false, self::priority_low, $allowed_priority),
163
                'STS_ID'             => new EE_Foreign_Key_String_Field('STS_ID', __('Status', 'event_espresso'), false,
164
                    self::status_incomplete, 'Status'),
165
                'MSG_created'        => new EE_Datetime_Field('MSG_created', __('Created', 'event_espresso'), false,
166
                    EE_Datetime_Field::now),
167
                'MSG_modified'       => new EE_Datetime_Field('MSG_modified', __('Modified', 'event_espresso'), true,
168
                    EE_Datetime_Field::now),
169
            ),
170
        );
171
        $this->_model_relations = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array('Attendee' => new ..._Belongs_To_Relation()) of type array<string,object<EE_B...Belongs_To_Relation>"}> is incompatible with the declared type array<integer,object<EE_Model_Relation_Base>> of property $_model_relations.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
172
            'Attendee'               => new EE_Belongs_To_Any_Relation(),
173
            'Registration'           => new EE_Belongs_To_Any_Relation(),
174
            'WP_User'                => new EE_Belongs_To_Any_Relation(),
175
            'Message_Template_Group' => new EE_Belongs_To_Relation(),
176
            'Transaction'            => new EE_Belongs_To_Relation(),
177
        );
178
        parent::__construct($timezone);
0 ignored issues
show
Bug introduced by
It seems like $timezone defined by parameter $timezone on line 112 can also be of type string; however, EEM_Base::__construct() does only seem to accept null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
179
    }
180
181
182
    /**
183
     * @return \EE_Message
184
     */
185
    public function create_default_object()
186
    {
187
        /** @type EE_Message $message */
188
        $message = parent::create_default_object();
189
        if ($message instanceof EE_Message) {
190
            return EE_Message_Factory::set_messenger_and_message_type($message);
191
        }
192
        return null;
193
    }
194
195
196
    /**
197
     * @param mixed $cols_n_values
198
     * @return \EE_Message
199
     */
200
    public function instantiate_class_from_array_or_object($cols_n_values)
201
    {
202
        /** @type EE_Message $message */
203
        $message = parent::instantiate_class_from_array_or_object($cols_n_values);
204
        if ($message instanceof EE_Message) {
205
            return EE_Message_Factory::set_messenger_and_message_type($message);
206
        }
207
        return null;
208
    }
209
210
211
    /**
212
     * Returns whether or not a message of that type was sent for a given attendee.
213
     *
214
     * @param EE_Attendee|int $attendee
215
     * @param string          $message_type the message type slug
216
     * @return boolean
217
     */
218 View Code Duplication
    public function message_sent_for_attendee($attendee, $message_type)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
219
    {
220
        $attendee_ID = EEM_Attendee::instance()->ensure_is_ID($attendee);
221
        return $this->exists(array(
222
            array(
223
                'Attendee.ATT_ID'  => $attendee_ID,
224
                'MSG_message_type' => $message_type,
225
                'STS_ID'           => array('IN', $this->stati_indicating_sent()),
226
            ),
227
        ));
228
    }
229
230
231
    /**
232
     * Returns whether or not a message of that type was sent for a given registration
233
     *
234
     * @param EE_Registration|int $registration
235
     * @param string              $message_type the message type slug
236
     * @return boolean
237
     */
238 View Code Duplication
    public function message_sent_for_registration($registration, $message_type)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
239
    {
240
        $registrationID = EEM_Registration::instance()->ensure_is_ID($registration);
241
        return $this->exists(array(
242
            array(
243
                'Registration.REG_ID' => $registrationID,
244
                'MSG_message_type'    => $message_type,
245
                'STS_ID'              => array('IN', $this->stati_indicating_sent()),
246
            ),
247
        ));
248
    }
249
250
251
    /**
252
     * This retrieves an EE_Message object from the db matching the given token string.
253
     *
254
     * @param string $token
255
     * @return EE_Message
256
     */
257
    public function get_one_by_token($token)
258
    {
259
        return $this->get_one(array(
260
            array(
261
                'MSG_token' => $token,
262
            ),
263
        ));
264
    }
265
266
267
    /**
268
     * Returns stati that indicate the message HAS been sent
269
     *
270
     * @return array of strings for possible stati
271
     */
272
    public function stati_indicating_sent()
273
    {
274
        return apply_filters('FHEE__EEM_Message__stati_indicating_sent', array(self::status_sent));
275
    }
276
277
278
    /**
279
     * Returns stati that indicate the message is waiting to be sent.
280
     *
281
     * @return array of strings for possible stati.
282
     */
283
    public function stati_indicating_to_send()
284
    {
285
        return apply_filters('FHEE__EEM_Message__stati_indicating_to_send',
286
            array(self::status_idle, self::status_resend));
287
    }
288
289
290
    /**
291
     * Returns stati that indicate the message has failed sending
292
     *
293
     * @return array  array of strings for possible stati.
294
     */
295
    public function stati_indicating_failed_sending()
296
    {
297
        $failed_stati = array(
298
            self::status_failed,
299
            self::status_retry,
300
            self::status_messenger_executing,
301
        );
302
        //if WP_DEBUG is set, then let's include debug_only fails
303
        if (WP_DEBUG) {
304
            $failed_stati[] = self::status_debug_only;
305
        }
306
        return apply_filters('FHEE__EEM_Message__stati_indicating_failed_sending', $failed_stati);
307
    }
308
309
310
    /**
311
     * Returns filterable array of all EEM_Message statuses.
312
     *
313
     * @return array
314
     */
315
    public function all_statuses()
316
    {
317
        return apply_filters(
318
            'FHEE__EEM_Message__all_statuses',
319
            array(
320
                EEM_Message::status_sent,
321
                EEM_Message::status_incomplete,
322
                EEM_Message::status_idle,
323
                EEM_Message::status_resend,
324
                EEM_Message::status_retry,
325
                EEM_Message::status_failed,
326
                EEM_Message::status_messenger_executing,
327
                EEM_Message::status_debug_only,
328
            )
329
        );
330
    }
331
332
    /**
333
     * Detects any specific query variables in the request and uses those to setup appropriate
334
     * filter for any queries.
335
     *
336
     * @return array
337
     */
338
    public function filter_by_query_params()
339
    {
340
        // expected possible query_vars, the key in this array matches an expected key in the request,
341
        // the value, matches the corresponding EEM_Base child reference.
342
        $expected_vars   = $this->_expected_vars_for_query_inject();
343
        $query_params[0] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$query_params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query_params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
344
        foreach ($expected_vars as $request_key => $model_name) {
345
            $request_value = EE_Registry::instance()->REQ->get($request_key);
346
            if ($request_value) {
347
                //special case
348
                switch ($request_key) {
349
                    case '_REG_ID' :
350
                        $query_params[0]['AND**filter_by']['OR**filter_by_REG_ID'] = array(
351
                            'Transaction.Registration.REG_ID' => $request_value,
352
                        );
353
                        break;
354
                    case 'EVT_ID' :
355
                        $query_params[0]['AND**filter_by']['OR**filter_by_EVT_ID'] = array(
356
                            'Transaction.Registration.EVT_ID' => $request_value,
357
                        );
358
                        break;
359
                    default :
360
                        $query_params[0]['AND**filter_by']['OR**filter_by_' . $request_key][$model_name . '.' . $request_key] = $request_value;
361
                        break;
362
                }
363
            }
364
        }
365
        return $query_params;
366
    }
367
368
369
    /**
370
     * @return string
371
     */
372
    public function get_pretty_label_for_results()
373
    {
374
        $expected_vars = $this->_expected_vars_for_query_inject();
375
        $pretty_label  = '';
376
        $label_parts   = array();
377
        foreach ($expected_vars as $request_key => $model_name) {
378
            $model = EE_Registry::instance()->load_model($model_name);
379
            if ($model_field_value = EE_Registry::instance()->REQ->get($request_key)) {
380
                switch ($request_key) {
381
                    case '_REG_ID' :
382
                        $label_parts[] = sprintf(
383
                            esc_html__('Registration with the ID: %s', 'event_espresso'),
384
                            $model_field_value
385
                        );
386
                        break;
387
                    case 'ATT_ID' :
388
                        /** @var EE_Attendee $attendee */
389
                        $attendee      = $model->get_one_by_ID($model_field_value);
390
                        $label_parts[] = $attendee instanceof EE_Attendee
391
                            ? sprintf(esc_html__('Attendee %s', 'event_espresso'), $attendee->full_name())
392
                            : sprintf(esc_html__('Attendee ID: %s', 'event_espresso'), $model_field_value);
393
                        break;
394
                    case 'ID' :
395
                        /** @var EE_WP_User $wpUser */
396
                        $wpUser        = $model->get_one_by_ID($model_field_value);
397
                        $label_parts[] = $wpUser instanceof EE_WP_User
398
                            ? sprintf(esc_html__('WP User: %s', 'event_espresso'), $wpUser->name())
399
                            : sprintf(esc_html__('WP User ID: %s', 'event_espresso'), $model_field_value);
400
                        break;
401
                    case 'TXN_ID' :
402
                        $label_parts[] = sprintf(
403
                            esc_html__('Transaction with the ID: %s', 'event_espresso'),
404
                            $model_field_value
405
                        );
406
                        break;
407
                    case 'EVT_ID' :
408
                        /** @var EE_Event $Event */
409
                        $Event         = $model->get_one_by_ID($model_field_value);
410
                        $label_parts[] = $Event instanceof EE_Event
411
                            ? sprintf(esc_html__('for the Event: %s', 'event_espresso'), $Event->name())
412
                            : sprintf(esc_html__('for the Event with ID: %s', 'event_espresso'), $model_field_value);
413
                        break;
414
                }
415
            }
416
        }
417
418
        if ($label_parts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $label_parts of type array 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...
419
420
            //prepend to the last element of $label_parts an "and".
421
            if (count($label_parts) > 1) {
422
                $label_parts_index_to_prepend               = count($label_parts) - 1;
423
                $label_parts[$label_parts_index_to_prepend] = 'and' . $label_parts[$label_parts_index_to_prepend];
424
            }
425
426
            $pretty_label .= sprintf(
427
                esc_html_x(
428
                    'Showing messages for %s',
429
                    'A label for the messages returned in a query that are filtered by items in the query. This could be Transaction, Event, Attendee, Registration, or WP_User.',
430
                    'event_espresso'
431
                ),
432
                implode(', ', $label_parts)
433
            );
434
        }
435
        return $pretty_label;
436
    }
437
438
439
    /**
440
     * This returns the array of expected variables for the EEI_Query_Filter methods being implemented
441
     * The array is in the format:
442
     * array(
443
     *  {$field_name} => {$model_name}
444
     * );
445
     *
446
     * @since 4.9.0
447
     * @return array
448
     */
449
    protected function _expected_vars_for_query_inject()
450
    {
451
        return array(
452
            '_REG_ID' => 'Registration',
453
            'ATT_ID'  => 'Attendee',
454
            'ID'      => 'WP_User',
455
            'TXN_ID'  => 'Transaction',
456
            'EVT_ID'  => 'Event',
457
        );
458
    }
459
460
461
    /**
462
     * This returns whether EEM_Message is in debug mode or not.
463
     * Currently "debug mode" is used to control the handling of the EEM_Message::debug_only status when
464
     * generating/sending messages. Debug mode can be set by either:
465
     * 1. Sending in a value for the $set_debug argument
466
     * 2. Defining `EE_DEBUG_MESSAGES` constant in wp-config.php
467
     * 3. Overriding the above via the provided filter.
468
     *
469
     * @param bool|null $set_debug      If provided, then the debug mode will be set internally until reset via the
470
     *                                  provided boolean. When no argument is provided (default null) then the debug
471
     *                                  mode will be returned.
472
     * @return bool         true means Messages is in debug mode.  false means messages system is not in debug mode.
473
     */
474
    public static function debug($set_debug = null)
475
    {
476
        static $is_debugging = null;
477
478
        //initialize (use constant if set).
479
        if (is_null($set_debug) && is_null($is_debugging)) {
480
            $is_debugging = defined('EE_DEBUG_MESSAGES') && EE_DEBUG_MESSAGES;
481
        }
482
483
        if ( ! is_null($set_debug)) {
484
            $is_debugging = filter_var($set_debug, FILTER_VALIDATE_BOOLEAN);
485
        }
486
487
        //return filtered value
488
        return apply_filters('FHEE__EEM_Message__debug', $is_debugging);
489
    }
490
491
492
    /**
493
     * Deletes old messages meeting certain criteria for removal from the database.
494
     * By default, this will delete messages that:
495
     * - are older than the value of the delete_threshold in months.
496
     * - have a STS_ID other than EEM_Message::status_idle
497
     *
498
     * @param int $delete_threshold  This integer will be used to set the boundary for what messages are deleted in months.
499
     * @return bool|false|int Either the number of records affected or false if there was an error (you can call
500
     *                         $wpdb->last_error to find out what the error was.
501
     */
502
    public function delete_old_messages($delete_threshold = 6)
503
    {
504
        $number_deleted = 0;
505
        /**
506
         * Allows code to change the boundary for what messages are kept.
507
         * Uses the value of the `delete_threshold` variable by default.
508
         *
509
         * @param int $seconds seconds that will be subtracted from the timestamp for now.
510
         * @return int
511
         */
512
        $time_to_leave_alone = absint(
513
            apply_filters(
514
                'FHEE__EEM_Message__delete_old_messages__time_to_leave_alone',
515
                ((int) $delete_threshold) * MONTH_IN_SECONDS
516
            )
517
        );
518
519
520
        /**
521
         * Allows code to change what message stati are ignored when deleting.
522
         * Defaults to only ignore EEM_Message::status_idle messages.
523
         *
524
         * @param string $message_stati_to_keep  An array of message statuses that will be ignored when deleting.
525
         */
526
        $message_stati_to_keep = (array) apply_filters(
527
            'FHEE__EEM_Message__delete_old_messages__message_stati_to_keep',
528
            array(
529
                EEM_Message::status_idle
530
            )
531
        );
532
533
        //first get all the ids of messages being deleted
534
        $message_ids_to_delete = EEM_Message::instance()->get_col(
535
            array(
536
                0 => array(
537
                    'STS_ID' => array('NOT_IN', $message_stati_to_keep),
538
                    'MSG_modified' => array('<', time() - $time_to_leave_alone)
539
                )
540
            )
541
        );
542
543 View Code Duplication
        if(! empty($message_ids_to_delete) && is_array($message_ids_to_delete)) {
544
            global $wpdb;
545
            $number_deleted = $wpdb->query('
546
                DELETE
547
                FROM ' . $this->table() . '
548
                WHERE
549
                    MSG_ID IN (' . implode(",", $message_ids_to_delete) . ')
550
            ');
551
        }
552
553
        /**
554
         * This will get called if the number of records deleted 0 or greater.  So a successful deletion is one where
555
         * there were no errors.  An unsuccessful deletion is where there were errors.  Keep that in mind for the actions
556
         * below.
557
         */
558
        if ($number_deleted !== false) {
559
            do_action('AHEE__EEM_Message__delete_old_messages__after_successful_deletion', $message_ids_to_delete, $number_deleted);
560
        } else {
561
            do_action('AHEE__EEM_Message__delete_old_messages__after_deletion_fail', $message_ids_to_delete, $number_deleted);
562
        }
563
        return $number_deleted;
564
    }
565
566
}
567
// End of file EEM_Message.model.php
568
// Location: /includes/models/EEM_Message.model.php
569