Completed
Branch GDPR/privacy-policy-content (f954f3)
by
unknown
60:17 queued 46:07
created
core/db_models/EEM_CPT_Base.model.php 2 patches
Indentation   +514 added lines, -514 removed lines patch added patch discarded remove patch
@@ -18,519 +18,519 @@
 block discarded – undo
18 18
 abstract class EEM_CPT_Base extends EEM_Soft_Delete_Base
19 19
 {
20 20
 
21
-    /**
22
-     * @var string post_status_publish - the wp post status for published cpts
23
-     */
24
-    const post_status_publish = 'publish';
25
-
26
-    /**
27
-     * @var string post_status_future - the wp post status for scheduled cpts
28
-     */
29
-    const post_status_future = 'future';
30
-
31
-    /**
32
-     * @var string post_status_draft - the wp post status for draft cpts
33
-     */
34
-    const post_status_draft = 'draft';
35
-
36
-    /**
37
-     * @var string post_status_pending - the wp post status for pending cpts
38
-     */
39
-    const post_status_pending = 'pending';
40
-
41
-    /**
42
-     * @var string post_status_private - the wp post status for private cpts
43
-     */
44
-    const post_status_private = 'private';
45
-
46
-    /**
47
-     * @var string post_status_trashed - the wp post status for trashed cpts
48
-     */
49
-    const post_status_trashed = 'trash';
50
-
51
-    /**
52
-     * This is an array of custom statuses for the given CPT model (modified by children)
53
-     * format:
54
-     * array(
55
-     *        'status_name' => array(
56
-     *            'label' => __('Status Name', 'event_espresso'),
57
-     *            'public' => TRUE //whether a public status or not.
58
-     *        )
59
-     * )
60
-     *
61
-     * @var array
62
-     */
63
-    protected $_custom_stati = array();
64
-
65
-
66
-
67
-    /**
68
-     * Adds a relationship to Term_Taxonomy for each CPT_Base
69
-     *
70
-     * @param string $timezone
71
-     * @throws \EE_Error
72
-     */
73
-    protected function __construct($timezone = null)
74
-    {
75
-        //adds a relationship to Term_Taxonomy for all these models. For this to work
76
-        //Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
77
-        //eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
78
-        //with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
79
-        //must also be new EE_HABTM_Relation('Term_Relationship');
80
-        $this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
81
-        $primary_table_name = null;
82
-        //add  the common _status field to all CPT primary tables.
83
-        foreach ($this->_tables as $alias => $table_obj) {
84
-            if ($table_obj instanceof EE_Primary_Table) {
85
-                $primary_table_name = $alias;
86
-            }
87
-        }
88
-        //set default wp post statuses if child has not already set.
89
-        if ( ! isset($this->_fields[$primary_table_name]['status'])) {
90
-            $this->_fields[$primary_table_name]['status'] = new EE_WP_Post_Status_Field('post_status',
91
-                __("Event Status", "event_espresso"), false, 'draft');
92
-        }
93
-        if ( ! isset($this->_fields[$primary_table_name]['to_ping'])) {
94
-            $this->_fields[$primary_table_name]['to_ping'] = new EE_DB_Only_Text_Field('to_ping',
95
-                __('To Ping', 'event_espresso'), false, '');
96
-        }
97
-        if ( ! isset($this->_fields[$primary_table_name]['pinged'])) {
98
-            $this->_fields[$primary_table_name]['pinged'] = new EE_DB_Only_Text_Field('pinged',
99
-                __('Pinged', 'event_espresso'), false, '');
100
-        }
101
-        if ( ! isset($this->_fields[$primary_table_name]['comment_status'])) {
102
-            $this->_fields[$primary_table_name]['comment_status'] = new EE_Plain_Text_Field('comment_status',
103
-                __('Comment Status', 'event_espresso'), false, 'open');
104
-        }
105
-        if ( ! isset($this->_fields[$primary_table_name]['ping_status'])) {
106
-            $this->_fields[$primary_table_name]['ping_status'] = new EE_Plain_Text_Field('ping_status',
107
-                __('Ping Status', 'event_espresso'), false, 'open');
108
-        }
109
-        if ( ! isset($this->_fields[$primary_table_name]['post_content_filtered'])) {
110
-            $this->_fields[$primary_table_name]['post_content_filtered'] = new EE_DB_Only_Text_Field('post_content_filtered',
111
-                __('Post Content Filtered', 'event_espresso'), false, '');
112
-        }
113
-        if ( ! isset($this->_model_relations['Post_Meta'])) {
114
-            //don't block deletes though because we want to maintain the current behaviour
115
-            $this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
116
-        }
117
-        if ( ! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
118
-            //nothing was set during child constructor, so set default
119
-            $this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
120
-        }
121
-        if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
122
-            //nothing was set during child constructor, so set default
123
-            //it's ok for child classes to specify this, but generally this is more DRY
124
-            $this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
125
-        }
126
-        parent::__construct($timezone);
127
-    }
128
-
129
-
130
-
131
-    /**
132
-     * @return array
133
-     */
134
-    public function public_event_stati()
135
-    {
136
-        // @see wp-includes/post.php
137
-        return get_post_stati(array('public' => true));
138
-    }
139
-
140
-
141
-
142
-    /**
143
-     * Searches for field on this model of type 'deleted_flag'. if it is found,
144
-     * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
145
-     *
146
-     * @return string
147
-     * @throws EE_Error
148
-     */
149
-    public function deleted_field_name()
150
-    {
151
-        throw new EE_Error(sprintf(__("EEM_CPT_Base should nto call deleted_field_name! It should instead use post_status_field_name",
152
-            "event_espresso")));
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     * Gets the field's name that sets the post status
159
-     *
160
-     * @return string
161
-     * @throws EE_Error
162
-     */
163
-    public function post_status_field_name()
164
-    {
165
-        $field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
166
-        if ($field) {
167
-            return $field->get_name();
168
-        } else {
169
-            throw new EE_Error(sprintf(__('We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
170
-                'event_espresso'), get_class($this), get_class($this)));
171
-        }
172
-    }
173
-
174
-
175
-
176
-    /**
177
-     * Alters the query params so that only trashed/soft-deleted items are considered
178
-     *
179
-     * @param array $query_params like EEM_Base::get_all's $query_params
180
-     * @return array like EEM_Base::get_all's $query_params
181
-     */
182
-    protected function _alter_query_params_so_only_trashed_items_included($query_params)
183
-    {
184
-        $post_status_field_name = $this->post_status_field_name();
185
-        $query_params[0][$post_status_field_name] = self::post_status_trashed;
186
-        return $query_params;
187
-    }
188
-
189
-
190
-
191
-    /**
192
-     * Alters the query params so each item's deleted status is ignored.
193
-     *
194
-     * @param array $query_params
195
-     * @return array
196
-     */
197
-    protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
198
-    {
199
-        $query_params['default_where_conditions'] = 'minimum';
200
-        return $query_params;
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
207
-     *
208
-     * @param boolean $delete       true to indicate deletion, false to indicate restoration
209
-     * @param array   $query_params like EEM_Base::get_all
210
-     * @return boolean success
211
-     */
212
-    function delete_or_restore($delete = true, $query_params = array())
213
-    {
214
-        $post_status_field_name = $this->post_status_field_name();
215
-        $query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
216
-        $new_status = $delete ? self::post_status_trashed : 'draft';
217
-        if ($this->update(array($post_status_field_name => $new_status), $query_params)) {
218
-            return true;
219
-        } else {
220
-            return false;
221
-        }
222
-    }
223
-
224
-
225
-
226
-    /**
227
-     * meta_table
228
-     * returns first EE_Secondary_Table table name
229
-     *
230
-     * @access public
231
-     * @return string
232
-     */
233
-    public function meta_table()
234
-    {
235
-        $meta_table = $this->_get_other_tables();
236
-        $meta_table = reset($meta_table);
237
-        return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
238
-    }
239
-
240
-
241
-
242
-    /**
243
-     * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
244
-     *
245
-     * @param  bool $all triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
246
-     *                   db only fields)
247
-     * @return array
248
-     */
249
-    public function get_meta_table_fields($all = false)
250
-    {
251
-        $all_fields = $fields_to_return = array();
252
-        foreach ($this->_tables as $alias => $table_obj) {
253
-            if ($table_obj instanceof EE_Secondary_Table) {
254
-                $all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
255
-            }
256
-        }
257
-        if ( ! $all) {
258
-            foreach ($all_fields as $name => $obj) {
259
-                if ($obj instanceof EE_DB_Only_Field_Base) {
260
-                    continue;
261
-                }
262
-                $fields_to_return[] = $name;
263
-            }
264
-        } else {
265
-            $fields_to_return = array_keys($all_fields);
266
-        }
267
-        return $fields_to_return;
268
-    }
269
-
270
-
271
-
272
-    /**
273
-     * Adds an event category with the specified name and description to the specified
274
-     * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
275
-     * and adds an entry in the term_relationship if necessary.
276
-     *
277
-     * @param EE_CPT_Base $cpt_model_object
278
-     * @param string      $category_name (used to derive the term slug too)
279
-     * @param string      $category_description
280
-     * @param int         $parent_term_taxonomy_id
281
-     * @return EE_Term_Taxonomy
282
-     */
283
-    function add_event_category(
284
-        EE_CPT_Base $cpt_model_object,
285
-        $category_name,
286
-        $category_description = '',
287
-        $parent_term_taxonomy_id = null
288
-    ) {
289
-        //create term
290
-        require_once(EE_MODELS . 'EEM_Term.model.php');
291
-        //first, check for a term by the same name or slug
292
-        $category_slug = sanitize_title($category_name);
293
-        $term = EEM_Term::instance()->get_one(array(
294
-            array(
295
-                'OR' => array(
296
-                    'name' => $category_name,
297
-                    'slug' => $category_slug,
298
-                ),
299
-            ),
300
-        ));
301
-        if ( ! $term) {
302
-            $term = EE_Term::new_instance(array(
303
-                'name' => $category_name,
304
-                'slug' => $category_slug,
305
-            ));
306
-            $term->save();
307
-        }
308
-        //make sure there's a term-taxonomy entry too
309
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
310
-        $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(array(
311
-            array(
312
-                'term_id'  => $term->ID(),
313
-                'taxonomy' => EE_Event_Category_Taxonomy,
314
-            ),
315
-        ));
316
-        /** @var $term_taxonomy EE_Term_Taxonomy */
317
-        if ( ! $term_taxonomy) {
318
-            $term_taxonomy = EE_Term_Taxonomy::new_instance(array(
319
-                'term_id'     => $term->ID(),
320
-                'taxonomy'    => EE_Event_Category_Taxonomy,
321
-                'description' => $category_description,
322
-                'count'       => 1,
323
-                'parent'      => $parent_term_taxonomy_id,
324
-            ));
325
-            $term_taxonomy->save();
326
-        } else {
327
-            $term_taxonomy->set_count($term_taxonomy->count() + 1);
328
-            $term_taxonomy->save();
329
-        }
330
-        return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
331
-    }
332
-
333
-
334
-
335
-    /**
336
-     * Removed the category specified by name as having a relation to this event.
337
-     * Does not remove the term or term_taxonomy.
338
-     *
339
-     * @param EE_CPT_Base $cpt_model_object_event
340
-     * @param string      $category_name name of the event category (term)
341
-     * @return bool
342
-     */
343
-    function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
344
-    {
345
-        //find the term_taxonomy by that name
346
-        $term_taxonomy = $this->get_first_related($cpt_model_object_event, 'Term_Taxonomy',
347
-            array(array('Term.name' => $category_name, 'taxonomy' => EE_Event_Category_Taxonomy)));
348
-        /** @var $term_taxonomy EE_Term_Taxonomy */
349
-        if ($term_taxonomy) {
350
-            $term_taxonomy->set_count($term_taxonomy->count() - 1);
351
-            $term_taxonomy->save();
352
-        }
353
-        return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
354
-    }
355
-
356
-
357
-
358
-    /**
359
-     * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
360
-     * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
361
-     *
362
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
363
-     * @access public
364
-     * @param int          $id   the ID for the cpt we want the feature image for
365
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
366
-     *                           representing width and height in pixels (i.e. array(32,32) ).
367
-     * @param string|array $attr Optional. Query string or array of attributes.
368
-     * @return string HTML image element
369
-     */
370
-    public function get_feature_image($id, $size = 'thumbnail', $attr = '')
371
-    {
372
-        return get_the_post_thumbnail($id, $size, $attr);
373
-    }
374
-
375
-
376
-
377
-    /**
378
-     * Just a handy way to get the list of post statuses currently registered with WP.
379
-     *
380
-     * @global array $wp_post_statuses set in wp core for storing all the post stati
381
-     * @return array
382
-     */
383
-    public function get_post_statuses()
384
-    {
385
-        global $wp_post_statuses;
386
-        $statuses = array();
387
-        foreach ($wp_post_statuses as $post_status => $args_object) {
388
-            $statuses[$post_status] = $args_object->label;
389
-        }
390
-        return $statuses;
391
-    }
392
-
393
-
394
-
395
-    /**
396
-     * public method that can be used to retrieve the protected status array on the instantiated cpt model
397
-     *
398
-     * @return array array of statuses.
399
-     */
400
-    public function get_status_array()
401
-    {
402
-        $statuses = $this->get_post_statuses();
403
-        //first the global filter
404
-        $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
405
-        //now the class specific filter
406
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
407
-        return $statuses;
408
-    }
409
-
410
-
411
-
412
-    /**
413
-     * this returns the post statuses that are NOT the default wordpress status
414
-     *
415
-     * @return array
416
-     */
417
-    public function get_custom_post_statuses()
418
-    {
419
-        $new_stati = array();
420
-        foreach ($this->_custom_stati as $status => $props) {
421
-            $new_stati[$status] = $props['label'];
422
-        }
423
-        return $new_stati;
424
-    }
425
-
426
-
427
-
428
-    /**
429
-     * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
430
-     * are a row from the posts table. If we're missing any fields required for the model,
431
-     * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
432
-     * make sure you are attaching all the model's fields onto the post)
433
-     *
434
-     * @param WP_Post|array $post
435
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
436
-     */
437
-    public function instantiate_class_from_post_object_orig($post)
438
-    {
439
-        $post = (array)$post;
440
-        $has_all_necessary_fields_for_table = true;
441
-        //check if the post has fields on the meta table already
442
-        foreach ($this->_get_other_tables() as $table_obj) {
443
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
444
-            foreach ($fields_for_that_table as $field_obj) {
445
-                if ( ! isset($post[$field_obj->get_table_column()])
446
-                     && ! isset($post[$field_obj->get_qualified_column()])
447
-                ) {
448
-                    $has_all_necessary_fields_for_table = false;
449
-                }
450
-            }
451
-        }
452
-        //if we don't have all the fields we need, then just fetch the proper model from the DB
453
-        if ( ! $has_all_necessary_fields_for_table) {
454
-            return $this->get_one_by_ID($post['ID']);
455
-        } else {
456
-            return $this->instantiate_class_from_array_or_object($post);
457
-        }
458
-    }
459
-
460
-
461
-
462
-    /**
463
-     * @param null $post
464
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class
465
-     */
466
-    public function instantiate_class_from_post_object($post = null)
467
-    {
468
-        if (empty($post)) {
469
-            global $post;
470
-        }
471
-        $post = (array)$post;
472
-        $tables_needing_to_be_queried = array();
473
-        //check if the post has fields on the meta table already
474
-        foreach ($this->get_tables() as $table_obj) {
475
-            $fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
476
-            foreach ($fields_for_that_table as $field_obj) {
477
-                if ( ! isset($post[$field_obj->get_table_column()])
478
-                     && ! isset($post[$field_obj->get_qualified_column()])
479
-                ) {
480
-                    $tables_needing_to_be_queried[$table_obj->get_table_alias()] = $table_obj;
481
-                }
482
-            }
483
-        }
484
-        //if we don't have all the fields we need, then just fetch the proper model from the DB
485
-        if ($tables_needing_to_be_queried) {
486
-            if (count($tables_needing_to_be_queried) == 1
487
-                && reset($tables_needing_to_be_queried)
488
-                   instanceof
489
-                   EE_Secondary_Table
490
-            ) {
491
-                //so we're only missing data from a secondary table. Well that's not too hard to query for
492
-                $table_to_query = reset($tables_needing_to_be_queried);
493
-                $missing_data = $this->_do_wpdb_query('get_row', array(
494
-                    'SELECT * FROM '
495
-                    . $table_to_query->get_table_name()
496
-                    . ' WHERE '
497
-                    . $table_to_query->get_fk_on_table()
498
-                    . ' = '
499
-                    . $post['ID'],
500
-                    ARRAY_A,
501
-                ));
502
-                if ( ! empty($missing_data)) {
503
-                    $post = array_merge($post, $missing_data);
504
-                }
505
-            } else {
506
-                return $this->get_one_by_ID($post['ID']);
507
-            }
508
-        }
509
-        return $this->instantiate_class_from_array_or_object($post);
510
-    }
511
-
512
-
513
-
514
-    /**
515
-     * Gets the post type associated with this
516
-     *
517
-     * @throws EE_Error
518
-     * @return string
519
-     */
520
-    public function post_type()
521
-    {
522
-        $post_type_field = null;
523
-        foreach ($this->field_settings(true) as $field_obj) {
524
-            if ($field_obj instanceof EE_WP_Post_Type_Field) {
525
-                $post_type_field = $field_obj;
526
-                break;
527
-            }
528
-        }
529
-        if ($post_type_field == null) {
530
-            throw new EE_Error(sprintf(__("CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
531
-                "event_espresso"), get_class($this)));
532
-        }
533
-        return $post_type_field->get_default_value();
534
-    }
21
+	/**
22
+	 * @var string post_status_publish - the wp post status for published cpts
23
+	 */
24
+	const post_status_publish = 'publish';
25
+
26
+	/**
27
+	 * @var string post_status_future - the wp post status for scheduled cpts
28
+	 */
29
+	const post_status_future = 'future';
30
+
31
+	/**
32
+	 * @var string post_status_draft - the wp post status for draft cpts
33
+	 */
34
+	const post_status_draft = 'draft';
35
+
36
+	/**
37
+	 * @var string post_status_pending - the wp post status for pending cpts
38
+	 */
39
+	const post_status_pending = 'pending';
40
+
41
+	/**
42
+	 * @var string post_status_private - the wp post status for private cpts
43
+	 */
44
+	const post_status_private = 'private';
45
+
46
+	/**
47
+	 * @var string post_status_trashed - the wp post status for trashed cpts
48
+	 */
49
+	const post_status_trashed = 'trash';
50
+
51
+	/**
52
+	 * This is an array of custom statuses for the given CPT model (modified by children)
53
+	 * format:
54
+	 * array(
55
+	 *        'status_name' => array(
56
+	 *            'label' => __('Status Name', 'event_espresso'),
57
+	 *            'public' => TRUE //whether a public status or not.
58
+	 *        )
59
+	 * )
60
+	 *
61
+	 * @var array
62
+	 */
63
+	protected $_custom_stati = array();
64
+
65
+
66
+
67
+	/**
68
+	 * Adds a relationship to Term_Taxonomy for each CPT_Base
69
+	 *
70
+	 * @param string $timezone
71
+	 * @throws \EE_Error
72
+	 */
73
+	protected function __construct($timezone = null)
74
+	{
75
+		//adds a relationship to Term_Taxonomy for all these models. For this to work
76
+		//Term_Relationship must have a relation to each model subclassing EE_CPT_Base explicitly
77
+		//eg, in EEM_Term_Relationship, inside the _model_relations array, there must be an entry
78
+		//with key equalling the subclassing model's model name (eg 'Event' or 'Venue'), and the value
79
+		//must also be new EE_HABTM_Relation('Term_Relationship');
80
+		$this->_model_relations['Term_Taxonomy'] = new EE_HABTM_Relation('Term_Relationship');
81
+		$primary_table_name = null;
82
+		//add  the common _status field to all CPT primary tables.
83
+		foreach ($this->_tables as $alias => $table_obj) {
84
+			if ($table_obj instanceof EE_Primary_Table) {
85
+				$primary_table_name = $alias;
86
+			}
87
+		}
88
+		//set default wp post statuses if child has not already set.
89
+		if ( ! isset($this->_fields[$primary_table_name]['status'])) {
90
+			$this->_fields[$primary_table_name]['status'] = new EE_WP_Post_Status_Field('post_status',
91
+				__("Event Status", "event_espresso"), false, 'draft');
92
+		}
93
+		if ( ! isset($this->_fields[$primary_table_name]['to_ping'])) {
94
+			$this->_fields[$primary_table_name]['to_ping'] = new EE_DB_Only_Text_Field('to_ping',
95
+				__('To Ping', 'event_espresso'), false, '');
96
+		}
97
+		if ( ! isset($this->_fields[$primary_table_name]['pinged'])) {
98
+			$this->_fields[$primary_table_name]['pinged'] = new EE_DB_Only_Text_Field('pinged',
99
+				__('Pinged', 'event_espresso'), false, '');
100
+		}
101
+		if ( ! isset($this->_fields[$primary_table_name]['comment_status'])) {
102
+			$this->_fields[$primary_table_name]['comment_status'] = new EE_Plain_Text_Field('comment_status',
103
+				__('Comment Status', 'event_espresso'), false, 'open');
104
+		}
105
+		if ( ! isset($this->_fields[$primary_table_name]['ping_status'])) {
106
+			$this->_fields[$primary_table_name]['ping_status'] = new EE_Plain_Text_Field('ping_status',
107
+				__('Ping Status', 'event_espresso'), false, 'open');
108
+		}
109
+		if ( ! isset($this->_fields[$primary_table_name]['post_content_filtered'])) {
110
+			$this->_fields[$primary_table_name]['post_content_filtered'] = new EE_DB_Only_Text_Field('post_content_filtered',
111
+				__('Post Content Filtered', 'event_espresso'), false, '');
112
+		}
113
+		if ( ! isset($this->_model_relations['Post_Meta'])) {
114
+			//don't block deletes though because we want to maintain the current behaviour
115
+			$this->_model_relations['Post_Meta'] = new EE_Has_Many_Relation(false);
116
+		}
117
+		if ( ! $this->_minimum_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
118
+			//nothing was set during child constructor, so set default
119
+			$this->_minimum_where_conditions_strategy = new EE_CPT_Minimum_Where_Conditions($this->post_type());
120
+		}
121
+		if ( ! $this->_default_where_conditions_strategy instanceof EE_Default_Where_Conditions) {
122
+			//nothing was set during child constructor, so set default
123
+			//it's ok for child classes to specify this, but generally this is more DRY
124
+			$this->_default_where_conditions_strategy = new EE_CPT_Where_Conditions($this->post_type());
125
+		}
126
+		parent::__construct($timezone);
127
+	}
128
+
129
+
130
+
131
+	/**
132
+	 * @return array
133
+	 */
134
+	public function public_event_stati()
135
+	{
136
+		// @see wp-includes/post.php
137
+		return get_post_stati(array('public' => true));
138
+	}
139
+
140
+
141
+
142
+	/**
143
+	 * Searches for field on this model of type 'deleted_flag'. if it is found,
144
+	 * returns it's name. BUT That doesn't apply to CPTs. We should instead use post_status_field_name
145
+	 *
146
+	 * @return string
147
+	 * @throws EE_Error
148
+	 */
149
+	public function deleted_field_name()
150
+	{
151
+		throw new EE_Error(sprintf(__("EEM_CPT_Base should nto call deleted_field_name! It should instead use post_status_field_name",
152
+			"event_espresso")));
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 * Gets the field's name that sets the post status
159
+	 *
160
+	 * @return string
161
+	 * @throws EE_Error
162
+	 */
163
+	public function post_status_field_name()
164
+	{
165
+		$field = $this->get_a_field_of_type('EE_WP_Post_Status_Field');
166
+		if ($field) {
167
+			return $field->get_name();
168
+		} else {
169
+			throw new EE_Error(sprintf(__('We are trying to find the post status flag field on %s, but none was found. Are you sure there is a field of type EE_Trashed_Flag_Field in %s constructor?',
170
+				'event_espresso'), get_class($this), get_class($this)));
171
+		}
172
+	}
173
+
174
+
175
+
176
+	/**
177
+	 * Alters the query params so that only trashed/soft-deleted items are considered
178
+	 *
179
+	 * @param array $query_params like EEM_Base::get_all's $query_params
180
+	 * @return array like EEM_Base::get_all's $query_params
181
+	 */
182
+	protected function _alter_query_params_so_only_trashed_items_included($query_params)
183
+	{
184
+		$post_status_field_name = $this->post_status_field_name();
185
+		$query_params[0][$post_status_field_name] = self::post_status_trashed;
186
+		return $query_params;
187
+	}
188
+
189
+
190
+
191
+	/**
192
+	 * Alters the query params so each item's deleted status is ignored.
193
+	 *
194
+	 * @param array $query_params
195
+	 * @return array
196
+	 */
197
+	protected function _alter_query_params_so_deleted_and_undeleted_items_included($query_params)
198
+	{
199
+		$query_params['default_where_conditions'] = 'minimum';
200
+		return $query_params;
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * Performs deletes or restores on items. Both soft-deleted and non-soft-deleted items considered.
207
+	 *
208
+	 * @param boolean $delete       true to indicate deletion, false to indicate restoration
209
+	 * @param array   $query_params like EEM_Base::get_all
210
+	 * @return boolean success
211
+	 */
212
+	function delete_or_restore($delete = true, $query_params = array())
213
+	{
214
+		$post_status_field_name = $this->post_status_field_name();
215
+		$query_params = $this->_alter_query_params_so_deleted_and_undeleted_items_included($query_params);
216
+		$new_status = $delete ? self::post_status_trashed : 'draft';
217
+		if ($this->update(array($post_status_field_name => $new_status), $query_params)) {
218
+			return true;
219
+		} else {
220
+			return false;
221
+		}
222
+	}
223
+
224
+
225
+
226
+	/**
227
+	 * meta_table
228
+	 * returns first EE_Secondary_Table table name
229
+	 *
230
+	 * @access public
231
+	 * @return string
232
+	 */
233
+	public function meta_table()
234
+	{
235
+		$meta_table = $this->_get_other_tables();
236
+		$meta_table = reset($meta_table);
237
+		return $meta_table instanceof EE_Secondary_Table ? $meta_table->get_table_name() : null;
238
+	}
239
+
240
+
241
+
242
+	/**
243
+	 * This simply returns an array of the meta table fields (useful for when we just need to update those fields)
244
+	 *
245
+	 * @param  bool $all triggers whether we include DB_Only fields or JUST non DB_Only fields.  Defaults to false (no
246
+	 *                   db only fields)
247
+	 * @return array
248
+	 */
249
+	public function get_meta_table_fields($all = false)
250
+	{
251
+		$all_fields = $fields_to_return = array();
252
+		foreach ($this->_tables as $alias => $table_obj) {
253
+			if ($table_obj instanceof EE_Secondary_Table) {
254
+				$all_fields = array_merge($this->_get_fields_for_table($alias), $all_fields);
255
+			}
256
+		}
257
+		if ( ! $all) {
258
+			foreach ($all_fields as $name => $obj) {
259
+				if ($obj instanceof EE_DB_Only_Field_Base) {
260
+					continue;
261
+				}
262
+				$fields_to_return[] = $name;
263
+			}
264
+		} else {
265
+			$fields_to_return = array_keys($all_fields);
266
+		}
267
+		return $fields_to_return;
268
+	}
269
+
270
+
271
+
272
+	/**
273
+	 * Adds an event category with the specified name and description to the specified
274
+	 * $cpt_model_object. Intelligently adds a term if necessary, and adds a term_taxonomy if necessary,
275
+	 * and adds an entry in the term_relationship if necessary.
276
+	 *
277
+	 * @param EE_CPT_Base $cpt_model_object
278
+	 * @param string      $category_name (used to derive the term slug too)
279
+	 * @param string      $category_description
280
+	 * @param int         $parent_term_taxonomy_id
281
+	 * @return EE_Term_Taxonomy
282
+	 */
283
+	function add_event_category(
284
+		EE_CPT_Base $cpt_model_object,
285
+		$category_name,
286
+		$category_description = '',
287
+		$parent_term_taxonomy_id = null
288
+	) {
289
+		//create term
290
+		require_once(EE_MODELS . 'EEM_Term.model.php');
291
+		//first, check for a term by the same name or slug
292
+		$category_slug = sanitize_title($category_name);
293
+		$term = EEM_Term::instance()->get_one(array(
294
+			array(
295
+				'OR' => array(
296
+					'name' => $category_name,
297
+					'slug' => $category_slug,
298
+				),
299
+			),
300
+		));
301
+		if ( ! $term) {
302
+			$term = EE_Term::new_instance(array(
303
+				'name' => $category_name,
304
+				'slug' => $category_slug,
305
+			));
306
+			$term->save();
307
+		}
308
+		//make sure there's a term-taxonomy entry too
309
+		require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
310
+		$term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(array(
311
+			array(
312
+				'term_id'  => $term->ID(),
313
+				'taxonomy' => EE_Event_Category_Taxonomy,
314
+			),
315
+		));
316
+		/** @var $term_taxonomy EE_Term_Taxonomy */
317
+		if ( ! $term_taxonomy) {
318
+			$term_taxonomy = EE_Term_Taxonomy::new_instance(array(
319
+				'term_id'     => $term->ID(),
320
+				'taxonomy'    => EE_Event_Category_Taxonomy,
321
+				'description' => $category_description,
322
+				'count'       => 1,
323
+				'parent'      => $parent_term_taxonomy_id,
324
+			));
325
+			$term_taxonomy->save();
326
+		} else {
327
+			$term_taxonomy->set_count($term_taxonomy->count() + 1);
328
+			$term_taxonomy->save();
329
+		}
330
+		return $this->add_relationship_to($cpt_model_object, $term_taxonomy, 'Term_Taxonomy');
331
+	}
332
+
333
+
334
+
335
+	/**
336
+	 * Removed the category specified by name as having a relation to this event.
337
+	 * Does not remove the term or term_taxonomy.
338
+	 *
339
+	 * @param EE_CPT_Base $cpt_model_object_event
340
+	 * @param string      $category_name name of the event category (term)
341
+	 * @return bool
342
+	 */
343
+	function remove_event_category(EE_CPT_Base $cpt_model_object_event, $category_name)
344
+	{
345
+		//find the term_taxonomy by that name
346
+		$term_taxonomy = $this->get_first_related($cpt_model_object_event, 'Term_Taxonomy',
347
+			array(array('Term.name' => $category_name, 'taxonomy' => EE_Event_Category_Taxonomy)));
348
+		/** @var $term_taxonomy EE_Term_Taxonomy */
349
+		if ($term_taxonomy) {
350
+			$term_taxonomy->set_count($term_taxonomy->count() - 1);
351
+			$term_taxonomy->save();
352
+		}
353
+		return $this->remove_relationship_to($cpt_model_object_event, $term_taxonomy, 'Term_Taxonomy');
354
+	}
355
+
356
+
357
+
358
+	/**
359
+	 * This is a wrapper for the WordPress get_the_post_thumbnail() function that returns the feature image for the
360
+	 * given CPT ID.  It accepts the same params as what get_the_post_thumbnail() accepts.
361
+	 *
362
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
363
+	 * @access public
364
+	 * @param int          $id   the ID for the cpt we want the feature image for
365
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
366
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
367
+	 * @param string|array $attr Optional. Query string or array of attributes.
368
+	 * @return string HTML image element
369
+	 */
370
+	public function get_feature_image($id, $size = 'thumbnail', $attr = '')
371
+	{
372
+		return get_the_post_thumbnail($id, $size, $attr);
373
+	}
374
+
375
+
376
+
377
+	/**
378
+	 * Just a handy way to get the list of post statuses currently registered with WP.
379
+	 *
380
+	 * @global array $wp_post_statuses set in wp core for storing all the post stati
381
+	 * @return array
382
+	 */
383
+	public function get_post_statuses()
384
+	{
385
+		global $wp_post_statuses;
386
+		$statuses = array();
387
+		foreach ($wp_post_statuses as $post_status => $args_object) {
388
+			$statuses[$post_status] = $args_object->label;
389
+		}
390
+		return $statuses;
391
+	}
392
+
393
+
394
+
395
+	/**
396
+	 * public method that can be used to retrieve the protected status array on the instantiated cpt model
397
+	 *
398
+	 * @return array array of statuses.
399
+	 */
400
+	public function get_status_array()
401
+	{
402
+		$statuses = $this->get_post_statuses();
403
+		//first the global filter
404
+		$statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
405
+		//now the class specific filter
406
+		$statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
407
+		return $statuses;
408
+	}
409
+
410
+
411
+
412
+	/**
413
+	 * this returns the post statuses that are NOT the default wordpress status
414
+	 *
415
+	 * @return array
416
+	 */
417
+	public function get_custom_post_statuses()
418
+	{
419
+		$new_stati = array();
420
+		foreach ($this->_custom_stati as $status => $props) {
421
+			$new_stati[$status] = $props['label'];
422
+		}
423
+		return $new_stati;
424
+	}
425
+
426
+
427
+
428
+	/**
429
+	 * Creates a child of EE_CPT_Base given a WP_Post or array of wpdb results which
430
+	 * are a row from the posts table. If we're missing any fields required for the model,
431
+	 * we just fetch the entire entry from the DB (ie, if you want to use this to save DB queries,
432
+	 * make sure you are attaching all the model's fields onto the post)
433
+	 *
434
+	 * @param WP_Post|array $post
435
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
436
+	 */
437
+	public function instantiate_class_from_post_object_orig($post)
438
+	{
439
+		$post = (array)$post;
440
+		$has_all_necessary_fields_for_table = true;
441
+		//check if the post has fields on the meta table already
442
+		foreach ($this->_get_other_tables() as $table_obj) {
443
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
444
+			foreach ($fields_for_that_table as $field_obj) {
445
+				if ( ! isset($post[$field_obj->get_table_column()])
446
+					 && ! isset($post[$field_obj->get_qualified_column()])
447
+				) {
448
+					$has_all_necessary_fields_for_table = false;
449
+				}
450
+			}
451
+		}
452
+		//if we don't have all the fields we need, then just fetch the proper model from the DB
453
+		if ( ! $has_all_necessary_fields_for_table) {
454
+			return $this->get_one_by_ID($post['ID']);
455
+		} else {
456
+			return $this->instantiate_class_from_array_or_object($post);
457
+		}
458
+	}
459
+
460
+
461
+
462
+	/**
463
+	 * @param null $post
464
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class
465
+	 */
466
+	public function instantiate_class_from_post_object($post = null)
467
+	{
468
+		if (empty($post)) {
469
+			global $post;
470
+		}
471
+		$post = (array)$post;
472
+		$tables_needing_to_be_queried = array();
473
+		//check if the post has fields on the meta table already
474
+		foreach ($this->get_tables() as $table_obj) {
475
+			$fields_for_that_table = $this->_get_fields_for_table($table_obj->get_table_alias());
476
+			foreach ($fields_for_that_table as $field_obj) {
477
+				if ( ! isset($post[$field_obj->get_table_column()])
478
+					 && ! isset($post[$field_obj->get_qualified_column()])
479
+				) {
480
+					$tables_needing_to_be_queried[$table_obj->get_table_alias()] = $table_obj;
481
+				}
482
+			}
483
+		}
484
+		//if we don't have all the fields we need, then just fetch the proper model from the DB
485
+		if ($tables_needing_to_be_queried) {
486
+			if (count($tables_needing_to_be_queried) == 1
487
+				&& reset($tables_needing_to_be_queried)
488
+				   instanceof
489
+				   EE_Secondary_Table
490
+			) {
491
+				//so we're only missing data from a secondary table. Well that's not too hard to query for
492
+				$table_to_query = reset($tables_needing_to_be_queried);
493
+				$missing_data = $this->_do_wpdb_query('get_row', array(
494
+					'SELECT * FROM '
495
+					. $table_to_query->get_table_name()
496
+					. ' WHERE '
497
+					. $table_to_query->get_fk_on_table()
498
+					. ' = '
499
+					. $post['ID'],
500
+					ARRAY_A,
501
+				));
502
+				if ( ! empty($missing_data)) {
503
+					$post = array_merge($post, $missing_data);
504
+				}
505
+			} else {
506
+				return $this->get_one_by_ID($post['ID']);
507
+			}
508
+		}
509
+		return $this->instantiate_class_from_array_or_object($post);
510
+	}
511
+
512
+
513
+
514
+	/**
515
+	 * Gets the post type associated with this
516
+	 *
517
+	 * @throws EE_Error
518
+	 * @return string
519
+	 */
520
+	public function post_type()
521
+	{
522
+		$post_type_field = null;
523
+		foreach ($this->field_settings(true) as $field_obj) {
524
+			if ($field_obj instanceof EE_WP_Post_Type_Field) {
525
+				$post_type_field = $field_obj;
526
+				break;
527
+			}
528
+		}
529
+		if ($post_type_field == null) {
530
+			throw new EE_Error(sprintf(__("CPT Model %s should have a field of type EE_WP_Post_Type, but doesnt",
531
+				"event_espresso"), get_class($this)));
532
+		}
533
+		return $post_type_field->get_default_value();
534
+	}
535 535
 
536 536
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
         $parent_term_taxonomy_id = null
288 288
     ) {
289 289
         //create term
290
-        require_once(EE_MODELS . 'EEM_Term.model.php');
290
+        require_once(EE_MODELS.'EEM_Term.model.php');
291 291
         //first, check for a term by the same name or slug
292 292
         $category_slug = sanitize_title($category_name);
293 293
         $term = EEM_Term::instance()->get_one(array(
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
             $term->save();
307 307
         }
308 308
         //make sure there's a term-taxonomy entry too
309
-        require_once(EE_MODELS . 'EEM_Term_Taxonomy.model.php');
309
+        require_once(EE_MODELS.'EEM_Term_Taxonomy.model.php');
310 310
         $term_taxonomy = EEM_Term_Taxonomy::instance()->get_one(array(
311 311
             array(
312 312
                 'term_id'  => $term->ID(),
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
         //first the global filter
404 404
         $statuses = apply_filters('FHEE_EEM_CPT_Base__get_status_array', $statuses);
405 405
         //now the class specific filter
406
-        $statuses = apply_filters('FHEE_EEM_' . get_class($this) . '__get_status_array', $statuses);
406
+        $statuses = apply_filters('FHEE_EEM_'.get_class($this).'__get_status_array', $statuses);
407 407
         return $statuses;
408 408
     }
409 409
 
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
      */
437 437
     public function instantiate_class_from_post_object_orig($post)
438 438
     {
439
-        $post = (array)$post;
439
+        $post = (array) $post;
440 440
         $has_all_necessary_fields_for_table = true;
441 441
         //check if the post has fields on the meta table already
442 442
         foreach ($this->_get_other_tables() as $table_obj) {
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
         if (empty($post)) {
469 469
             global $post;
470 470
         }
471
-        $post = (array)$post;
471
+        $post = (array) $post;
472 472
         $tables_needing_to_be_queried = array();
473 473
         //check if the post has fields on the meta table already
474 474
         foreach ($this->get_tables() as $table_obj) {
Please login to merge, or discard this patch.
core/db_models/EEM_Venue.model.php 2 patches
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -25,87 +25,87 @@  discard block
 block discarded – undo
25 25
 class EEM_Venue extends EEM_CPT_Base
26 26
 {
27 27
 
28
-    // private instance of the Attendee object
29
-    protected static $_instance = null;
28
+	// private instance of the Attendee object
29
+	protected static $_instance = null;
30 30
 
31 31
 
32 32
 
33
-    protected function __construct($timezone = null)
34
-    {
35
-        $this->singular_item = __('Venue', 'event_espresso');
36
-        $this->plural_item = __('Venues', 'event_espresso');
37
-        $this->_tables = array(
38
-            'Venue_CPT'  => new EE_Primary_Table('posts', 'ID'),
39
-            'Venue_Meta' => new EE_Secondary_Table('esp_venue_meta', 'VNUM_ID', 'VNU_ID'),
40
-        );
41
-        $this->_fields = array(
42
-            'Venue_CPT'  => array(
43
-                'VNU_ID'         => new EE_Primary_Key_Int_Field('ID', __("Venue ID", "event_espresso")),
44
-                'VNU_name'       => new EE_Plain_Text_Field('post_title', __("Venue Name", "event_espresso"), false,
45
-                    ''),
46
-                'VNU_desc'       => new EE_Post_Content_Field('post_content', __("Venue Description", "event_espresso"),
47
-                    false, ''),
48
-                'VNU_identifier' => new EE_Slug_Field('post_name', __("Venue Identifier", "event_espresso"), false, ''),
49
-                'VNU_created'    => new EE_Datetime_Field('post_date', __("Date Venue Created", "event_espresso"),
50
-                    false, EE_Datetime_Field::now),
51
-                'VNU_short_desc' => new EE_Plain_Text_Field('post_excerpt',
52
-                    __("Short Description of Venue", "event_espresso"), true, ''),
53
-                'VNU_modified'   => new EE_Datetime_Field('post_modified', __("Venue Modified Date", "event_espresso"),
54
-                    false, EE_Datetime_Field::now),
55
-                'VNU_wp_user'    => new EE_WP_User_Field('post_author', __("Venue Creator ID", "event_espresso"),
56
-                    false),
57
-                'parent'         => new EE_Integer_Field('post_parent', __("Venue Parent ID", "event_espresso"), false,
58
-                    0),
59
-                'VNU_order'      => new EE_Integer_Field('menu_order', __("Venue order", "event_espresso"), false, 1),
60
-                'post_type'      => new EE_WP_Post_Type_Field('espresso_venues'),
61
-                // EE_Plain_Text_Field('post_type', __("Venue post type", "event_espresso"), false, 'espresso_venues'),
62
-            ),
63
-            'Venue_Meta' => array(
64
-                'VNUM_ID'             => new EE_DB_Only_Int_Field('VNUM_ID',
65
-                    __("ID of Venue Meta Row", "event_espresso"), false),
66
-                'VNU_ID_fk'           => new EE_DB_Only_Int_Field('VNU_ID',
67
-                    __("Foreign Key to Venue Post ", "event_espresso"), false),
68
-                'VNU_address'         => new EE_Plain_Text_Field('VNU_address',
69
-                    __("Venue Address line 1", "event_espresso"), true, ''),
70
-                'VNU_address2'        => new EE_Plain_Text_Field('VNU_address2',
71
-                    __("Venue Address line 2", "event_espresso"), true, ''),
72
-                'VNU_city'            => new EE_Plain_Text_Field('VNU_city', __("Venue City", "event_espresso"), true,
73
-                    ''),
74
-                'STA_ID'              => new EE_Foreign_Key_Int_Field('STA_ID', __("State ID", "event_espresso"), true,
75
-                    null, 'State'),
76
-                'CNT_ISO'             => new EE_Foreign_Key_String_Field('CNT_ISO',
77
-                    __("Country Code", "event_espresso"), true, null, 'Country'),
78
-                'VNU_zip'             => new EE_Plain_Text_Field('VNU_zip',
79
-                    __("Venue Zip/Postal Code", "event_espresso"), true),
80
-                'VNU_phone'           => new EE_Plain_Text_Field('VNU_phone', __("Venue Phone", "event_espresso"),
81
-                    true),
82
-                'VNU_capacity'        => new EE_Infinite_Integer_Field('VNU_capacity',
83
-                    __("Venue Capacity", "event_espresso"), true, EE_INF),
84
-                'VNU_url'             => new EE_Plain_Text_Field('VNU_url', __('Venue Website', 'event_espresso'),
85
-                    true),
86
-                'VNU_virtual_phone'   => new EE_Plain_Text_Field('VNU_virtual_phone',
87
-                    __('Call in Number', 'event_espresso'), true),
88
-                'VNU_virtual_url'     => new EE_Plain_Text_Field('VNU_virtual_url', __('Virtual URL', 'event_espresso'),
89
-                    true),
90
-                'VNU_google_map_link' => new EE_Plain_Text_Field('VNU_google_map_link',
91
-                    __('Google Map Link', 'event_espresso'), true),
92
-                'VNU_enable_for_gmap' => new EE_Boolean_Field('VNU_enable_for_gmap',
93
-                    __('Show Google Map?', 'event_espresso'), false, false),
94
-            ),
95
-        );
96
-        $this->_model_relations = array(
97
-            'Event'             => new EE_HABTM_Relation('Event_Venue'),
98
-            'State'             => new EE_Belongs_To_Relation(),
99
-            'Country'           => new EE_Belongs_To_Relation(),
100
-            'Event_Venue'       => new EE_Has_Many_Relation(),
101
-            'WP_User'           => new EE_Belongs_To_Relation(),
102
-            'Term_Relationship' => new EE_Has_Many_Relation(),
103
-            'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
104
-        );
105
-        //this model is generally available for reading
106
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
107
-        parent::__construct($timezone);
108
-    }
33
+	protected function __construct($timezone = null)
34
+	{
35
+		$this->singular_item = __('Venue', 'event_espresso');
36
+		$this->plural_item = __('Venues', 'event_espresso');
37
+		$this->_tables = array(
38
+			'Venue_CPT'  => new EE_Primary_Table('posts', 'ID'),
39
+			'Venue_Meta' => new EE_Secondary_Table('esp_venue_meta', 'VNUM_ID', 'VNU_ID'),
40
+		);
41
+		$this->_fields = array(
42
+			'Venue_CPT'  => array(
43
+				'VNU_ID'         => new EE_Primary_Key_Int_Field('ID', __("Venue ID", "event_espresso")),
44
+				'VNU_name'       => new EE_Plain_Text_Field('post_title', __("Venue Name", "event_espresso"), false,
45
+					''),
46
+				'VNU_desc'       => new EE_Post_Content_Field('post_content', __("Venue Description", "event_espresso"),
47
+					false, ''),
48
+				'VNU_identifier' => new EE_Slug_Field('post_name', __("Venue Identifier", "event_espresso"), false, ''),
49
+				'VNU_created'    => new EE_Datetime_Field('post_date', __("Date Venue Created", "event_espresso"),
50
+					false, EE_Datetime_Field::now),
51
+				'VNU_short_desc' => new EE_Plain_Text_Field('post_excerpt',
52
+					__("Short Description of Venue", "event_espresso"), true, ''),
53
+				'VNU_modified'   => new EE_Datetime_Field('post_modified', __("Venue Modified Date", "event_espresso"),
54
+					false, EE_Datetime_Field::now),
55
+				'VNU_wp_user'    => new EE_WP_User_Field('post_author', __("Venue Creator ID", "event_espresso"),
56
+					false),
57
+				'parent'         => new EE_Integer_Field('post_parent', __("Venue Parent ID", "event_espresso"), false,
58
+					0),
59
+				'VNU_order'      => new EE_Integer_Field('menu_order', __("Venue order", "event_espresso"), false, 1),
60
+				'post_type'      => new EE_WP_Post_Type_Field('espresso_venues'),
61
+				// EE_Plain_Text_Field('post_type', __("Venue post type", "event_espresso"), false, 'espresso_venues'),
62
+			),
63
+			'Venue_Meta' => array(
64
+				'VNUM_ID'             => new EE_DB_Only_Int_Field('VNUM_ID',
65
+					__("ID of Venue Meta Row", "event_espresso"), false),
66
+				'VNU_ID_fk'           => new EE_DB_Only_Int_Field('VNU_ID',
67
+					__("Foreign Key to Venue Post ", "event_espresso"), false),
68
+				'VNU_address'         => new EE_Plain_Text_Field('VNU_address',
69
+					__("Venue Address line 1", "event_espresso"), true, ''),
70
+				'VNU_address2'        => new EE_Plain_Text_Field('VNU_address2',
71
+					__("Venue Address line 2", "event_espresso"), true, ''),
72
+				'VNU_city'            => new EE_Plain_Text_Field('VNU_city', __("Venue City", "event_espresso"), true,
73
+					''),
74
+				'STA_ID'              => new EE_Foreign_Key_Int_Field('STA_ID', __("State ID", "event_espresso"), true,
75
+					null, 'State'),
76
+				'CNT_ISO'             => new EE_Foreign_Key_String_Field('CNT_ISO',
77
+					__("Country Code", "event_espresso"), true, null, 'Country'),
78
+				'VNU_zip'             => new EE_Plain_Text_Field('VNU_zip',
79
+					__("Venue Zip/Postal Code", "event_espresso"), true),
80
+				'VNU_phone'           => new EE_Plain_Text_Field('VNU_phone', __("Venue Phone", "event_espresso"),
81
+					true),
82
+				'VNU_capacity'        => new EE_Infinite_Integer_Field('VNU_capacity',
83
+					__("Venue Capacity", "event_espresso"), true, EE_INF),
84
+				'VNU_url'             => new EE_Plain_Text_Field('VNU_url', __('Venue Website', 'event_espresso'),
85
+					true),
86
+				'VNU_virtual_phone'   => new EE_Plain_Text_Field('VNU_virtual_phone',
87
+					__('Call in Number', 'event_espresso'), true),
88
+				'VNU_virtual_url'     => new EE_Plain_Text_Field('VNU_virtual_url', __('Virtual URL', 'event_espresso'),
89
+					true),
90
+				'VNU_google_map_link' => new EE_Plain_Text_Field('VNU_google_map_link',
91
+					__('Google Map Link', 'event_espresso'), true),
92
+				'VNU_enable_for_gmap' => new EE_Boolean_Field('VNU_enable_for_gmap',
93
+					__('Show Google Map?', 'event_espresso'), false, false),
94
+			),
95
+		);
96
+		$this->_model_relations = array(
97
+			'Event'             => new EE_HABTM_Relation('Event_Venue'),
98
+			'State'             => new EE_Belongs_To_Relation(),
99
+			'Country'           => new EE_Belongs_To_Relation(),
100
+			'Event_Venue'       => new EE_Has_Many_Relation(),
101
+			'WP_User'           => new EE_Belongs_To_Relation(),
102
+			'Term_Relationship' => new EE_Has_Many_Relation(),
103
+			'Term_Taxonomy'     => new EE_HABTM_Relation('Term_Relationship'),
104
+		);
105
+		//this model is generally available for reading
106
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
107
+		parent::__construct($timezone);
108
+	}
109 109
 
110 110
 }
111 111
 // End of file EEM_Venue.model.php
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@
 block discarded – undo
18 18
  * @author                Michael Nelson
19 19
  *                        ------------------------------------------------------------------------
20 20
  */
21
-require_once(EE_MODELS . 'EEM_Base.model.php');
21
+require_once(EE_MODELS.'EEM_Base.model.php');
22 22
 
23 23
 
24 24
 
Please login to merge, or discard this patch.
core/db_classes/EE_Message.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -697,7 +697,7 @@
 block discarded – undo
697 697
     /**
698 698
      * Gets any error message.
699 699
      *
700
-     * @return mixed|null
700
+     * @return string
701 701
      */
702 702
     public function error_message()
703 703
     {
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
      */
860 860
     public function set_messenger_is_executing()
861 861
     {
862
-        $this->set_STS_ID( EEM_Message::status_messenger_executing );
862
+        $this->set_STS_ID(EEM_Message::status_messenger_executing);
863 863
         $this->set_error_message(
864 864
             esc_html__(
865 865
                 'A message with this status indicates that there was a problem that occurred while the message was being
Please login to merge, or discard this patch.
Indentation   +860 added lines, -860 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -12,869 +12,869 @@  discard block
 block discarded – undo
12 12
 class EE_Message extends EE_Base_Class implements EEI_Admin_Links
13 13
 {
14 14
 
15
-    /**
16
-     * @deprecated 4.9.0  Added for backward compat with add-on's
17
-     * @type null
18
-     */
19
-    public $template_pack;
20
-
21
-    /**
22
-     * @deprecated 4.9.0 Added for backward compat with add-on's
23
-     * @type null
24
-     */
25
-    public $template_variation;
26
-
27
-    /**
28
-     * @deprecated 4.9.0 Added for backward compat with add-on's
29
-     * @type string
30
-     */
31
-    public $content = '';
32
-
33
-
34
-    /**
35
-     * @type EE_messenger $_messenger
36
-     */
37
-    protected $_messenger = null;
38
-
39
-    /**
40
-     * @type EE_message_type $_message_type
41
-     */
42
-    protected $_message_type = null;
43
-
44
-
45
-    /**
46
-     * @param array  $props_n_values
47
-     * @param string $timezone
48
-     * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
49
-     *                             format.
50
-     * @return EE_Message
51
-     */
52
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
53
-    {
54
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
55
-        //if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
56
-        if ( ! $has_object) {
57
-            EE_Registry::instance()->load_helper('URL');
58
-            $props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
59
-        }
60
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
61
-    }
62
-
63
-
64
-    /**
65
-     * @param array  $props_n_values
66
-     * @param string $timezone
67
-     * @return EE_Message
68
-     */
69
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
70
-    {
71
-        return new self($props_n_values, true, $timezone);
72
-    }
73
-
74
-
75
-    /**
76
-     * Gets MSG_token
77
-     *
78
-     * @return int
79
-     */
80
-    public function MSG_token()
81
-    {
82
-        return $this->get('MSG_token');
83
-    }
84
-
85
-
86
-    /**
87
-     * Sets MSG_token
88
-     *
89
-     * @param int $MSG_token
90
-     */
91
-    public function set_MSG_token($MSG_token)
92
-    {
93
-        $this->set('MSG_token', $MSG_token);
94
-    }
95
-
96
-
97
-    /**
98
-     * Gets GRP_ID
99
-     *
100
-     * @return int
101
-     */
102
-    public function GRP_ID()
103
-    {
104
-        return $this->get('GRP_ID');
105
-    }
106
-
107
-
108
-    /**
109
-     * Sets GRP_ID
110
-     *
111
-     * @param int $GRP_ID
112
-     */
113
-    public function set_GRP_ID($GRP_ID)
114
-    {
115
-        $this->set('GRP_ID', $GRP_ID);
116
-    }
117
-
118
-
119
-    /**
120
-     * Gets TXN_ID
121
-     *
122
-     * @return int
123
-     */
124
-    public function TXN_ID()
125
-    {
126
-        return $this->get('TXN_ID');
127
-    }
128
-
129
-
130
-    /**
131
-     * Sets TXN_ID
132
-     *
133
-     * @param int $TXN_ID
134
-     */
135
-    public function set_TXN_ID($TXN_ID)
136
-    {
137
-        $this->set('TXN_ID', $TXN_ID);
138
-    }
139
-
140
-
141
-    /**
142
-     * Gets messenger
143
-     *
144
-     * @return string
145
-     */
146
-    public function messenger()
147
-    {
148
-        return $this->get('MSG_messenger');
149
-    }
150
-
151
-
152
-    /**
153
-     * Sets messenger
154
-     *
155
-     * @param string $messenger
156
-     */
157
-    public function set_messenger($messenger)
158
-    {
159
-        $this->set('MSG_messenger', $messenger);
160
-    }
161
-
162
-
163
-    /**
164
-     * Returns corresponding messenger object for the set messenger on this message
165
-     *
166
-     * @return EE_messenger | null
167
-     */
168
-    public function messenger_object()
169
-    {
170
-        return $this->_messenger;
171
-    }
172
-
173
-
174
-    /**
175
-     * Sets messenger
176
-     *
177
-     * @param EE_messenger $messenger
178
-     */
179
-    public function set_messenger_object(EE_messenger $messenger)
180
-    {
181
-        $this->_messenger = $messenger;
182
-    }
183
-
184
-
185
-    /**
186
-     * validates messenger
187
-     *
188
-     * @param bool $throw_exceptions
189
-     * @return bool
190
-     * @throws \EE_Error
191
-     */
192
-    public function valid_messenger($throw_exceptions = false)
193
-    {
194
-        if ($this->_messenger instanceof EE_messenger) {
195
-            return true;
196
-        }
197
-        if ($throw_exceptions) {
198
-            throw new EE_Error(
199
-                sprintf(
200
-                    __(
201
-                        'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
202
-                        'event_espresso'
203
-                    ),
204
-                    $this->messenger()
205
-                )
206
-            );
207
-        }
208
-        return false;
209
-    }
210
-
211
-
212
-    /**
213
-     * This returns the set localized label for the messenger on this message.
214
-     * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
215
-     * with this message.
216
-     *
217
-     * @param   bool $plural whether to return the plural label or not.
218
-     * @return string
219
-     */
220
-    public function messenger_label($plural = false)
221
-    {
222
-        $label_type = $plural ? 'plural' : 'singular';
223
-        $messenger  = $this->messenger_object();
224
-        return $messenger instanceof EE_messenger ? $messenger->label[$label_type] : $this->messenger();
225
-    }
226
-
227
-
228
-    /**
229
-     * Gets message_type
230
-     *
231
-     * @return string
232
-     */
233
-    public function message_type()
234
-    {
235
-        return $this->get('MSG_message_type');
236
-    }
237
-
238
-
239
-    /**
240
-     * Sets message_type
241
-     *
242
-     * @param string $message_type
243
-     */
244
-    public function set_message_type($message_type)
245
-    {
246
-        $this->set('MSG_message_type', $message_type);
247
-    }
248
-
249
-
250
-    /**
251
-     * Returns the message type object for the set message type on this message
252
-     *
253
-     * @return EE_message_type | null
254
-     */
255
-    public function message_type_object()
256
-    {
257
-        return $this->_message_type;
258
-    }
259
-
260
-
261
-    /**
262
-     * Sets message_type
263
-     *
264
-     * @param EE_message_type $message_type
265
-     * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
266
-     *                                        the message type or not.
267
-     */
268
-    public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
269
-    {
270
-        $this->_message_type = $message_type;
271
-        if ($set_priority) {
272
-            $this->set_priority($this->_message_type->get_priority());
273
-        }
274
-    }
275
-
276
-
277
-    /**
278
-     * validates message_type
279
-     *
280
-     * @param bool $throw_exceptions
281
-     * @return bool
282
-     * @throws \EE_Error
283
-     */
284
-    public function valid_message_type($throw_exceptions = false)
285
-    {
286
-        if ($this->_message_type instanceof EE_message_type) {
287
-            return true;
288
-        }
289
-        if ($throw_exceptions) {
290
-            throw new EE_Error(
291
-                sprintf(
292
-                    __(
293
-                        'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
294
-                        'event_espresso'
295
-                    ),
296
-                    $this->message_type()
297
-                )
298
-            );
299
-        }
300
-        return false;
301
-    }
302
-
303
-
304
-    /**
305
-     * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
306
-     *
307
-     * @param bool $throw_exceptions
308
-     * @return bool
309
-     * @throws \EE_Error
310
-     */
311
-    public function is_valid($throw_exceptions = false)
312
-    {
313
-        if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
314
-            return true;
315
-        }
316
-        return false;
317
-    }
318
-
319
-
320
-    /**
321
-     * This validates whether the internal messenger and message type objects are valid for sending.
322
-     * Three checks are done:
323
-     * 1. There is a valid messenger object.
324
-     * 2. There is a valid message type object.
325
-     * 3. The message type object is active for the messenger.
326
-     *
327
-     * @throws EE_Error  But only if $throw_exceptions is set to true.
328
-     * @param bool $throw_exceptions
329
-     * @return bool
330
-     */
331
-    public function is_valid_for_sending_or_generation($throw_exceptions = false)
332
-    {
333
-        $valid = false;
334
-        if ($this->is_valid($throw_exceptions)) {
335
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
336
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
337
-            $valid                    = $message_resource_manager->is_message_type_active_for_messenger($this->messenger(),
338
-                $this->message_type());
339
-            if ( ! $valid && $throw_exceptions) {
340
-                throw new EE_Error(
341
-                    sprintf(
342
-                        __('The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
343
-                            'event_espresso'),
344
-                        $this->message_type(),
345
-                        $this->messenger()
346
-                    )
347
-                );
348
-            }
349
-        }
350
-        return $valid;
351
-    }
352
-
353
-
354
-    /**
355
-     * This returns the set localized label for the message type on this message.
356
-     * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
357
-     * with this message.
358
-     *
359
-     * @param   bool $plural whether to return the plural label or not.
360
-     * @return string
361
-     */
362
-    public function message_type_label($plural = false)
363
-    {
364
-        $label_type   = $plural ? 'plural' : 'singular';
365
-        $message_type = $this->message_type_object();
366
-        return $message_type instanceof EE_message_type ? $message_type->label[$label_type] : str_replace(
367
-            '_',
368
-            ' ',
369
-            $this->message_type()
370
-        );
371
-    }
372
-
373
-
374
-    /**
375
-     * Gets context
376
-     *
377
-     * @return string
378
-     */
379
-    public function context()
380
-    {
381
-        return $this->get('MSG_context');
382
-    }
383
-
384
-
385
-    /**
386
-     * This returns the corresponding localized label for the given context slug, if possible from installed message
387
-     * types. Otherwise, this will just return the set context slug on this object.
388
-     *
389
-     * @return string
390
-     */
391
-    public function context_label()
392
-    {
393
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
394
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
395
-        $contexts                 = $message_resource_manager->get_all_contexts();
396
-        return isset($contexts[$this->context()]) ? $contexts[$this->context()] : $this->context();
397
-    }
398
-
399
-
400
-    /**
401
-     * Sets context
402
-     *
403
-     * @param string $context
404
-     */
405
-    public function set_context($context)
406
-    {
407
-        $this->set('MSG_context', $context);
408
-    }
409
-
410
-
411
-    /**
412
-     * Gets recipient_ID
413
-     *
414
-     * @return int
415
-     */
416
-    public function recipient_ID()
417
-    {
418
-        return $this->get('MSG_recipient_ID');
419
-    }
420
-
421
-
422
-    /**
423
-     * Sets recipient_ID
424
-     *
425
-     * @param string $recipient_ID
426
-     */
427
-    public function set_recipient_ID($recipient_ID)
428
-    {
429
-        $this->set('MSG_recipient_ID', $recipient_ID);
430
-    }
431
-
432
-
433
-    /**
434
-     * Gets recipient_type
435
-     *
436
-     * @return string
437
-     */
438
-    public function recipient_type()
439
-    {
440
-        return $this->get('MSG_recipient_type');
441
-    }
442
-
443
-
444
-    /**
445
-     * Return the related object matching the recipient type and ID.
446
-     *
447
-     * @return EE_Base_Class | null
448
-     */
449
-    public function recipient_object()
450
-    {
451
-        if ( ! $this->recipient_type() || ! $this->recipient_ID()) {
452
-            return null;
453
-        }
454
-
455
-        return $this->get_first_related($this->recipient_type());
456
-    }
457
-
458
-
459
-    /**
460
-     * Sets recipient_type
461
-     *
462
-     * @param string $recipient_type
463
-     */
464
-    public function set_recipient_type($recipient_type)
465
-    {
466
-        $this->set('MSG_recipient_type', $recipient_type);
467
-    }
468
-
469
-
470
-    /**
471
-     * Gets content
472
-     *
473
-     * @return string
474
-     */
475
-    public function content()
476
-    {
477
-        return $this->get('MSG_content');
478
-    }
479
-
480
-
481
-    /**
482
-     * Sets content
483
-     *
484
-     * @param string $content
485
-     */
486
-    public function set_content($content)
487
-    {
488
-        $this->set('MSG_content', $content);
489
-    }
490
-
491
-
492
-    /**
493
-     * Gets subject
494
-     *
495
-     * @return string
496
-     */
497
-    public function subject()
498
-    {
499
-        return $this->get('MSG_subject');
500
-    }
501
-
502
-
503
-    /**
504
-     * Sets subject
505
-     *
506
-     * @param string $subject
507
-     */
508
-    public function set_subject($subject)
509
-    {
510
-        $this->set('MSG_subject', $subject);
511
-    }
512
-
513
-
514
-    /**
515
-     * Gets to
516
-     *
517
-     * @return string
518
-     */
519
-    public function to()
520
-    {
521
-        $to = $this->get('MSG_to');
522
-        return empty($to) ? __('No recipient', 'event_espresso') : $to;
523
-    }
524
-
525
-
526
-    /**
527
-     * Sets to
528
-     *
529
-     * @param string $to
530
-     */
531
-    public function set_to($to)
532
-    {
533
-        $this->set('MSG_to', $to);
534
-    }
535
-
536
-
537
-    /**
538
-     * Gets from
539
-     *
540
-     * @return string
541
-     */
542
-    public function from()
543
-    {
544
-        return $this->get('MSG_from');
545
-    }
546
-
547
-
548
-    /**
549
-     * Sets from
550
-     *
551
-     * @param string $from
552
-     */
553
-    public function set_from($from)
554
-    {
555
-        $this->set('MSG_from', $from);
556
-    }
557
-
558
-
559
-    /**
560
-     * Gets priority
561
-     *
562
-     * @return int
563
-     */
564
-    public function priority()
565
-    {
566
-        return $this->get('MSG_priority');
567
-    }
568
-
569
-
570
-    /**
571
-     * Sets priority
572
-     * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
573
-     * this method calls the send_now method to verify that.
574
-     *
575
-     * @param int $priority
576
-     */
577
-    public function set_priority($priority)
578
-    {
579
-        $priority = $this->send_now() ? EEM_Message::priority_high : $priority;
580
-        parent::set('MSG_priority', $priority);
581
-    }
582
-
583
-
584
-    /**
585
-     * Overrides parent::set method so we can capture any sets for priority.
586
-     *
587
-     * @see parent::set() for phpdocs
588
-     * @param string $field_name
589
-     * @param mixed  $field_value
590
-     * @param bool   $use_default
591
-     * @throws EE_Error
592
-     */
593
-    public function set($field_name, $field_value, $use_default = false)
594
-    {
595
-        if ($field_name === 'MSG_priority') {
596
-            $this->set_priority($field_value);
597
-        }
598
-        parent::set($field_name, $field_value, $use_default);
599
-    }
600
-
601
-
602
-    /**
603
-     * @return bool
604
-     * @throws \EE_Error
605
-     */
606
-    public function send_now()
607
-    {
608
-        $send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high : $this->priority();
609
-        return $send_now === EEM_Message::priority_high ? true : false;
610
-    }
611
-
612
-
613
-    /**
614
-     * Gets STS_ID
615
-     *
616
-     * @return string
617
-     */
618
-    public function STS_ID()
619
-    {
620
-        return $this->get('STS_ID');
621
-    }
622
-
623
-
624
-    /**
625
-     * Sets STS_ID
626
-     *
627
-     * @param string $STS_ID
628
-     */
629
-    public function set_STS_ID($STS_ID)
630
-    {
631
-        $this->set('STS_ID', $STS_ID);
632
-    }
633
-
634
-
635
-    /**
636
-     * Gets created
637
-     *
638
-     * @return string
639
-     */
640
-    public function created()
641
-    {
642
-        return $this->get('MSG_created');
643
-    }
644
-
645
-
646
-    /**
647
-     * Sets created
648
-     *
649
-     * @param string $created
650
-     */
651
-    public function set_created($created)
652
-    {
653
-        $this->set('MSG_created', $created);
654
-    }
655
-
656
-
657
-    /**
658
-     * Gets modified
659
-     *
660
-     * @return string
661
-     */
662
-    public function modified()
663
-    {
664
-        return $this->get('MSG_modified');
665
-    }
666
-
667
-
668
-    /**
669
-     * Sets modified
670
-     *
671
-     * @param string $modified
672
-     */
673
-    public function set_modified($modified)
674
-    {
675
-        $this->set('MSG_modified', $modified);
676
-    }
677
-
678
-
679
-    /**
680
-     * Sets generation data for this message.
681
-     *
682
-     * @param mixed $data
683
-     */
684
-    public function set_generation_data($data)
685
-    {
686
-        $this->set_field_or_extra_meta('MSG_generation_data', $data);
687
-    }
688
-
689
-
690
-    /**
691
-     * Returns any set generation data for this message.
692
-     *
693
-     * @return mixed|null
694
-     */
695
-    public function get_generation_data()
696
-    {
697
-        return $this->get_field_or_extra_meta('MSG_generation_data');
698
-    }
699
-
700
-
701
-    /**
702
-     * Gets any error message.
703
-     *
704
-     * @return mixed|null
705
-     */
706
-    public function error_message()
707
-    {
708
-        return $this->get_field_or_extra_meta('MSG_error');
709
-    }
710
-
711
-
712
-    /**
713
-     * Sets an error message.
714
-     *
715
-     * @param $message
716
-     * @return bool|int
717
-     */
718
-    public function set_error_message($message)
719
-    {
720
-        return $this->set_field_or_extra_meta('MSG_error', $message);
721
-    }
722
-
723
-
724
-    /**
725
-     * This retrieves the associated template pack with this message.
726
-     *
727
-     * @return EE_Messages_Template_Pack | null
728
-     */
729
-    public function get_template_pack()
730
-    {
731
-        /**
732
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
733
-         */
734
-        if ( ! empty($this->template_pack)) {
735
-            return $this->template_pack;
736
-        }
737
-        /** @type EE_Message_Template_Group $grp */
738
-        $grp = $this->get_first_related('Message_Template_Group');
739
-        //if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
740
-        if ( ! $grp instanceof EE_Message_Template_Group) {
741
-            $grp = EEM_Message_Template_Group::instance()->get_one(
742
-                array(
743
-                    array(
744
-                        'MTP_messenger'    => $this->messenger(),
745
-                        'MTP_message_type' => $this->message_type(),
746
-                        'MTP_is_global'    => true,
747
-                    ),
748
-                )
749
-            );
750
-        }
751
-
752
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
753
-    }
754
-
755
-
756
-    /**
757
-     * Retrieves the variation used for generating this message.
758
-     *
759
-     * @return string
760
-     */
761
-    public function get_template_pack_variation()
762
-    {
763
-        /**
764
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
765
-         */
766
-        if ( ! empty($this->template_variation)) {
767
-            return $this->template_variation;
768
-        }
769
-
770
-        /** @type EE_Message_Template_Group $grp */
771
-        $grp = $this->get_first_related('Message_Template_Group');
772
-
773
-        //if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
774
-        if ( ! $grp instanceof EE_Message_Template_Group) {
775
-            $grp = EEM_Message_Template_Group::instance()->get_one(
776
-                array(
777
-                    array(
778
-                        'MTP_messenger'    => $this->messenger(),
779
-                        'MTP_message_type' => $this->message_type(),
780
-                        'MTP_is_global'    => true,
781
-                    ),
782
-                )
783
-            );
784
-        }
785
-
786
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
787
-    }
788
-
789
-    /**
790
-     * Return the link to the admin details for the object.
791
-     *
792
-     * @return string
793
-     */
794
-    public function get_admin_details_link()
795
-    {
796
-        EE_Registry::instance()->load_helper('URL');
797
-        EE_Registry::instance()->load_helper('MSG_Template');
798
-        switch ($this->STS_ID()) {
799
-            case EEM_Message::status_failed :
800
-            case EEM_Message::status_debug_only :
801
-                return EEH_MSG_Template::generate_error_display_trigger($this);
802
-                break;
803
-
804
-            case EEM_Message::status_sent :
805
-                return EEH_MSG_Template::generate_browser_trigger($this);
806
-                break;
807
-
808
-            default :
809
-                return '';
810
-        }
811
-    }
812
-
813
-    /**
814
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
815
-     *
816
-     * @return string
817
-     */
818
-    public function get_admin_edit_link()
819
-    {
820
-        return $this->get_admin_details_link();
821
-    }
822
-
823
-    /**
824
-     * Returns the link to a settings page for the object.
825
-     *
826
-     * @return string
827
-     */
828
-    public function get_admin_settings_link()
829
-    {
830
-        EE_Registry::instance()->load_helper('URL');
831
-        return EEH_URL::add_query_args_and_nonce(
832
-            array(
833
-                'page'   => 'espresso_messages',
834
-                'action' => 'settings',
835
-            ),
836
-            admin_url('admin.php')
837
-        );
838
-    }
839
-
840
-    /**
841
-     * Returns the link to the "overview" for the object (typically the "list table" view).
842
-     *
843
-     * @return string
844
-     */
845
-    public function get_admin_overview_link()
846
-    {
847
-        EE_Registry::instance()->load_helper('URL');
848
-        return EEH_URL::add_query_args_and_nonce(
849
-            array(
850
-                'page'   => 'espresso_messages',
851
-                'action' => 'default',
852
-            ),
853
-            admin_url('admin.php')
854
-        );
855
-    }
856
-
857
-
858
-    /**
859
-     * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
860
-     * it.
861
-     * Note this also SAVES the current message object to the db because it adds an error message to accompany the status.
862
-     *
863
-     */
864
-    public function set_messenger_is_executing()
865
-    {
866
-        $this->set_STS_ID( EEM_Message::status_messenger_executing );
867
-        $this->set_error_message(
868
-            esc_html__(
869
-                'A message with this status indicates that there was a problem that occurred while the message was being
15
+	/**
16
+	 * @deprecated 4.9.0  Added for backward compat with add-on's
17
+	 * @type null
18
+	 */
19
+	public $template_pack;
20
+
21
+	/**
22
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
23
+	 * @type null
24
+	 */
25
+	public $template_variation;
26
+
27
+	/**
28
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
29
+	 * @type string
30
+	 */
31
+	public $content = '';
32
+
33
+
34
+	/**
35
+	 * @type EE_messenger $_messenger
36
+	 */
37
+	protected $_messenger = null;
38
+
39
+	/**
40
+	 * @type EE_message_type $_message_type
41
+	 */
42
+	protected $_message_type = null;
43
+
44
+
45
+	/**
46
+	 * @param array  $props_n_values
47
+	 * @param string $timezone
48
+	 * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
49
+	 *                             format.
50
+	 * @return EE_Message
51
+	 */
52
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
53
+	{
54
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
55
+		//if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
56
+		if ( ! $has_object) {
57
+			EE_Registry::instance()->load_helper('URL');
58
+			$props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
59
+		}
60
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
61
+	}
62
+
63
+
64
+	/**
65
+	 * @param array  $props_n_values
66
+	 * @param string $timezone
67
+	 * @return EE_Message
68
+	 */
69
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
70
+	{
71
+		return new self($props_n_values, true, $timezone);
72
+	}
73
+
74
+
75
+	/**
76
+	 * Gets MSG_token
77
+	 *
78
+	 * @return int
79
+	 */
80
+	public function MSG_token()
81
+	{
82
+		return $this->get('MSG_token');
83
+	}
84
+
85
+
86
+	/**
87
+	 * Sets MSG_token
88
+	 *
89
+	 * @param int $MSG_token
90
+	 */
91
+	public function set_MSG_token($MSG_token)
92
+	{
93
+		$this->set('MSG_token', $MSG_token);
94
+	}
95
+
96
+
97
+	/**
98
+	 * Gets GRP_ID
99
+	 *
100
+	 * @return int
101
+	 */
102
+	public function GRP_ID()
103
+	{
104
+		return $this->get('GRP_ID');
105
+	}
106
+
107
+
108
+	/**
109
+	 * Sets GRP_ID
110
+	 *
111
+	 * @param int $GRP_ID
112
+	 */
113
+	public function set_GRP_ID($GRP_ID)
114
+	{
115
+		$this->set('GRP_ID', $GRP_ID);
116
+	}
117
+
118
+
119
+	/**
120
+	 * Gets TXN_ID
121
+	 *
122
+	 * @return int
123
+	 */
124
+	public function TXN_ID()
125
+	{
126
+		return $this->get('TXN_ID');
127
+	}
128
+
129
+
130
+	/**
131
+	 * Sets TXN_ID
132
+	 *
133
+	 * @param int $TXN_ID
134
+	 */
135
+	public function set_TXN_ID($TXN_ID)
136
+	{
137
+		$this->set('TXN_ID', $TXN_ID);
138
+	}
139
+
140
+
141
+	/**
142
+	 * Gets messenger
143
+	 *
144
+	 * @return string
145
+	 */
146
+	public function messenger()
147
+	{
148
+		return $this->get('MSG_messenger');
149
+	}
150
+
151
+
152
+	/**
153
+	 * Sets messenger
154
+	 *
155
+	 * @param string $messenger
156
+	 */
157
+	public function set_messenger($messenger)
158
+	{
159
+		$this->set('MSG_messenger', $messenger);
160
+	}
161
+
162
+
163
+	/**
164
+	 * Returns corresponding messenger object for the set messenger on this message
165
+	 *
166
+	 * @return EE_messenger | null
167
+	 */
168
+	public function messenger_object()
169
+	{
170
+		return $this->_messenger;
171
+	}
172
+
173
+
174
+	/**
175
+	 * Sets messenger
176
+	 *
177
+	 * @param EE_messenger $messenger
178
+	 */
179
+	public function set_messenger_object(EE_messenger $messenger)
180
+	{
181
+		$this->_messenger = $messenger;
182
+	}
183
+
184
+
185
+	/**
186
+	 * validates messenger
187
+	 *
188
+	 * @param bool $throw_exceptions
189
+	 * @return bool
190
+	 * @throws \EE_Error
191
+	 */
192
+	public function valid_messenger($throw_exceptions = false)
193
+	{
194
+		if ($this->_messenger instanceof EE_messenger) {
195
+			return true;
196
+		}
197
+		if ($throw_exceptions) {
198
+			throw new EE_Error(
199
+				sprintf(
200
+					__(
201
+						'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
202
+						'event_espresso'
203
+					),
204
+					$this->messenger()
205
+				)
206
+			);
207
+		}
208
+		return false;
209
+	}
210
+
211
+
212
+	/**
213
+	 * This returns the set localized label for the messenger on this message.
214
+	 * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
215
+	 * with this message.
216
+	 *
217
+	 * @param   bool $plural whether to return the plural label or not.
218
+	 * @return string
219
+	 */
220
+	public function messenger_label($plural = false)
221
+	{
222
+		$label_type = $plural ? 'plural' : 'singular';
223
+		$messenger  = $this->messenger_object();
224
+		return $messenger instanceof EE_messenger ? $messenger->label[$label_type] : $this->messenger();
225
+	}
226
+
227
+
228
+	/**
229
+	 * Gets message_type
230
+	 *
231
+	 * @return string
232
+	 */
233
+	public function message_type()
234
+	{
235
+		return $this->get('MSG_message_type');
236
+	}
237
+
238
+
239
+	/**
240
+	 * Sets message_type
241
+	 *
242
+	 * @param string $message_type
243
+	 */
244
+	public function set_message_type($message_type)
245
+	{
246
+		$this->set('MSG_message_type', $message_type);
247
+	}
248
+
249
+
250
+	/**
251
+	 * Returns the message type object for the set message type on this message
252
+	 *
253
+	 * @return EE_message_type | null
254
+	 */
255
+	public function message_type_object()
256
+	{
257
+		return $this->_message_type;
258
+	}
259
+
260
+
261
+	/**
262
+	 * Sets message_type
263
+	 *
264
+	 * @param EE_message_type $message_type
265
+	 * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
266
+	 *                                        the message type or not.
267
+	 */
268
+	public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
269
+	{
270
+		$this->_message_type = $message_type;
271
+		if ($set_priority) {
272
+			$this->set_priority($this->_message_type->get_priority());
273
+		}
274
+	}
275
+
276
+
277
+	/**
278
+	 * validates message_type
279
+	 *
280
+	 * @param bool $throw_exceptions
281
+	 * @return bool
282
+	 * @throws \EE_Error
283
+	 */
284
+	public function valid_message_type($throw_exceptions = false)
285
+	{
286
+		if ($this->_message_type instanceof EE_message_type) {
287
+			return true;
288
+		}
289
+		if ($throw_exceptions) {
290
+			throw new EE_Error(
291
+				sprintf(
292
+					__(
293
+						'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
294
+						'event_espresso'
295
+					),
296
+					$this->message_type()
297
+				)
298
+			);
299
+		}
300
+		return false;
301
+	}
302
+
303
+
304
+	/**
305
+	 * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
306
+	 *
307
+	 * @param bool $throw_exceptions
308
+	 * @return bool
309
+	 * @throws \EE_Error
310
+	 */
311
+	public function is_valid($throw_exceptions = false)
312
+	{
313
+		if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
314
+			return true;
315
+		}
316
+		return false;
317
+	}
318
+
319
+
320
+	/**
321
+	 * This validates whether the internal messenger and message type objects are valid for sending.
322
+	 * Three checks are done:
323
+	 * 1. There is a valid messenger object.
324
+	 * 2. There is a valid message type object.
325
+	 * 3. The message type object is active for the messenger.
326
+	 *
327
+	 * @throws EE_Error  But only if $throw_exceptions is set to true.
328
+	 * @param bool $throw_exceptions
329
+	 * @return bool
330
+	 */
331
+	public function is_valid_for_sending_or_generation($throw_exceptions = false)
332
+	{
333
+		$valid = false;
334
+		if ($this->is_valid($throw_exceptions)) {
335
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
336
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
337
+			$valid                    = $message_resource_manager->is_message_type_active_for_messenger($this->messenger(),
338
+				$this->message_type());
339
+			if ( ! $valid && $throw_exceptions) {
340
+				throw new EE_Error(
341
+					sprintf(
342
+						__('The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
343
+							'event_espresso'),
344
+						$this->message_type(),
345
+						$this->messenger()
346
+					)
347
+				);
348
+			}
349
+		}
350
+		return $valid;
351
+	}
352
+
353
+
354
+	/**
355
+	 * This returns the set localized label for the message type on this message.
356
+	 * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
357
+	 * with this message.
358
+	 *
359
+	 * @param   bool $plural whether to return the plural label or not.
360
+	 * @return string
361
+	 */
362
+	public function message_type_label($plural = false)
363
+	{
364
+		$label_type   = $plural ? 'plural' : 'singular';
365
+		$message_type = $this->message_type_object();
366
+		return $message_type instanceof EE_message_type ? $message_type->label[$label_type] : str_replace(
367
+			'_',
368
+			' ',
369
+			$this->message_type()
370
+		);
371
+	}
372
+
373
+
374
+	/**
375
+	 * Gets context
376
+	 *
377
+	 * @return string
378
+	 */
379
+	public function context()
380
+	{
381
+		return $this->get('MSG_context');
382
+	}
383
+
384
+
385
+	/**
386
+	 * This returns the corresponding localized label for the given context slug, if possible from installed message
387
+	 * types. Otherwise, this will just return the set context slug on this object.
388
+	 *
389
+	 * @return string
390
+	 */
391
+	public function context_label()
392
+	{
393
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
394
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
395
+		$contexts                 = $message_resource_manager->get_all_contexts();
396
+		return isset($contexts[$this->context()]) ? $contexts[$this->context()] : $this->context();
397
+	}
398
+
399
+
400
+	/**
401
+	 * Sets context
402
+	 *
403
+	 * @param string $context
404
+	 */
405
+	public function set_context($context)
406
+	{
407
+		$this->set('MSG_context', $context);
408
+	}
409
+
410
+
411
+	/**
412
+	 * Gets recipient_ID
413
+	 *
414
+	 * @return int
415
+	 */
416
+	public function recipient_ID()
417
+	{
418
+		return $this->get('MSG_recipient_ID');
419
+	}
420
+
421
+
422
+	/**
423
+	 * Sets recipient_ID
424
+	 *
425
+	 * @param string $recipient_ID
426
+	 */
427
+	public function set_recipient_ID($recipient_ID)
428
+	{
429
+		$this->set('MSG_recipient_ID', $recipient_ID);
430
+	}
431
+
432
+
433
+	/**
434
+	 * Gets recipient_type
435
+	 *
436
+	 * @return string
437
+	 */
438
+	public function recipient_type()
439
+	{
440
+		return $this->get('MSG_recipient_type');
441
+	}
442
+
443
+
444
+	/**
445
+	 * Return the related object matching the recipient type and ID.
446
+	 *
447
+	 * @return EE_Base_Class | null
448
+	 */
449
+	public function recipient_object()
450
+	{
451
+		if ( ! $this->recipient_type() || ! $this->recipient_ID()) {
452
+			return null;
453
+		}
454
+
455
+		return $this->get_first_related($this->recipient_type());
456
+	}
457
+
458
+
459
+	/**
460
+	 * Sets recipient_type
461
+	 *
462
+	 * @param string $recipient_type
463
+	 */
464
+	public function set_recipient_type($recipient_type)
465
+	{
466
+		$this->set('MSG_recipient_type', $recipient_type);
467
+	}
468
+
469
+
470
+	/**
471
+	 * Gets content
472
+	 *
473
+	 * @return string
474
+	 */
475
+	public function content()
476
+	{
477
+		return $this->get('MSG_content');
478
+	}
479
+
480
+
481
+	/**
482
+	 * Sets content
483
+	 *
484
+	 * @param string $content
485
+	 */
486
+	public function set_content($content)
487
+	{
488
+		$this->set('MSG_content', $content);
489
+	}
490
+
491
+
492
+	/**
493
+	 * Gets subject
494
+	 *
495
+	 * @return string
496
+	 */
497
+	public function subject()
498
+	{
499
+		return $this->get('MSG_subject');
500
+	}
501
+
502
+
503
+	/**
504
+	 * Sets subject
505
+	 *
506
+	 * @param string $subject
507
+	 */
508
+	public function set_subject($subject)
509
+	{
510
+		$this->set('MSG_subject', $subject);
511
+	}
512
+
513
+
514
+	/**
515
+	 * Gets to
516
+	 *
517
+	 * @return string
518
+	 */
519
+	public function to()
520
+	{
521
+		$to = $this->get('MSG_to');
522
+		return empty($to) ? __('No recipient', 'event_espresso') : $to;
523
+	}
524
+
525
+
526
+	/**
527
+	 * Sets to
528
+	 *
529
+	 * @param string $to
530
+	 */
531
+	public function set_to($to)
532
+	{
533
+		$this->set('MSG_to', $to);
534
+	}
535
+
536
+
537
+	/**
538
+	 * Gets from
539
+	 *
540
+	 * @return string
541
+	 */
542
+	public function from()
543
+	{
544
+		return $this->get('MSG_from');
545
+	}
546
+
547
+
548
+	/**
549
+	 * Sets from
550
+	 *
551
+	 * @param string $from
552
+	 */
553
+	public function set_from($from)
554
+	{
555
+		$this->set('MSG_from', $from);
556
+	}
557
+
558
+
559
+	/**
560
+	 * Gets priority
561
+	 *
562
+	 * @return int
563
+	 */
564
+	public function priority()
565
+	{
566
+		return $this->get('MSG_priority');
567
+	}
568
+
569
+
570
+	/**
571
+	 * Sets priority
572
+	 * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
573
+	 * this method calls the send_now method to verify that.
574
+	 *
575
+	 * @param int $priority
576
+	 */
577
+	public function set_priority($priority)
578
+	{
579
+		$priority = $this->send_now() ? EEM_Message::priority_high : $priority;
580
+		parent::set('MSG_priority', $priority);
581
+	}
582
+
583
+
584
+	/**
585
+	 * Overrides parent::set method so we can capture any sets for priority.
586
+	 *
587
+	 * @see parent::set() for phpdocs
588
+	 * @param string $field_name
589
+	 * @param mixed  $field_value
590
+	 * @param bool   $use_default
591
+	 * @throws EE_Error
592
+	 */
593
+	public function set($field_name, $field_value, $use_default = false)
594
+	{
595
+		if ($field_name === 'MSG_priority') {
596
+			$this->set_priority($field_value);
597
+		}
598
+		parent::set($field_name, $field_value, $use_default);
599
+	}
600
+
601
+
602
+	/**
603
+	 * @return bool
604
+	 * @throws \EE_Error
605
+	 */
606
+	public function send_now()
607
+	{
608
+		$send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high : $this->priority();
609
+		return $send_now === EEM_Message::priority_high ? true : false;
610
+	}
611
+
612
+
613
+	/**
614
+	 * Gets STS_ID
615
+	 *
616
+	 * @return string
617
+	 */
618
+	public function STS_ID()
619
+	{
620
+		return $this->get('STS_ID');
621
+	}
622
+
623
+
624
+	/**
625
+	 * Sets STS_ID
626
+	 *
627
+	 * @param string $STS_ID
628
+	 */
629
+	public function set_STS_ID($STS_ID)
630
+	{
631
+		$this->set('STS_ID', $STS_ID);
632
+	}
633
+
634
+
635
+	/**
636
+	 * Gets created
637
+	 *
638
+	 * @return string
639
+	 */
640
+	public function created()
641
+	{
642
+		return $this->get('MSG_created');
643
+	}
644
+
645
+
646
+	/**
647
+	 * Sets created
648
+	 *
649
+	 * @param string $created
650
+	 */
651
+	public function set_created($created)
652
+	{
653
+		$this->set('MSG_created', $created);
654
+	}
655
+
656
+
657
+	/**
658
+	 * Gets modified
659
+	 *
660
+	 * @return string
661
+	 */
662
+	public function modified()
663
+	{
664
+		return $this->get('MSG_modified');
665
+	}
666
+
667
+
668
+	/**
669
+	 * Sets modified
670
+	 *
671
+	 * @param string $modified
672
+	 */
673
+	public function set_modified($modified)
674
+	{
675
+		$this->set('MSG_modified', $modified);
676
+	}
677
+
678
+
679
+	/**
680
+	 * Sets generation data for this message.
681
+	 *
682
+	 * @param mixed $data
683
+	 */
684
+	public function set_generation_data($data)
685
+	{
686
+		$this->set_field_or_extra_meta('MSG_generation_data', $data);
687
+	}
688
+
689
+
690
+	/**
691
+	 * Returns any set generation data for this message.
692
+	 *
693
+	 * @return mixed|null
694
+	 */
695
+	public function get_generation_data()
696
+	{
697
+		return $this->get_field_or_extra_meta('MSG_generation_data');
698
+	}
699
+
700
+
701
+	/**
702
+	 * Gets any error message.
703
+	 *
704
+	 * @return mixed|null
705
+	 */
706
+	public function error_message()
707
+	{
708
+		return $this->get_field_or_extra_meta('MSG_error');
709
+	}
710
+
711
+
712
+	/**
713
+	 * Sets an error message.
714
+	 *
715
+	 * @param $message
716
+	 * @return bool|int
717
+	 */
718
+	public function set_error_message($message)
719
+	{
720
+		return $this->set_field_or_extra_meta('MSG_error', $message);
721
+	}
722
+
723
+
724
+	/**
725
+	 * This retrieves the associated template pack with this message.
726
+	 *
727
+	 * @return EE_Messages_Template_Pack | null
728
+	 */
729
+	public function get_template_pack()
730
+	{
731
+		/**
732
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
733
+		 */
734
+		if ( ! empty($this->template_pack)) {
735
+			return $this->template_pack;
736
+		}
737
+		/** @type EE_Message_Template_Group $grp */
738
+		$grp = $this->get_first_related('Message_Template_Group');
739
+		//if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
740
+		if ( ! $grp instanceof EE_Message_Template_Group) {
741
+			$grp = EEM_Message_Template_Group::instance()->get_one(
742
+				array(
743
+					array(
744
+						'MTP_messenger'    => $this->messenger(),
745
+						'MTP_message_type' => $this->message_type(),
746
+						'MTP_is_global'    => true,
747
+					),
748
+				)
749
+			);
750
+		}
751
+
752
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
753
+	}
754
+
755
+
756
+	/**
757
+	 * Retrieves the variation used for generating this message.
758
+	 *
759
+	 * @return string
760
+	 */
761
+	public function get_template_pack_variation()
762
+	{
763
+		/**
764
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
765
+		 */
766
+		if ( ! empty($this->template_variation)) {
767
+			return $this->template_variation;
768
+		}
769
+
770
+		/** @type EE_Message_Template_Group $grp */
771
+		$grp = $this->get_first_related('Message_Template_Group');
772
+
773
+		//if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
774
+		if ( ! $grp instanceof EE_Message_Template_Group) {
775
+			$grp = EEM_Message_Template_Group::instance()->get_one(
776
+				array(
777
+					array(
778
+						'MTP_messenger'    => $this->messenger(),
779
+						'MTP_message_type' => $this->message_type(),
780
+						'MTP_is_global'    => true,
781
+					),
782
+				)
783
+			);
784
+		}
785
+
786
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
787
+	}
788
+
789
+	/**
790
+	 * Return the link to the admin details for the object.
791
+	 *
792
+	 * @return string
793
+	 */
794
+	public function get_admin_details_link()
795
+	{
796
+		EE_Registry::instance()->load_helper('URL');
797
+		EE_Registry::instance()->load_helper('MSG_Template');
798
+		switch ($this->STS_ID()) {
799
+			case EEM_Message::status_failed :
800
+			case EEM_Message::status_debug_only :
801
+				return EEH_MSG_Template::generate_error_display_trigger($this);
802
+				break;
803
+
804
+			case EEM_Message::status_sent :
805
+				return EEH_MSG_Template::generate_browser_trigger($this);
806
+				break;
807
+
808
+			default :
809
+				return '';
810
+		}
811
+	}
812
+
813
+	/**
814
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
815
+	 *
816
+	 * @return string
817
+	 */
818
+	public function get_admin_edit_link()
819
+	{
820
+		return $this->get_admin_details_link();
821
+	}
822
+
823
+	/**
824
+	 * Returns the link to a settings page for the object.
825
+	 *
826
+	 * @return string
827
+	 */
828
+	public function get_admin_settings_link()
829
+	{
830
+		EE_Registry::instance()->load_helper('URL');
831
+		return EEH_URL::add_query_args_and_nonce(
832
+			array(
833
+				'page'   => 'espresso_messages',
834
+				'action' => 'settings',
835
+			),
836
+			admin_url('admin.php')
837
+		);
838
+	}
839
+
840
+	/**
841
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
842
+	 *
843
+	 * @return string
844
+	 */
845
+	public function get_admin_overview_link()
846
+	{
847
+		EE_Registry::instance()->load_helper('URL');
848
+		return EEH_URL::add_query_args_and_nonce(
849
+			array(
850
+				'page'   => 'espresso_messages',
851
+				'action' => 'default',
852
+			),
853
+			admin_url('admin.php')
854
+		);
855
+	}
856
+
857
+
858
+	/**
859
+	 * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
860
+	 * it.
861
+	 * Note this also SAVES the current message object to the db because it adds an error message to accompany the status.
862
+	 *
863
+	 */
864
+	public function set_messenger_is_executing()
865
+	{
866
+		$this->set_STS_ID( EEM_Message::status_messenger_executing );
867
+		$this->set_error_message(
868
+			esc_html__(
869
+				'A message with this status indicates that there was a problem that occurred while the message was being
870 870
                 processed by the messenger.  It is still possible that the message was sent successfully, but at some
871 871
                 point during the processing there was a failure.  This usually is indicative of a timeout issue with PHP 
872 872
                 or memory limits being reached.  If you see this repeatedly you may want to consider upgrading the memory 
873 873
                 available to PHP on your server.',
874
-                'event_espresso'
875
-            )
876
-        );
877
-    }
874
+				'event_espresso'
875
+			)
876
+		);
877
+	}
878 878
 }
879 879
 /* End of file EE_Message.class.php */
880 880
 /* Location: /core/db_classes/EE_Message.class.php */
881 881
\ No newline at end of file
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Queue.lib.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -603,7 +603,7 @@
 block discarded – undo
603 603
      * @param EE_Message      $message
604 604
      * @param EE_messenger    $messenger
605 605
      * @param EE_message_type $message_type
606
-     * @param                 $test_send
606
+     * @param                 boolean $test_send
607 607
      * @return bool   true means all went well, false means, not so much.
608 608
      */
609 609
     protected function _do_preview(
Please login to merge, or discard this patch.
Indentation   +689 added lines, -689 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use \EventEspresso\core\exceptions\SendMessageException;
3 3
 
4 4
 if (! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 /**
@@ -18,693 +18,693 @@  discard block
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * @type    string  reference for sending action
23
-     */
24
-    const action_sending = 'sending';
25
-
26
-    /**
27
-     * @type    string  reference for generation action
28
-     */
29
-    const action_generating = 'generation';
30
-
31
-
32
-    /**
33
-     * @type EE_Message_Repository $_message_repository
34
-     */
35
-    protected $_message_repository;
36
-
37
-    /**
38
-     * Sets the limit of how many messages are generated per process.
39
-     *
40
-     * @type int
41
-     */
42
-    protected $_batch_count;
43
-
44
-
45
-    /**
46
-     * This is an array of cached queue items being stored in this object.
47
-     * The array keys will be the ID of the EE_Message in the db if saved.  If the EE_Message
48
-     * is not saved to the db then its key will be an increment of "UNS" (i.e. UNS1, UNS2 etc.)
49
-     *
50
-     * @type EE_Message[]
51
-     */
52
-    protected $_cached_queue_items;
53
-
54
-    /**
55
-     * Tracks the number of unsaved queue items.
56
-     *
57
-     * @type int
58
-     */
59
-    protected $_unsaved_count = 0;
60
-
61
-    /**
62
-     * used to record if a do_messenger_hooks has already been called for a message type.  This prevents multiple
63
-     * hooks getting fired if users have setup their action/filter hooks to prevent duplicate calls.
64
-     *
65
-     * @type array
66
-     */
67
-    protected $_did_hook = array();
68
-
69
-
70
-    /**
71
-     * Constructor.
72
-     * Setup all the initial properties and load a EE_Message_Repository.
73
-     *
74
-     * @param \EE_Message_Repository $message_repository
75
-     */
76
-    public function __construct(EE_Message_Repository $message_repository)
77
-    {
78
-        $this->_batch_count        = apply_filters('FHEE__EE_Messages_Queue___batch_count', 50);
79
-        $this->_message_repository = $message_repository;
80
-    }
81
-
82
-
83
-    /**
84
-     * Add a EE_Message object to the queue
85
-     *
86
-     * @param EE_Message $message
87
-     * @param array      $data         This will be an array of data to attach to the object in the repository.  If the
88
-     *                                 object is persisted, this data will be saved on an extra_meta object related to
89
-     *                                 EE_Message.
90
-     * @param  bool      $preview      Whether this EE_Message represents a preview or not.
91
-     * @param  bool      $test_send    This indicates whether to do a test send instead of actual send. A test send will
92
-     *                                 use the messenger send method but typically is based on preview data.
93
-     * @return bool          Whether the message was successfully added to the repository or not.
94
-     */
95
-    public function add(EE_Message $message, $data = array(), $preview = false, $test_send = false)
96
-    {
97
-        $data['preview']   = $preview;
98
-        $data['test_send'] = $test_send;
99
-        return $this->_message_repository->add($message, $data);
100
-    }
101
-
102
-
103
-    /**
104
-     * Removes EE_Message from _queue that matches the given EE_Message if the pointer is on a matching EE_Message
105
-     *
106
-     * @param EE_Message $message The message to detach from the queue
107
-     * @param bool       $persist This flag indicates whether to attempt to delete the object from the db as well.
108
-     * @return bool
109
-     */
110
-    public function remove(EE_Message $message, $persist = false)
111
-    {
112
-        if ($persist && $this->_message_repository->current() !== $message) {
113
-            //get pointer on right message
114
-            if ($this->_message_repository->has($message)) {
115
-                $this->_message_repository->rewind();
116
-                while ($this->_message_repository->valid()) {
117
-                    if ($this->_message_repository->current() === $message) {
118
-                        break;
119
-                    }
120
-                    $this->_message_repository->next();
121
-                }
122
-            } else {
123
-                return false;
124
-            }
125
-        }
126
-        return $persist ? $this->_message_repository->delete() : $this->_message_repository->remove($message);
127
-    }
128
-
129
-
130
-    /**
131
-     * Persists all queued EE_Message objects to the db.
132
-     *
133
-     * @param bool $do_hooks_only       @see EE_Message_Repository::saveAll
134
-     * @return array @see EE_Messages_Repository::saveAll() for return values.
135
-     */
136
-    public function save($do_hooks_only = false)
137
-    {
138
-        return $this->_message_repository->saveAll($do_hooks_only);
139
-    }
140
-
141
-
142
-    /**
143
-     * @return EE_Message_Repository
144
-     */
145
-    public function get_message_repository()
146
-    {
147
-        return $this->_message_repository;
148
-    }
149
-
150
-
151
-    /**
152
-     * This does the following things:
153
-     * 1. Checks if there is a lock on generation (prevents race conditions).  If there is a lock then exits (return
154
-     * false).
155
-     * 2. If no lock, sets lock, then retrieves a batch of non-generated EE_Message objects and adds to queue
156
-     * 3. Returns bool.  True = batch ready.  False = no batch ready (or nothing available for generation).
157
-     * Note: Callers should make sure they release the lock otherwise batch generation will be prevented from
158
-     * continuing. The lock is on a transient that is set to expire after one hour as a fallback in case locks are not
159
-     * removed.
160
-     *
161
-     * @return bool  true if successfully retrieved batch, false no batch ready.
162
-     */
163
-    public function get_batch_to_generate()
164
-    {
165
-        if ($this->is_locked(EE_Messages_Queue::action_generating)) {
166
-            return false;
167
-        }
168
-
169
-        //lock batch generation to prevent race conditions.
170
-        $this->lock_queue(EE_Messages_Queue::action_generating);
171
-
172
-        $query_args = array(
173
-            // key 0 = where conditions
174
-            0          => array('STS_ID' => EEM_Message::status_incomplete),
175
-            'order_by' => $this->_get_priority_orderby(),
176
-            'limit'    => $this->_batch_count,
177
-        );
178
-        $messages   = EEM_Message::instance()->get_all($query_args);
179
-
180
-        if ( ! $messages) {
181
-            return false; //nothing to generate
182
-        }
183
-
184
-        foreach ($messages as $message) {
185
-            if ($message instanceof EE_Message) {
186
-                $data = $message->all_extra_meta_array();
187
-                $this->add($message, $data);
188
-            }
189
-        }
190
-        return true;
191
-    }
192
-
193
-
194
-    /**
195
-     * This does the following things:
196
-     * 1. Checks if there is a lock on sending (prevents race conditions).  If there is a lock then exits (return
197
-     * false).
198
-     * 2. Grabs the allowed number of messages to send for the rate_limit.  If cannot send any more messages, then
199
-     * return false.
200
-     * 2. If no lock, sets lock, then retrieves a batch of EE_Message objects, adds to queue and triggers execution.
201
-     * 3. On success or unsuccessful send, sets status appropriately.
202
-     * 4. Saves messages via the queue
203
-     * 5. Releases lock.
204
-     *
205
-     * @return bool  true on success, false if something preventing sending (i.e. lock set).  Note: true does not
206
-     *               necessarily mean that all messages were successfully sent.  It just means that this method
207
-     *               successfully completed. On true, client may want to call $this->count_STS_in_queue(
208
-     *               EEM_Message::status_failed ) to see if any failed EE_Message objects.  Each failed message object
209
-     *               will also have a saved error message on it to assist with notifying user.
210
-     */
211
-    public function get_to_send_batch_and_send()
212
-    {
213
-        $rate_limit = $this->get_rate_limit();
214
-        if ($rate_limit < 1 || $this->is_locked(EE_Messages_Queue::action_sending)) {
215
-            return false;
216
-        }
217
-
218
-        $this->lock_queue(EE_Messages_Queue::action_sending);
219
-
220
-        $batch = $this->_batch_count < $rate_limit ? $this->_batch_count : $rate_limit;
221
-
222
-        $query_args = array(
223
-            // key 0 = where conditions
224
-            0          => array('STS_ID' => array('IN', EEM_Message::instance()->stati_indicating_to_send())),
225
-            'order_by' => $this->_get_priority_orderby(),
226
-            'limit'    => $batch,
227
-        );
228
-
229
-        $messages_to_send = EEM_Message::instance()->get_all($query_args);
230
-
231
-
232
-        //any to send?
233
-        if ( ! $messages_to_send) {
234
-            $this->unlock_queue(EE_Messages_Queue::action_sending);
235
-            return false;
236
-        }
237
-
238
-        $queue_count = 0;
239
-
240
-        //add to queue.
241
-        foreach ($messages_to_send as $message) {
242
-            if ($message instanceof EE_Message) {
243
-                $queue_count++;
244
-                $this->add($message);
245
-            }
246
-        }
247
-
248
-        //send messages  (this also updates the rate limit)
249
-        $this->execute();
250
-
251
-        //release lock
252
-        $this->unlock_queue(EE_Messages_Queue::action_sending);
253
-        //update rate limit
254
-        $this->set_rate_limit($queue_count);
255
-        return true;
256
-    }
257
-
258
-
259
-    /**
260
-     * Locks the queue so that no other queues can call the "batch" methods.
261
-     *
262
-     * @param   string $type The type of queue being locked.
263
-     */
264
-    public function lock_queue($type = EE_Messages_Queue::action_generating)
265
-    {
266
-        update_option($this->_get_lock_key($type), $this->_get_lock_expiry($type));
267
-    }
268
-
269
-
270
-    /**
271
-     * Unlocks the queue so that batch methods can be used.
272
-     *
273
-     * @param   string $type The type of queue being unlocked.
274
-     */
275
-    public function unlock_queue($type = EE_Messages_Queue::action_generating)
276
-    {
277
-        delete_option($this->_get_lock_key($type));
278
-    }
279
-
280
-
281
-    /**
282
-     * Retrieve the key used for the lock transient.
283
-     *
284
-     * @param string $type The type of lock.
285
-     * @return string
286
-     */
287
-    protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
288
-    {
289
-        return '_ee_lock_' . $type;
290
-    }
291
-
292
-
293
-    /**
294
-     * Retrieve the expiry time for the lock transient.
295
-     *
296
-     * @param string $type The type of lock
297
-     * @return int   time to expiry in seconds.
298
-     */
299
-    protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
300
-    {
301
-        return time() + (int) apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
302
-    }
303
-
304
-
305
-    /**
306
-     * Returns the key used for rate limit transient.
307
-     *
308
-     * @return string
309
-     */
310
-    protected function _get_rate_limit_key()
311
-    {
312
-        return '_ee_rate_limit';
313
-    }
314
-
315
-
316
-    /**
317
-     * Returns the rate limit expiry time.
318
-     *
319
-     * @return int
320
-     */
321
-    protected function _get_rate_limit_expiry()
322
-    {
323
-        return time() + (int) apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
324
-    }
325
-
326
-
327
-    /**
328
-     * Returns the default rate limit for sending messages.
329
-     *
330
-     * @return int
331
-     */
332
-    protected function _default_rate_limit()
333
-    {
334
-        return (int) apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
335
-    }
336
-
337
-
338
-    /**
339
-     * Return the orderby array for priority.
340
-     *
341
-     * @return array
342
-     */
343
-    protected function _get_priority_orderby()
344
-    {
345
-        return array(
346
-            'MSG_priority' => 'ASC',
347
-            'MSG_modified' => 'DESC',
348
-        );
349
-    }
350
-
351
-
352
-    /**
353
-     * Returns whether batch methods are "locked" or not.
354
-     *
355
-     * @param  string $type The type of lock being checked for.
356
-     * @return bool
357
-     */
358
-    public function is_locked($type = EE_Messages_Queue::action_generating)
359
-    {
360
-        $lock = (int) get_option($this->_get_lock_key($type), 0);
361
-        /**
362
-         * This filters the default is_locked behaviour.
363
-         */
364
-        $is_locked = filter_var(
365
-            apply_filters(
366
-                'FHEE__EE_Messages_Queue__is_locked',
367
-                $lock > time(),
368
-                $this
369
-            ),
370
-            FILTER_VALIDATE_BOOLEAN
371
-        );
372
-
373
-        /**
374
-         * @see usage of this filter in EE_Messages_Queue::initiate_request_by_priority() method.
375
-         *            Also implemented here because messages processed on the same request should not have any locks applied.
376
-         */
377
-        if (
378
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
379
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
380
-        ) {
381
-            $is_locked = false;
382
-        }
383
-
384
-
385
-        return $is_locked;
386
-    }
387
-
388
-
389
-    /**
390
-     * Retrieves the rate limit that may be cached as a transient.
391
-     * If the rate limit is not set, then this sets the default rate limit and expiry and returns it.
392
-     *
393
-     * @param bool $return_expiry  If true then return the expiry time not the rate_limit.
394
-     * @return int
395
-     */
396
-    protected function get_rate_limit($return_expiry = false)
397
-    {
398
-        $stored_rate_info = get_option($this->_get_rate_limit_key(), array());
399
-        $rate_limit = isset($stored_rate_info[0])
400
-            ? (int) $stored_rate_info[0]
401
-            : 0;
402
-        $expiry = isset($stored_rate_info[1])
403
-            ? (int) $stored_rate_info[1]
404
-            : 0;
405
-        //set the default for tracking?
406
-        if (empty($stored_rate_info) || time() > $expiry) {
407
-            $expiry = $this->_get_rate_limit_expiry();
408
-            $rate_limit = $this->_default_rate_limit();
409
-            update_option($this->_get_rate_limit_key(), array($rate_limit, $expiry));
410
-        }
411
-        return $return_expiry ? $expiry : $rate_limit;
412
-    }
413
-
414
-
415
-    /**
416
-     * This updates existing rate limit with the new limit which is the old minus the batch.
417
-     *
418
-     * @param int $batch_completed This sets the new rate limit based on the given batch that was completed.
419
-     */
420
-    protected function set_rate_limit($batch_completed)
421
-    {
422
-        //first get the most up to date rate limit (in case its expired and reset)
423
-        $rate_limit = $this->get_rate_limit();
424
-        $expiry = $this->get_rate_limit(true);
425
-        $new_limit  = $rate_limit - $batch_completed;
426
-        //updating the transient option directly to avoid resetting the expiry.
427
-
428
-        update_option($this->_get_rate_limit_key(), array($new_limit, $expiry));
429
-    }
430
-
431
-
432
-    /**
433
-     * This method checks the queue for ANY EE_Message objects with a priority matching the given priority passed in.
434
-     * If that exists, then we immediately initiate a non-blocking request to do the requested action type.
435
-     * Note: Keep in mind that there is the possibility that the request will not execute if there is already another
436
-     * request running on a queue for the given task.
437
-     *
438
-     * @param string $task     This indicates what type of request is going to be initiated.
439
-     * @param int    $priority This indicates the priority that triggers initiating the request.
440
-     */
441
-    public function initiate_request_by_priority($task = 'generate', $priority = EEM_Message::priority_high)
442
-    {
443
-        //determine what status is matched with the priority as part of the trigger conditions.
444
-        $status = $task == 'generate'
445
-            ? EEM_Message::status_incomplete
446
-            : EEM_Message::instance()->stati_indicating_to_send();
447
-        // always make sure we save because either this will get executed immediately on a separate request
448
-        // or remains in the queue for the regularly scheduled queue batch.
449
-        $this->save();
450
-        /**
451
-         * This filter/option allows users to override processing of messages on separate requests and instead have everything
452
-         * happen on the same request.  If this is utilized remember:
453
-         * - message priorities don't matter
454
-         * - existing unprocessed messages in the queue will not get processed unless manually triggered.
455
-         * - things will be perceived to take longer to happen for end users (i.e. registrations) because of the additional
456
-         *   processing happening on the same request.
457
-         * - any race condition protection (locks) are removed because they don't apply when things are processed on
458
-         *   the same request.
459
-         */
460
-        if (
461
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
462
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
463
-        ) {
464
-            $messages_processor = EE_Registry::instance()->load_lib('Messages_Processor');
465
-            if ($messages_processor instanceof EE_Messages_Processor) {
466
-                return $messages_processor->process_immediately_from_queue($this);
467
-            }
468
-            //if we get here then that means the messages processor couldn't be loaded so messages will just remain
469
-            //queued for manual triggering by end user.
470
-        }
471
-
472
-        if ($this->_message_repository->count_by_priority_and_status($priority, $status)) {
473
-            EE_Messages_Scheduler::initiate_scheduled_non_blocking_request($task);
474
-        }
475
-    }
476
-
477
-
478
-    /**
479
-     *  Loops through the EE_Message objects in the _queue and calls the messenger send methods for each message.
480
-     *
481
-     * @param   bool     $save                    Used to indicate whether to save the message queue after sending
482
-     *                                            (default will save).
483
-     * @param   mixed    $sending_messenger       (optional) When the sending messenger is different than
484
-     *                                            what is on the EE_Message object in the queue.
485
-     *                                            For instance, showing the browser view of an email message,
486
-     *                                            or giving a pdf generated view of an html document.
487
-     *                                            This should be an instance of EE_messenger but if you call this
488
-     *                                            method
489
-     *                                            intending it to be a sending messenger but a valid one could not be
490
-     *                                            retrieved then send in an instance of EE_Error that contains the
491
-     *                                            related error message.
492
-     * @param   bool|int $by_priority             When set, this indicates that only messages
493
-     *                                            matching the given priority should be executed.
494
-     * @return int        Number of messages sent.  Note, 0 does not mean that no messages were processed.
495
-     *                                            Also, if the messenger is an request type messenger (or a preview),
496
-     *                                            its entirely possible that the messenger will exit before
497
-     */
498
-    public function execute($save = true, $sending_messenger = null, $by_priority = false)
499
-    {
500
-        $messages_sent   = 0;
501
-        $this->_did_hook = array();
502
-        $this->_message_repository->rewind();
503
-
504
-        while ($this->_message_repository->valid()) {
505
-            $error_messages = array();
506
-            /** @type EE_Message $message */
507
-            $message = $this->_message_repository->current();
508
-            //only process things that are queued for sending
509
-            if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
510
-                $this->_message_repository->next();
511
-                continue;
512
-            }
513
-            //if $by_priority is set and does not match then continue;
514
-            if ($by_priority && $by_priority != $message->priority()) {
515
-                $this->_message_repository->next();
516
-                continue;
517
-            }
518
-            //error checking
519
-            if (! $message->valid_messenger()) {
520
-                $error_messages[] = sprintf(
521
-                    __('The %s messenger is not active at time of sending.', 'event_espresso'),
522
-                    $message->messenger()
523
-                );
524
-            }
525
-            if (! $message->valid_message_type()) {
526
-                $error_messages[] = sprintf(
527
-                    __('The %s message type is not active at the time of sending.', 'event_espresso'),
528
-                    $message->message_type()
529
-                );
530
-            }
531
-            // if there was supposed to be a sending messenger for this message, but it was invalid/inactive,
532
-            // then it will instead be an EE_Error object, so let's check for that
533
-            if ($sending_messenger instanceof EE_Error) {
534
-                $error_messages[] = $sending_messenger->getMessage();
535
-            }
536
-            // if there are no errors, then let's process the message
537
-            if (empty($error_messages)) {
538
-                if ($save) {
539
-                    $message->set_messenger_is_executing();
540
-                }
541
-                if ($this->_process_message($message, $sending_messenger)) {
542
-                    $messages_sent++;
543
-                }
544
-            }
545
-            $this->_set_error_message($message, $error_messages);
546
-            //add modified time
547
-            $message->set_modified(time());
548
-            //we save each message after its processed to make sure its status persists in case PHP times-out or runs
549
-            //out of memory. @see https://events.codebasehq.com/projects/event-espresso/tickets/10281
550
-            if ($save) {
551
-                $message->save();
552
-            }
553
-
554
-            $this->_message_repository->next();
555
-        }
556
-        if ($save) {
557
-            $this->save(true);
558
-        }
559
-        return $messages_sent;
560
-    }
561
-
562
-
563
-    /**
564
-     * _process_message
565
-     *
566
-     * @param EE_Message $message
567
-     * @param mixed      $sending_messenger (optional)
568
-     * @return bool
569
-     */
570
-    protected function _process_message(EE_Message $message, $sending_messenger = null)
571
-    {
572
-        // these *should* have been validated in the execute() method above
573
-        $messenger    = $message->messenger_object();
574
-        $message_type = $message->message_type_object();
575
-        //do actions for sending messenger if it differs from generating messenger and swap values.
576
-        if (
577
-            $sending_messenger instanceof EE_messenger
578
-            && $messenger instanceof EE_messenger
579
-            && $sending_messenger->name != $messenger->name
580
-        ) {
581
-            $messenger->do_secondary_messenger_hooks($sending_messenger->name);
582
-            $messenger = $sending_messenger;
583
-        }
584
-        // send using messenger, but double check objects
585
-        if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
586
-            //set hook for message type (but only if not using another messenger to send).
587
-            if ( ! isset($this->_did_hook[$message_type->name])) {
588
-                $message_type->do_messenger_hooks($messenger);
589
-                $this->_did_hook[$message_type->name] = 1;
590
-            }
591
-            //if preview then use preview method
592
-            return $this->_message_repository->is_preview()
593
-                ? $this->_do_preview($message, $messenger, $message_type, $this->_message_repository->is_test_send())
594
-                : $this->_do_send($message, $messenger, $message_type);
595
-        }
596
-        return false;
597
-    }
598
-
599
-
600
-    /**
601
-     * The intention of this method is to count how many EE_Message objects
602
-     * are in the queue with a given status.
603
-     * Example usage:
604
-     * After a caller calls the "EE_Message_Queue::execute()" method, the caller can check if there were any failed
605
-     * sends by calling $queue->count_STS_in_queue( EEM_Message_Queue::status_failed ).
606
-     *
607
-     * @param array|string $status Stati to check for in queue
608
-     * @return int  Count of EE_Message's matching the given status.
609
-     */
610
-    public function count_STS_in_queue($status)
611
-    {
612
-        $count  = 0;
613
-        $status = is_array($status) ? $status : array($status);
614
-        $this->_message_repository->rewind();
615
-        foreach ($this->_message_repository as $message) {
616
-            if (in_array($message->STS_ID(), $status)) {
617
-                $count++;
618
-            }
619
-        }
620
-        return $count;
621
-    }
622
-
623
-
624
-    /**
625
-     * Executes the get_preview method on the provided messenger.
626
-     *
627
-     * @param EE_Message      $message
628
-     * @param EE_messenger    $messenger
629
-     * @param EE_message_type $message_type
630
-     * @param                 $test_send
631
-     * @return bool   true means all went well, false means, not so much.
632
-     */
633
-    protected function _do_preview(
634
-        EE_Message $message,
635
-        EE_messenger $messenger,
636
-        EE_message_type $message_type,
637
-        $test_send
638
-    ) {
639
-        if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
640
-            if ( ! $test_send) {
641
-                $message->set_content($preview);
642
-            }
643
-            $message->set_STS_ID(EEM_Message::status_sent);
644
-            return true;
645
-        } else {
646
-            $message->set_STS_ID(EEM_Message::status_failed);
647
-            return false;
648
-        }
649
-    }
650
-
651
-
652
-    /**
653
-     * Executes the send method on the provided messenger
654
-     * EE_Messengers are expected to:
655
-     * - return true if the send was successful.
656
-     * - return false if the send was unsuccessful but can be tried again.
657
-     * - throw an Exception if the send was unsuccessful and cannot be tried again.
658
-     *
659
-     * @param EE_Message      $message
660
-     * @param EE_messenger    $messenger
661
-     * @param EE_message_type $message_type
662
-     * @return bool true means all went well, false means, not so much.
663
-     */
664
-    protected function _do_send(EE_Message $message, EE_messenger $messenger, EE_message_type $message_type)
665
-    {
666
-        try {
667
-            if ($messenger->send_message($message, $message_type)) {
668
-                $message->set_STS_ID(EEM_Message::status_sent);
669
-                return true;
670
-            } else {
671
-                $message->set_STS_ID(EEM_Message::status_retry);
672
-                return false;
673
-            }
674
-        } catch (SendMessageException $e) {
675
-            $message->set_STS_ID(EEM_Message::status_failed);
676
-            $message->set_error_message($e->getMessage());
677
-            return false;
678
-        }
679
-    }
680
-
681
-
682
-    /**
683
-     * This sets any necessary error messages on the message object and its status to failed.
684
-     *
685
-     * @param EE_Message $message
686
-     * @param array      $error_messages the response from the messenger.
687
-     */
688
-    protected function _set_error_message(EE_Message $message, $error_messages)
689
-    {
690
-        $error_messages = (array)$error_messages;
691
-        if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
692
-            $notices          = EE_Error::has_notices();
693
-            $error_messages[] = __(
694
-                'Messenger and Message Type were valid and active, but the messenger send method failed.',
695
-                'event_espresso'
696
-            );
697
-            if ($notices === 1) {
698
-                $notices           = EE_Error::get_vanilla_notices();
699
-                $notices['errors'] = isset($notices['errors']) ? $notices['errors'] : array();
700
-                $error_messages[]  = implode("\n", $notices['errors']);
701
-            }
702
-        }
703
-        if (count($error_messages) > 0) {
704
-            $msg = __('Message was not executed successfully.', 'event_espresso');
705
-            $msg = $msg . "\n" . implode("\n", $error_messages);
706
-            $message->set_error_message($msg);
707
-        }
708
-    }
21
+	/**
22
+	 * @type    string  reference for sending action
23
+	 */
24
+	const action_sending = 'sending';
25
+
26
+	/**
27
+	 * @type    string  reference for generation action
28
+	 */
29
+	const action_generating = 'generation';
30
+
31
+
32
+	/**
33
+	 * @type EE_Message_Repository $_message_repository
34
+	 */
35
+	protected $_message_repository;
36
+
37
+	/**
38
+	 * Sets the limit of how many messages are generated per process.
39
+	 *
40
+	 * @type int
41
+	 */
42
+	protected $_batch_count;
43
+
44
+
45
+	/**
46
+	 * This is an array of cached queue items being stored in this object.
47
+	 * The array keys will be the ID of the EE_Message in the db if saved.  If the EE_Message
48
+	 * is not saved to the db then its key will be an increment of "UNS" (i.e. UNS1, UNS2 etc.)
49
+	 *
50
+	 * @type EE_Message[]
51
+	 */
52
+	protected $_cached_queue_items;
53
+
54
+	/**
55
+	 * Tracks the number of unsaved queue items.
56
+	 *
57
+	 * @type int
58
+	 */
59
+	protected $_unsaved_count = 0;
60
+
61
+	/**
62
+	 * used to record if a do_messenger_hooks has already been called for a message type.  This prevents multiple
63
+	 * hooks getting fired if users have setup their action/filter hooks to prevent duplicate calls.
64
+	 *
65
+	 * @type array
66
+	 */
67
+	protected $_did_hook = array();
68
+
69
+
70
+	/**
71
+	 * Constructor.
72
+	 * Setup all the initial properties and load a EE_Message_Repository.
73
+	 *
74
+	 * @param \EE_Message_Repository $message_repository
75
+	 */
76
+	public function __construct(EE_Message_Repository $message_repository)
77
+	{
78
+		$this->_batch_count        = apply_filters('FHEE__EE_Messages_Queue___batch_count', 50);
79
+		$this->_message_repository = $message_repository;
80
+	}
81
+
82
+
83
+	/**
84
+	 * Add a EE_Message object to the queue
85
+	 *
86
+	 * @param EE_Message $message
87
+	 * @param array      $data         This will be an array of data to attach to the object in the repository.  If the
88
+	 *                                 object is persisted, this data will be saved on an extra_meta object related to
89
+	 *                                 EE_Message.
90
+	 * @param  bool      $preview      Whether this EE_Message represents a preview or not.
91
+	 * @param  bool      $test_send    This indicates whether to do a test send instead of actual send. A test send will
92
+	 *                                 use the messenger send method but typically is based on preview data.
93
+	 * @return bool          Whether the message was successfully added to the repository or not.
94
+	 */
95
+	public function add(EE_Message $message, $data = array(), $preview = false, $test_send = false)
96
+	{
97
+		$data['preview']   = $preview;
98
+		$data['test_send'] = $test_send;
99
+		return $this->_message_repository->add($message, $data);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Removes EE_Message from _queue that matches the given EE_Message if the pointer is on a matching EE_Message
105
+	 *
106
+	 * @param EE_Message $message The message to detach from the queue
107
+	 * @param bool       $persist This flag indicates whether to attempt to delete the object from the db as well.
108
+	 * @return bool
109
+	 */
110
+	public function remove(EE_Message $message, $persist = false)
111
+	{
112
+		if ($persist && $this->_message_repository->current() !== $message) {
113
+			//get pointer on right message
114
+			if ($this->_message_repository->has($message)) {
115
+				$this->_message_repository->rewind();
116
+				while ($this->_message_repository->valid()) {
117
+					if ($this->_message_repository->current() === $message) {
118
+						break;
119
+					}
120
+					$this->_message_repository->next();
121
+				}
122
+			} else {
123
+				return false;
124
+			}
125
+		}
126
+		return $persist ? $this->_message_repository->delete() : $this->_message_repository->remove($message);
127
+	}
128
+
129
+
130
+	/**
131
+	 * Persists all queued EE_Message objects to the db.
132
+	 *
133
+	 * @param bool $do_hooks_only       @see EE_Message_Repository::saveAll
134
+	 * @return array @see EE_Messages_Repository::saveAll() for return values.
135
+	 */
136
+	public function save($do_hooks_only = false)
137
+	{
138
+		return $this->_message_repository->saveAll($do_hooks_only);
139
+	}
140
+
141
+
142
+	/**
143
+	 * @return EE_Message_Repository
144
+	 */
145
+	public function get_message_repository()
146
+	{
147
+		return $this->_message_repository;
148
+	}
149
+
150
+
151
+	/**
152
+	 * This does the following things:
153
+	 * 1. Checks if there is a lock on generation (prevents race conditions).  If there is a lock then exits (return
154
+	 * false).
155
+	 * 2. If no lock, sets lock, then retrieves a batch of non-generated EE_Message objects and adds to queue
156
+	 * 3. Returns bool.  True = batch ready.  False = no batch ready (or nothing available for generation).
157
+	 * Note: Callers should make sure they release the lock otherwise batch generation will be prevented from
158
+	 * continuing. The lock is on a transient that is set to expire after one hour as a fallback in case locks are not
159
+	 * removed.
160
+	 *
161
+	 * @return bool  true if successfully retrieved batch, false no batch ready.
162
+	 */
163
+	public function get_batch_to_generate()
164
+	{
165
+		if ($this->is_locked(EE_Messages_Queue::action_generating)) {
166
+			return false;
167
+		}
168
+
169
+		//lock batch generation to prevent race conditions.
170
+		$this->lock_queue(EE_Messages_Queue::action_generating);
171
+
172
+		$query_args = array(
173
+			// key 0 = where conditions
174
+			0          => array('STS_ID' => EEM_Message::status_incomplete),
175
+			'order_by' => $this->_get_priority_orderby(),
176
+			'limit'    => $this->_batch_count,
177
+		);
178
+		$messages   = EEM_Message::instance()->get_all($query_args);
179
+
180
+		if ( ! $messages) {
181
+			return false; //nothing to generate
182
+		}
183
+
184
+		foreach ($messages as $message) {
185
+			if ($message instanceof EE_Message) {
186
+				$data = $message->all_extra_meta_array();
187
+				$this->add($message, $data);
188
+			}
189
+		}
190
+		return true;
191
+	}
192
+
193
+
194
+	/**
195
+	 * This does the following things:
196
+	 * 1. Checks if there is a lock on sending (prevents race conditions).  If there is a lock then exits (return
197
+	 * false).
198
+	 * 2. Grabs the allowed number of messages to send for the rate_limit.  If cannot send any more messages, then
199
+	 * return false.
200
+	 * 2. If no lock, sets lock, then retrieves a batch of EE_Message objects, adds to queue and triggers execution.
201
+	 * 3. On success or unsuccessful send, sets status appropriately.
202
+	 * 4. Saves messages via the queue
203
+	 * 5. Releases lock.
204
+	 *
205
+	 * @return bool  true on success, false if something preventing sending (i.e. lock set).  Note: true does not
206
+	 *               necessarily mean that all messages were successfully sent.  It just means that this method
207
+	 *               successfully completed. On true, client may want to call $this->count_STS_in_queue(
208
+	 *               EEM_Message::status_failed ) to see if any failed EE_Message objects.  Each failed message object
209
+	 *               will also have a saved error message on it to assist with notifying user.
210
+	 */
211
+	public function get_to_send_batch_and_send()
212
+	{
213
+		$rate_limit = $this->get_rate_limit();
214
+		if ($rate_limit < 1 || $this->is_locked(EE_Messages_Queue::action_sending)) {
215
+			return false;
216
+		}
217
+
218
+		$this->lock_queue(EE_Messages_Queue::action_sending);
219
+
220
+		$batch = $this->_batch_count < $rate_limit ? $this->_batch_count : $rate_limit;
221
+
222
+		$query_args = array(
223
+			// key 0 = where conditions
224
+			0          => array('STS_ID' => array('IN', EEM_Message::instance()->stati_indicating_to_send())),
225
+			'order_by' => $this->_get_priority_orderby(),
226
+			'limit'    => $batch,
227
+		);
228
+
229
+		$messages_to_send = EEM_Message::instance()->get_all($query_args);
230
+
231
+
232
+		//any to send?
233
+		if ( ! $messages_to_send) {
234
+			$this->unlock_queue(EE_Messages_Queue::action_sending);
235
+			return false;
236
+		}
237
+
238
+		$queue_count = 0;
239
+
240
+		//add to queue.
241
+		foreach ($messages_to_send as $message) {
242
+			if ($message instanceof EE_Message) {
243
+				$queue_count++;
244
+				$this->add($message);
245
+			}
246
+		}
247
+
248
+		//send messages  (this also updates the rate limit)
249
+		$this->execute();
250
+
251
+		//release lock
252
+		$this->unlock_queue(EE_Messages_Queue::action_sending);
253
+		//update rate limit
254
+		$this->set_rate_limit($queue_count);
255
+		return true;
256
+	}
257
+
258
+
259
+	/**
260
+	 * Locks the queue so that no other queues can call the "batch" methods.
261
+	 *
262
+	 * @param   string $type The type of queue being locked.
263
+	 */
264
+	public function lock_queue($type = EE_Messages_Queue::action_generating)
265
+	{
266
+		update_option($this->_get_lock_key($type), $this->_get_lock_expiry($type));
267
+	}
268
+
269
+
270
+	/**
271
+	 * Unlocks the queue so that batch methods can be used.
272
+	 *
273
+	 * @param   string $type The type of queue being unlocked.
274
+	 */
275
+	public function unlock_queue($type = EE_Messages_Queue::action_generating)
276
+	{
277
+		delete_option($this->_get_lock_key($type));
278
+	}
279
+
280
+
281
+	/**
282
+	 * Retrieve the key used for the lock transient.
283
+	 *
284
+	 * @param string $type The type of lock.
285
+	 * @return string
286
+	 */
287
+	protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
288
+	{
289
+		return '_ee_lock_' . $type;
290
+	}
291
+
292
+
293
+	/**
294
+	 * Retrieve the expiry time for the lock transient.
295
+	 *
296
+	 * @param string $type The type of lock
297
+	 * @return int   time to expiry in seconds.
298
+	 */
299
+	protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
300
+	{
301
+		return time() + (int) apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
302
+	}
303
+
304
+
305
+	/**
306
+	 * Returns the key used for rate limit transient.
307
+	 *
308
+	 * @return string
309
+	 */
310
+	protected function _get_rate_limit_key()
311
+	{
312
+		return '_ee_rate_limit';
313
+	}
314
+
315
+
316
+	/**
317
+	 * Returns the rate limit expiry time.
318
+	 *
319
+	 * @return int
320
+	 */
321
+	protected function _get_rate_limit_expiry()
322
+	{
323
+		return time() + (int) apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
324
+	}
325
+
326
+
327
+	/**
328
+	 * Returns the default rate limit for sending messages.
329
+	 *
330
+	 * @return int
331
+	 */
332
+	protected function _default_rate_limit()
333
+	{
334
+		return (int) apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
335
+	}
336
+
337
+
338
+	/**
339
+	 * Return the orderby array for priority.
340
+	 *
341
+	 * @return array
342
+	 */
343
+	protected function _get_priority_orderby()
344
+	{
345
+		return array(
346
+			'MSG_priority' => 'ASC',
347
+			'MSG_modified' => 'DESC',
348
+		);
349
+	}
350
+
351
+
352
+	/**
353
+	 * Returns whether batch methods are "locked" or not.
354
+	 *
355
+	 * @param  string $type The type of lock being checked for.
356
+	 * @return bool
357
+	 */
358
+	public function is_locked($type = EE_Messages_Queue::action_generating)
359
+	{
360
+		$lock = (int) get_option($this->_get_lock_key($type), 0);
361
+		/**
362
+		 * This filters the default is_locked behaviour.
363
+		 */
364
+		$is_locked = filter_var(
365
+			apply_filters(
366
+				'FHEE__EE_Messages_Queue__is_locked',
367
+				$lock > time(),
368
+				$this
369
+			),
370
+			FILTER_VALIDATE_BOOLEAN
371
+		);
372
+
373
+		/**
374
+		 * @see usage of this filter in EE_Messages_Queue::initiate_request_by_priority() method.
375
+		 *            Also implemented here because messages processed on the same request should not have any locks applied.
376
+		 */
377
+		if (
378
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
379
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
380
+		) {
381
+			$is_locked = false;
382
+		}
383
+
384
+
385
+		return $is_locked;
386
+	}
387
+
388
+
389
+	/**
390
+	 * Retrieves the rate limit that may be cached as a transient.
391
+	 * If the rate limit is not set, then this sets the default rate limit and expiry and returns it.
392
+	 *
393
+	 * @param bool $return_expiry  If true then return the expiry time not the rate_limit.
394
+	 * @return int
395
+	 */
396
+	protected function get_rate_limit($return_expiry = false)
397
+	{
398
+		$stored_rate_info = get_option($this->_get_rate_limit_key(), array());
399
+		$rate_limit = isset($stored_rate_info[0])
400
+			? (int) $stored_rate_info[0]
401
+			: 0;
402
+		$expiry = isset($stored_rate_info[1])
403
+			? (int) $stored_rate_info[1]
404
+			: 0;
405
+		//set the default for tracking?
406
+		if (empty($stored_rate_info) || time() > $expiry) {
407
+			$expiry = $this->_get_rate_limit_expiry();
408
+			$rate_limit = $this->_default_rate_limit();
409
+			update_option($this->_get_rate_limit_key(), array($rate_limit, $expiry));
410
+		}
411
+		return $return_expiry ? $expiry : $rate_limit;
412
+	}
413
+
414
+
415
+	/**
416
+	 * This updates existing rate limit with the new limit which is the old minus the batch.
417
+	 *
418
+	 * @param int $batch_completed This sets the new rate limit based on the given batch that was completed.
419
+	 */
420
+	protected function set_rate_limit($batch_completed)
421
+	{
422
+		//first get the most up to date rate limit (in case its expired and reset)
423
+		$rate_limit = $this->get_rate_limit();
424
+		$expiry = $this->get_rate_limit(true);
425
+		$new_limit  = $rate_limit - $batch_completed;
426
+		//updating the transient option directly to avoid resetting the expiry.
427
+
428
+		update_option($this->_get_rate_limit_key(), array($new_limit, $expiry));
429
+	}
430
+
431
+
432
+	/**
433
+	 * This method checks the queue for ANY EE_Message objects with a priority matching the given priority passed in.
434
+	 * If that exists, then we immediately initiate a non-blocking request to do the requested action type.
435
+	 * Note: Keep in mind that there is the possibility that the request will not execute if there is already another
436
+	 * request running on a queue for the given task.
437
+	 *
438
+	 * @param string $task     This indicates what type of request is going to be initiated.
439
+	 * @param int    $priority This indicates the priority that triggers initiating the request.
440
+	 */
441
+	public function initiate_request_by_priority($task = 'generate', $priority = EEM_Message::priority_high)
442
+	{
443
+		//determine what status is matched with the priority as part of the trigger conditions.
444
+		$status = $task == 'generate'
445
+			? EEM_Message::status_incomplete
446
+			: EEM_Message::instance()->stati_indicating_to_send();
447
+		// always make sure we save because either this will get executed immediately on a separate request
448
+		// or remains in the queue for the regularly scheduled queue batch.
449
+		$this->save();
450
+		/**
451
+		 * This filter/option allows users to override processing of messages on separate requests and instead have everything
452
+		 * happen on the same request.  If this is utilized remember:
453
+		 * - message priorities don't matter
454
+		 * - existing unprocessed messages in the queue will not get processed unless manually triggered.
455
+		 * - things will be perceived to take longer to happen for end users (i.e. registrations) because of the additional
456
+		 *   processing happening on the same request.
457
+		 * - any race condition protection (locks) are removed because they don't apply when things are processed on
458
+		 *   the same request.
459
+		 */
460
+		if (
461
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
462
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
463
+		) {
464
+			$messages_processor = EE_Registry::instance()->load_lib('Messages_Processor');
465
+			if ($messages_processor instanceof EE_Messages_Processor) {
466
+				return $messages_processor->process_immediately_from_queue($this);
467
+			}
468
+			//if we get here then that means the messages processor couldn't be loaded so messages will just remain
469
+			//queued for manual triggering by end user.
470
+		}
471
+
472
+		if ($this->_message_repository->count_by_priority_and_status($priority, $status)) {
473
+			EE_Messages_Scheduler::initiate_scheduled_non_blocking_request($task);
474
+		}
475
+	}
476
+
477
+
478
+	/**
479
+	 *  Loops through the EE_Message objects in the _queue and calls the messenger send methods for each message.
480
+	 *
481
+	 * @param   bool     $save                    Used to indicate whether to save the message queue after sending
482
+	 *                                            (default will save).
483
+	 * @param   mixed    $sending_messenger       (optional) When the sending messenger is different than
484
+	 *                                            what is on the EE_Message object in the queue.
485
+	 *                                            For instance, showing the browser view of an email message,
486
+	 *                                            or giving a pdf generated view of an html document.
487
+	 *                                            This should be an instance of EE_messenger but if you call this
488
+	 *                                            method
489
+	 *                                            intending it to be a sending messenger but a valid one could not be
490
+	 *                                            retrieved then send in an instance of EE_Error that contains the
491
+	 *                                            related error message.
492
+	 * @param   bool|int $by_priority             When set, this indicates that only messages
493
+	 *                                            matching the given priority should be executed.
494
+	 * @return int        Number of messages sent.  Note, 0 does not mean that no messages were processed.
495
+	 *                                            Also, if the messenger is an request type messenger (or a preview),
496
+	 *                                            its entirely possible that the messenger will exit before
497
+	 */
498
+	public function execute($save = true, $sending_messenger = null, $by_priority = false)
499
+	{
500
+		$messages_sent   = 0;
501
+		$this->_did_hook = array();
502
+		$this->_message_repository->rewind();
503
+
504
+		while ($this->_message_repository->valid()) {
505
+			$error_messages = array();
506
+			/** @type EE_Message $message */
507
+			$message = $this->_message_repository->current();
508
+			//only process things that are queued for sending
509
+			if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
510
+				$this->_message_repository->next();
511
+				continue;
512
+			}
513
+			//if $by_priority is set and does not match then continue;
514
+			if ($by_priority && $by_priority != $message->priority()) {
515
+				$this->_message_repository->next();
516
+				continue;
517
+			}
518
+			//error checking
519
+			if (! $message->valid_messenger()) {
520
+				$error_messages[] = sprintf(
521
+					__('The %s messenger is not active at time of sending.', 'event_espresso'),
522
+					$message->messenger()
523
+				);
524
+			}
525
+			if (! $message->valid_message_type()) {
526
+				$error_messages[] = sprintf(
527
+					__('The %s message type is not active at the time of sending.', 'event_espresso'),
528
+					$message->message_type()
529
+				);
530
+			}
531
+			// if there was supposed to be a sending messenger for this message, but it was invalid/inactive,
532
+			// then it will instead be an EE_Error object, so let's check for that
533
+			if ($sending_messenger instanceof EE_Error) {
534
+				$error_messages[] = $sending_messenger->getMessage();
535
+			}
536
+			// if there are no errors, then let's process the message
537
+			if (empty($error_messages)) {
538
+				if ($save) {
539
+					$message->set_messenger_is_executing();
540
+				}
541
+				if ($this->_process_message($message, $sending_messenger)) {
542
+					$messages_sent++;
543
+				}
544
+			}
545
+			$this->_set_error_message($message, $error_messages);
546
+			//add modified time
547
+			$message->set_modified(time());
548
+			//we save each message after its processed to make sure its status persists in case PHP times-out or runs
549
+			//out of memory. @see https://events.codebasehq.com/projects/event-espresso/tickets/10281
550
+			if ($save) {
551
+				$message->save();
552
+			}
553
+
554
+			$this->_message_repository->next();
555
+		}
556
+		if ($save) {
557
+			$this->save(true);
558
+		}
559
+		return $messages_sent;
560
+	}
561
+
562
+
563
+	/**
564
+	 * _process_message
565
+	 *
566
+	 * @param EE_Message $message
567
+	 * @param mixed      $sending_messenger (optional)
568
+	 * @return bool
569
+	 */
570
+	protected function _process_message(EE_Message $message, $sending_messenger = null)
571
+	{
572
+		// these *should* have been validated in the execute() method above
573
+		$messenger    = $message->messenger_object();
574
+		$message_type = $message->message_type_object();
575
+		//do actions for sending messenger if it differs from generating messenger and swap values.
576
+		if (
577
+			$sending_messenger instanceof EE_messenger
578
+			&& $messenger instanceof EE_messenger
579
+			&& $sending_messenger->name != $messenger->name
580
+		) {
581
+			$messenger->do_secondary_messenger_hooks($sending_messenger->name);
582
+			$messenger = $sending_messenger;
583
+		}
584
+		// send using messenger, but double check objects
585
+		if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
586
+			//set hook for message type (but only if not using another messenger to send).
587
+			if ( ! isset($this->_did_hook[$message_type->name])) {
588
+				$message_type->do_messenger_hooks($messenger);
589
+				$this->_did_hook[$message_type->name] = 1;
590
+			}
591
+			//if preview then use preview method
592
+			return $this->_message_repository->is_preview()
593
+				? $this->_do_preview($message, $messenger, $message_type, $this->_message_repository->is_test_send())
594
+				: $this->_do_send($message, $messenger, $message_type);
595
+		}
596
+		return false;
597
+	}
598
+
599
+
600
+	/**
601
+	 * The intention of this method is to count how many EE_Message objects
602
+	 * are in the queue with a given status.
603
+	 * Example usage:
604
+	 * After a caller calls the "EE_Message_Queue::execute()" method, the caller can check if there were any failed
605
+	 * sends by calling $queue->count_STS_in_queue( EEM_Message_Queue::status_failed ).
606
+	 *
607
+	 * @param array|string $status Stati to check for in queue
608
+	 * @return int  Count of EE_Message's matching the given status.
609
+	 */
610
+	public function count_STS_in_queue($status)
611
+	{
612
+		$count  = 0;
613
+		$status = is_array($status) ? $status : array($status);
614
+		$this->_message_repository->rewind();
615
+		foreach ($this->_message_repository as $message) {
616
+			if (in_array($message->STS_ID(), $status)) {
617
+				$count++;
618
+			}
619
+		}
620
+		return $count;
621
+	}
622
+
623
+
624
+	/**
625
+	 * Executes the get_preview method on the provided messenger.
626
+	 *
627
+	 * @param EE_Message      $message
628
+	 * @param EE_messenger    $messenger
629
+	 * @param EE_message_type $message_type
630
+	 * @param                 $test_send
631
+	 * @return bool   true means all went well, false means, not so much.
632
+	 */
633
+	protected function _do_preview(
634
+		EE_Message $message,
635
+		EE_messenger $messenger,
636
+		EE_message_type $message_type,
637
+		$test_send
638
+	) {
639
+		if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
640
+			if ( ! $test_send) {
641
+				$message->set_content($preview);
642
+			}
643
+			$message->set_STS_ID(EEM_Message::status_sent);
644
+			return true;
645
+		} else {
646
+			$message->set_STS_ID(EEM_Message::status_failed);
647
+			return false;
648
+		}
649
+	}
650
+
651
+
652
+	/**
653
+	 * Executes the send method on the provided messenger
654
+	 * EE_Messengers are expected to:
655
+	 * - return true if the send was successful.
656
+	 * - return false if the send was unsuccessful but can be tried again.
657
+	 * - throw an Exception if the send was unsuccessful and cannot be tried again.
658
+	 *
659
+	 * @param EE_Message      $message
660
+	 * @param EE_messenger    $messenger
661
+	 * @param EE_message_type $message_type
662
+	 * @return bool true means all went well, false means, not so much.
663
+	 */
664
+	protected function _do_send(EE_Message $message, EE_messenger $messenger, EE_message_type $message_type)
665
+	{
666
+		try {
667
+			if ($messenger->send_message($message, $message_type)) {
668
+				$message->set_STS_ID(EEM_Message::status_sent);
669
+				return true;
670
+			} else {
671
+				$message->set_STS_ID(EEM_Message::status_retry);
672
+				return false;
673
+			}
674
+		} catch (SendMessageException $e) {
675
+			$message->set_STS_ID(EEM_Message::status_failed);
676
+			$message->set_error_message($e->getMessage());
677
+			return false;
678
+		}
679
+	}
680
+
681
+
682
+	/**
683
+	 * This sets any necessary error messages on the message object and its status to failed.
684
+	 *
685
+	 * @param EE_Message $message
686
+	 * @param array      $error_messages the response from the messenger.
687
+	 */
688
+	protected function _set_error_message(EE_Message $message, $error_messages)
689
+	{
690
+		$error_messages = (array)$error_messages;
691
+		if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
692
+			$notices          = EE_Error::has_notices();
693
+			$error_messages[] = __(
694
+				'Messenger and Message Type were valid and active, but the messenger send method failed.',
695
+				'event_espresso'
696
+			);
697
+			if ($notices === 1) {
698
+				$notices           = EE_Error::get_vanilla_notices();
699
+				$notices['errors'] = isset($notices['errors']) ? $notices['errors'] : array();
700
+				$error_messages[]  = implode("\n", $notices['errors']);
701
+			}
702
+		}
703
+		if (count($error_messages) > 0) {
704
+			$msg = __('Message was not executed successfully.', 'event_espresso');
705
+			$msg = $msg . "\n" . implode("\n", $error_messages);
706
+			$message->set_error_message($msg);
707
+		}
708
+	}
709 709
 
710 710
 } //end EE_Messages_Queue class
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 use \EventEspresso\core\exceptions\SendMessageException;
3 3
 
4
-if (! defined('EVENT_ESPRESSO_VERSION')) {
4
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5 5
     exit('No direct script access allowed');
6 6
 }
7 7
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
             'order_by' => $this->_get_priority_orderby(),
176 176
             'limit'    => $this->_batch_count,
177 177
         );
178
-        $messages   = EEM_Message::instance()->get_all($query_args);
178
+        $messages = EEM_Message::instance()->get_all($query_args);
179 179
 
180 180
         if ( ! $messages) {
181 181
             return false; //nothing to generate
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
      */
287 287
     protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
288 288
     {
289
-        return '_ee_lock_' . $type;
289
+        return '_ee_lock_'.$type;
290 290
     }
291 291
 
292 292
 
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
             /** @type EE_Message $message */
507 507
             $message = $this->_message_repository->current();
508 508
             //only process things that are queued for sending
509
-            if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
509
+            if ( ! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
510 510
                 $this->_message_repository->next();
511 511
                 continue;
512 512
             }
@@ -516,13 +516,13 @@  discard block
 block discarded – undo
516 516
                 continue;
517 517
             }
518 518
             //error checking
519
-            if (! $message->valid_messenger()) {
519
+            if ( ! $message->valid_messenger()) {
520 520
                 $error_messages[] = sprintf(
521 521
                     __('The %s messenger is not active at time of sending.', 'event_espresso'),
522 522
                     $message->messenger()
523 523
                 );
524 524
             }
525
-            if (! $message->valid_message_type()) {
525
+            if ( ! $message->valid_message_type()) {
526 526
                 $error_messages[] = sprintf(
527 527
                     __('The %s message type is not active at the time of sending.', 'event_espresso'),
528 528
                     $message->message_type()
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
      */
688 688
     protected function _set_error_message(EE_Message $message, $error_messages)
689 689
     {
690
-        $error_messages = (array)$error_messages;
690
+        $error_messages = (array) $error_messages;
691 691
         if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
692 692
             $notices          = EE_Error::has_notices();
693 693
             $error_messages[] = __(
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
         }
703 703
         if (count($error_messages) > 0) {
704 704
             $msg = __('Message was not executed successfully.', 'event_espresso');
705
-            $msg = $msg . "\n" . implode("\n", $error_messages);
705
+            $msg = $msg."\n".implode("\n", $error_messages);
706 706
             $message->set_error_message($msg);
707 707
         }
708 708
     }
Please login to merge, or discard this patch.
core/db_models/EEM_Status.model.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 /**
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
  * @ version            4.0
13 13
  * ------------------------------------------------------------------------
14 14
  */
15
-require_once(EE_MODELS . 'EEM_Base.model.php');
15
+require_once(EE_MODELS.'EEM_Base.model.php');
16 16
 
17 17
 /**
18 18
  * Class EEM_Status
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
                     false,
50 50
                     'event',
51 51
                     array(
52
-                        'event'        => __("Event", "event_espresso"),//deprecated
52
+                        'event'        => __("Event", "event_espresso"), //deprecated
53 53
                         'registration' => __("Registration", "event_espresso"),
54 54
                         'transaction'  => __("Transaction", "event_espresso"),
55 55
                         'payment'      => __("Payment", "event_espresso"),
Please login to merge, or discard this patch.
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -25,291 +25,291 @@  discard block
 block discarded – undo
25 25
 class EEM_Status extends EEM_Base
26 26
 {
27 27
 
28
-    // private instance of the Attendee object
29
-    protected static $_instance = null;
28
+	// private instance of the Attendee object
29
+	protected static $_instance = null;
30 30
 
31 31
 
32
-    /**
33
-     * @return EEM_Status
34
-     */
35
-    protected function __construct($timezone = null)
36
-    {
37
-        $this->singular_item    = __('Status', 'event_espresso');
38
-        $this->plural_item      = __('Stati', 'event_espresso');
39
-        $this->_tables          = array(
40
-            'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
-        );
42
-        $this->_fields          = array(
43
-            'StatusTable' => array(
44
-                'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
-                'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
-                'STS_type'     => new EE_Enum_Text_Field(
47
-                    'STS_type',
48
-                    __("Type", "event_espresso"),
49
-                    false,
50
-                    'event',
51
-                    array(
52
-                        'event'        => __("Event", "event_espresso"),//deprecated
53
-                        'registration' => __("Registration", "event_espresso"),
54
-                        'transaction'  => __("Transaction", "event_espresso"),
55
-                        'payment'      => __("Payment", "event_espresso"),
56
-                        'email'        => __("Email", "event_espresso"),
57
-                        'message'      => __("Message", "event_espresso"),
58
-                    )),
59
-                'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false, false),
60
-                'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
-                'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
-            ),
63
-        );
64
-        $this->_model_relations = array(
65
-            'Registration' => new EE_Has_Many_Relation(),
66
-            'Transaction'  => new EE_Has_Many_Relation(),
67
-            'Payment'      => new EE_Has_Many_Relation(),
68
-        );
69
-        //this model is generally available for reading
70
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
32
+	/**
33
+	 * @return EEM_Status
34
+	 */
35
+	protected function __construct($timezone = null)
36
+	{
37
+		$this->singular_item    = __('Status', 'event_espresso');
38
+		$this->plural_item      = __('Stati', 'event_espresso');
39
+		$this->_tables          = array(
40
+			'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
+		);
42
+		$this->_fields          = array(
43
+			'StatusTable' => array(
44
+				'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
+				'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
+				'STS_type'     => new EE_Enum_Text_Field(
47
+					'STS_type',
48
+					__("Type", "event_espresso"),
49
+					false,
50
+					'event',
51
+					array(
52
+						'event'        => __("Event", "event_espresso"),//deprecated
53
+						'registration' => __("Registration", "event_espresso"),
54
+						'transaction'  => __("Transaction", "event_espresso"),
55
+						'payment'      => __("Payment", "event_espresso"),
56
+						'email'        => __("Email", "event_espresso"),
57
+						'message'      => __("Message", "event_espresso"),
58
+					)),
59
+				'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false, false),
60
+				'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
+				'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
+			),
63
+		);
64
+		$this->_model_relations = array(
65
+			'Registration' => new EE_Has_Many_Relation(),
66
+			'Transaction'  => new EE_Has_Many_Relation(),
67
+			'Payment'      => new EE_Has_Many_Relation(),
68
+		);
69
+		//this model is generally available for reading
70
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
71 71
 
72
-        parent::__construct($timezone);
73
-    }
72
+		parent::__construct($timezone);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * This method provides the localized singular or plural string for a given status id
78
-     *
79
-     * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
-     *                           That way if there isn't a translation in the index we'll return the default code.
81
-     * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
-     *                           same as the singular (in English), however, this may NOT be the case with other
83
-     *                           languages
84
-     * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
-     *                           the status string returned ( UPPER, lower, Sentence)
86
-     * @throws EE_Error
87
-     * @return array             an array of translated strings for the incoming status id.
88
-     */
89
-    public function localized_status($statuses, $plural = false, $schema = 'upper')
90
-    {
91
-        //note these are all in lower case because ucwords() on upper case will NOT convert.
92
-        $translation_array = array(
93
-            EEM_Registration::status_id_pending_payment => array(
94
-                __('pending payment', 'event_espresso'), //singular
95
-                __('pending payments', 'event_espresso') //plural
96
-            ),
97
-            EEM_Registration::status_id_approved        => array(
98
-                __('approved', 'event_espresso'), //singular
99
-                __('approved', 'event_espresso') //plural
100
-            ),
101
-            EEM_Registration::status_id_not_approved    => array(
102
-                __('not approved', 'event_espresso'),
103
-                __('not approved', 'event_espresso'),
104
-            ),
105
-            EEM_Registration::status_id_cancelled       => array(
106
-                __('cancelled', 'event_espresso'),
107
-                __('cancelled', 'event_espresso'),
108
-            ),
109
-            EEM_Registration::status_id_incomplete      => array(
110
-                __('incomplete', 'event_espresso'),
111
-                __('incomplete', 'event_espresso'),
112
-            ),
113
-            EEM_Registration::status_id_declined        => array(
114
-                __('declined', 'event_espresso'),
115
-                __('declined', 'event_espresso'),
116
-            ),
117
-            EEM_Registration::status_id_wait_list       => array(
118
-                __('wait list', 'event_espresso'),
119
-                __('wait list', 'event_espresso'),
120
-            ),
121
-            EEM_Transaction::overpaid_status_code       => array(
122
-                __('overpaid', 'event_espresso'),
123
-                __('overpaid', 'event_espresso'),
124
-            ),
125
-            EEM_Transaction::complete_status_code       => array(
126
-                __('complete', 'event_espresso'),
127
-                __('complete', 'event_espresso'),
128
-            ),
129
-            EEM_Transaction::incomplete_status_code     => array(
130
-                __('incomplete', 'event_espresso'),
131
-                __('incomplete', 'event_espresso'),
132
-            ),
133
-            EEM_Transaction::failed_status_code         => array(
134
-                __('failed', 'event_espresso'),
135
-                __('failed', 'event_espresso'),
136
-            ),
137
-            EEM_Transaction::abandoned_status_code      => array(
138
-                __('abandoned', 'event_espresso'),
139
-                __('abandoned', 'event_espresso'),
140
-            ),
141
-            EEM_Payment::status_id_approved             => array(
142
-                __('accepted', 'event_espresso'),
143
-                __('accepted', 'event_espresso'),
144
-            ),
145
-            EEM_Payment::status_id_pending              => array(
146
-                __('pending', 'event_espresso'),
147
-                __('pending', 'event_espresso'),
148
-            ),
149
-            EEM_Payment::status_id_cancelled            => array(
150
-                __('cancelled', 'event_espresso'),
151
-                __('cancelled', 'event_espresso'),
152
-            ),
153
-            EEM_Payment::status_id_declined             => array(
154
-                __('declined', 'event_espresso'),
155
-                __('declined', 'event_espresso'),
156
-            ),
157
-            EEM_Payment::status_id_failed               => array(
158
-                __('failed', 'event_espresso'),
159
-                __('failed', 'event_espresso'),
160
-            ),
161
-            //following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
-            EEM_Event::sold_out                         => array(
163
-                __('sold out', 'event_espresso'),
164
-                __('sold out', 'event_espresso'),
165
-            ),
166
-            EEM_Event::postponed                        => array(
167
-                __('postponed', 'event_espresso'),
168
-                __('Postponed', 'event_espresso'),
169
-            ),
170
-            EEM_Event::cancelled                        => array(
171
-                __('cancelled', 'event_espresso'),
172
-                __('cancelled', 'event_espresso'),
173
-            ),
174
-            EE_Ticket::archived                         => array(
175
-                __('archived', 'event_espresso'),
176
-                __('archived', 'event_espresso'),
177
-            ),
178
-            EE_Ticket::expired                          => array(
179
-                __('expired', 'event_espresso'),
180
-                __('expired', 'event_espresso'),
181
-            ),
182
-            EE_Ticket::sold_out                         => array(
183
-                __('sold out', 'event_espresso'),
184
-                __('sold out', 'event_espresso'),
185
-            ),
186
-            EE_Ticket::pending                          => array(
187
-                __('upcoming', 'event_espresso'),
188
-                __('upcoming', 'event_espresso'),
189
-            ),
190
-            EE_Ticket::onsale                           => array(
191
-                __('on sale', 'event_espresso'),
192
-                __('on sale', 'event_espresso'),
193
-            ),
194
-            EE_Datetime::cancelled                      => array(
195
-                __('cancelled', 'event_espresso'),
196
-                __('cancelled', 'event_espresso'),
197
-            ),
198
-            EE_Datetime::sold_out                       => array(
199
-                __('sold out', 'event_espresso'),
200
-                __('sold out', 'event_espresso'),
201
-            ),
202
-            EE_Datetime::expired                        => array(
203
-                __('expired', 'event_espresso'),
204
-                __('expired', 'event_espresso'),
205
-            ),
206
-            EE_Datetime::inactive                       => array(
207
-                __('inactive', 'event_espresso'),
208
-                __('inactive', 'event_espresso'),
209
-            ),
210
-            EE_Datetime::upcoming                       => array(
211
-                __('upcoming', 'event_espresso'),
212
-                __('upcoming', 'event_espresso'),
213
-            ),
214
-            EE_Datetime::active                         => array(
215
-                __('active', 'event_espresso'),
216
-                __('active', 'event_espresso'),
217
-            ),
218
-            EE_Datetime::postponed                      => array(
219
-                __('postponed', 'event_espresso'),
220
-                __('postponed', 'event_espresso'),
221
-            ),
222
-            //messages related
223
-            EEM_Message::status_sent                    => array(
224
-                __('sent', 'event_espresso'),
225
-                __('sent', 'event_espresso'),
226
-            ),
227
-            EEM_Message::status_idle                    => array(
228
-                __('queued for sending', 'event_espresso'),
229
-                __('queued for sending', 'event_espresso'),
230
-            ),
231
-            EEM_Message::status_failed                  => array(
232
-                __('failed', 'event_espresso'),
233
-                __('failed', 'event_espresso'),
234
-            ),
235
-            EEM_Message::status_debug_only              => array(
236
-                __('debug only', 'event_espresso'),
237
-                __('debug only', 'event_espresso'),
238
-            ),
239
-            EEM_Message::status_messenger_executing     => array(
240
-                __('messenger is executing', 'event_espresso'),
241
-                __('messenger is executing', 'event_espresso'),
242
-            ),
243
-            EEM_Message::status_resend                  => array(
244
-                __('queued for resending', 'event_espresso'),
245
-                __('queued for resending', 'event_espresso'),
246
-            ),
247
-            EEM_Message::status_incomplete              => array(
248
-                __('queued for generating', 'event_espresso'),
249
-                __('queued for generating', 'event_espresso'),
250
-            ),
251
-            EEM_Message::status_retry                   => array(
252
-                __('failed sending, can be retried', 'event_espresso'),
253
-                __('failed sending, can be retried', 'event_espresso'),
254
-            ),
255
-            EEM_CPT_Base::post_status_publish           => array(
256
-                __('published', 'event_espresso'),
257
-                __('published', 'event_espresso'),
258
-            ),
259
-            EEM_CPT_Base::post_status_future            => array(
260
-                __('scheduled', 'event_espresso'),
261
-                __('scheduled', 'event_espresso'),
262
-            ),
263
-            EEM_CPT_Base::post_status_draft             => array(
264
-                __('draft', 'event_espresso'),
265
-                __('draft', 'event_espresso'),
266
-            ),
267
-            EEM_CPT_Base::post_status_pending           => array(
268
-                __('pending', 'event_espresso'),
269
-                __('pending', 'event_espresso'),
270
-            ),
271
-            EEM_CPT_Base::post_status_private           => array(
272
-                __('private', 'event_espresso'),
273
-                __('private', 'event_espresso'),
274
-            ),
275
-            EEM_CPT_Base::post_status_trashed           => array(
276
-                __('trashed', 'event_espresso'),
277
-                __('trashed', 'event_espresso'),
278
-            ),
279
-        );
76
+	/**
77
+	 * This method provides the localized singular or plural string for a given status id
78
+	 *
79
+	 * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
+	 *                           That way if there isn't a translation in the index we'll return the default code.
81
+	 * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
+	 *                           same as the singular (in English), however, this may NOT be the case with other
83
+	 *                           languages
84
+	 * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
+	 *                           the status string returned ( UPPER, lower, Sentence)
86
+	 * @throws EE_Error
87
+	 * @return array             an array of translated strings for the incoming status id.
88
+	 */
89
+	public function localized_status($statuses, $plural = false, $schema = 'upper')
90
+	{
91
+		//note these are all in lower case because ucwords() on upper case will NOT convert.
92
+		$translation_array = array(
93
+			EEM_Registration::status_id_pending_payment => array(
94
+				__('pending payment', 'event_espresso'), //singular
95
+				__('pending payments', 'event_espresso') //plural
96
+			),
97
+			EEM_Registration::status_id_approved        => array(
98
+				__('approved', 'event_espresso'), //singular
99
+				__('approved', 'event_espresso') //plural
100
+			),
101
+			EEM_Registration::status_id_not_approved    => array(
102
+				__('not approved', 'event_espresso'),
103
+				__('not approved', 'event_espresso'),
104
+			),
105
+			EEM_Registration::status_id_cancelled       => array(
106
+				__('cancelled', 'event_espresso'),
107
+				__('cancelled', 'event_espresso'),
108
+			),
109
+			EEM_Registration::status_id_incomplete      => array(
110
+				__('incomplete', 'event_espresso'),
111
+				__('incomplete', 'event_espresso'),
112
+			),
113
+			EEM_Registration::status_id_declined        => array(
114
+				__('declined', 'event_espresso'),
115
+				__('declined', 'event_espresso'),
116
+			),
117
+			EEM_Registration::status_id_wait_list       => array(
118
+				__('wait list', 'event_espresso'),
119
+				__('wait list', 'event_espresso'),
120
+			),
121
+			EEM_Transaction::overpaid_status_code       => array(
122
+				__('overpaid', 'event_espresso'),
123
+				__('overpaid', 'event_espresso'),
124
+			),
125
+			EEM_Transaction::complete_status_code       => array(
126
+				__('complete', 'event_espresso'),
127
+				__('complete', 'event_espresso'),
128
+			),
129
+			EEM_Transaction::incomplete_status_code     => array(
130
+				__('incomplete', 'event_espresso'),
131
+				__('incomplete', 'event_espresso'),
132
+			),
133
+			EEM_Transaction::failed_status_code         => array(
134
+				__('failed', 'event_espresso'),
135
+				__('failed', 'event_espresso'),
136
+			),
137
+			EEM_Transaction::abandoned_status_code      => array(
138
+				__('abandoned', 'event_espresso'),
139
+				__('abandoned', 'event_espresso'),
140
+			),
141
+			EEM_Payment::status_id_approved             => array(
142
+				__('accepted', 'event_espresso'),
143
+				__('accepted', 'event_espresso'),
144
+			),
145
+			EEM_Payment::status_id_pending              => array(
146
+				__('pending', 'event_espresso'),
147
+				__('pending', 'event_espresso'),
148
+			),
149
+			EEM_Payment::status_id_cancelled            => array(
150
+				__('cancelled', 'event_espresso'),
151
+				__('cancelled', 'event_espresso'),
152
+			),
153
+			EEM_Payment::status_id_declined             => array(
154
+				__('declined', 'event_espresso'),
155
+				__('declined', 'event_espresso'),
156
+			),
157
+			EEM_Payment::status_id_failed               => array(
158
+				__('failed', 'event_espresso'),
159
+				__('failed', 'event_espresso'),
160
+			),
161
+			//following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
+			EEM_Event::sold_out                         => array(
163
+				__('sold out', 'event_espresso'),
164
+				__('sold out', 'event_espresso'),
165
+			),
166
+			EEM_Event::postponed                        => array(
167
+				__('postponed', 'event_espresso'),
168
+				__('Postponed', 'event_espresso'),
169
+			),
170
+			EEM_Event::cancelled                        => array(
171
+				__('cancelled', 'event_espresso'),
172
+				__('cancelled', 'event_espresso'),
173
+			),
174
+			EE_Ticket::archived                         => array(
175
+				__('archived', 'event_espresso'),
176
+				__('archived', 'event_espresso'),
177
+			),
178
+			EE_Ticket::expired                          => array(
179
+				__('expired', 'event_espresso'),
180
+				__('expired', 'event_espresso'),
181
+			),
182
+			EE_Ticket::sold_out                         => array(
183
+				__('sold out', 'event_espresso'),
184
+				__('sold out', 'event_espresso'),
185
+			),
186
+			EE_Ticket::pending                          => array(
187
+				__('upcoming', 'event_espresso'),
188
+				__('upcoming', 'event_espresso'),
189
+			),
190
+			EE_Ticket::onsale                           => array(
191
+				__('on sale', 'event_espresso'),
192
+				__('on sale', 'event_espresso'),
193
+			),
194
+			EE_Datetime::cancelled                      => array(
195
+				__('cancelled', 'event_espresso'),
196
+				__('cancelled', 'event_espresso'),
197
+			),
198
+			EE_Datetime::sold_out                       => array(
199
+				__('sold out', 'event_espresso'),
200
+				__('sold out', 'event_espresso'),
201
+			),
202
+			EE_Datetime::expired                        => array(
203
+				__('expired', 'event_espresso'),
204
+				__('expired', 'event_espresso'),
205
+			),
206
+			EE_Datetime::inactive                       => array(
207
+				__('inactive', 'event_espresso'),
208
+				__('inactive', 'event_espresso'),
209
+			),
210
+			EE_Datetime::upcoming                       => array(
211
+				__('upcoming', 'event_espresso'),
212
+				__('upcoming', 'event_espresso'),
213
+			),
214
+			EE_Datetime::active                         => array(
215
+				__('active', 'event_espresso'),
216
+				__('active', 'event_espresso'),
217
+			),
218
+			EE_Datetime::postponed                      => array(
219
+				__('postponed', 'event_espresso'),
220
+				__('postponed', 'event_espresso'),
221
+			),
222
+			//messages related
223
+			EEM_Message::status_sent                    => array(
224
+				__('sent', 'event_espresso'),
225
+				__('sent', 'event_espresso'),
226
+			),
227
+			EEM_Message::status_idle                    => array(
228
+				__('queued for sending', 'event_espresso'),
229
+				__('queued for sending', 'event_espresso'),
230
+			),
231
+			EEM_Message::status_failed                  => array(
232
+				__('failed', 'event_espresso'),
233
+				__('failed', 'event_espresso'),
234
+			),
235
+			EEM_Message::status_debug_only              => array(
236
+				__('debug only', 'event_espresso'),
237
+				__('debug only', 'event_espresso'),
238
+			),
239
+			EEM_Message::status_messenger_executing     => array(
240
+				__('messenger is executing', 'event_espresso'),
241
+				__('messenger is executing', 'event_espresso'),
242
+			),
243
+			EEM_Message::status_resend                  => array(
244
+				__('queued for resending', 'event_espresso'),
245
+				__('queued for resending', 'event_espresso'),
246
+			),
247
+			EEM_Message::status_incomplete              => array(
248
+				__('queued for generating', 'event_espresso'),
249
+				__('queued for generating', 'event_espresso'),
250
+			),
251
+			EEM_Message::status_retry                   => array(
252
+				__('failed sending, can be retried', 'event_espresso'),
253
+				__('failed sending, can be retried', 'event_espresso'),
254
+			),
255
+			EEM_CPT_Base::post_status_publish           => array(
256
+				__('published', 'event_espresso'),
257
+				__('published', 'event_espresso'),
258
+			),
259
+			EEM_CPT_Base::post_status_future            => array(
260
+				__('scheduled', 'event_espresso'),
261
+				__('scheduled', 'event_espresso'),
262
+			),
263
+			EEM_CPT_Base::post_status_draft             => array(
264
+				__('draft', 'event_espresso'),
265
+				__('draft', 'event_espresso'),
266
+			),
267
+			EEM_CPT_Base::post_status_pending           => array(
268
+				__('pending', 'event_espresso'),
269
+				__('pending', 'event_espresso'),
270
+			),
271
+			EEM_CPT_Base::post_status_private           => array(
272
+				__('private', 'event_espresso'),
273
+				__('private', 'event_espresso'),
274
+			),
275
+			EEM_CPT_Base::post_status_trashed           => array(
276
+				__('trashed', 'event_espresso'),
277
+				__('trashed', 'event_espresso'),
278
+			),
279
+		);
280 280
 
281
-        $translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
281
+		$translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
282 282
 
283
-        if ( ! is_array($statuses)) {
284
-            throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
-                'event_espresso'));
286
-        }
283
+		if ( ! is_array($statuses)) {
284
+			throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
+				'event_espresso'));
286
+		}
287 287
 
288
-        $translation = array();
288
+		$translation = array();
289 289
 
290
-        foreach ($statuses as $id => $code) {
291
-            if (isset($translation_array[$id])) {
292
-                $translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
-            } else {
294
-                $translation[$id] = $code;
295
-            }
290
+		foreach ($statuses as $id => $code) {
291
+			if (isset($translation_array[$id])) {
292
+				$translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
+			} else {
294
+				$translation[$id] = $code;
295
+			}
296 296
 
297
-            //schema
298
-            switch ($schema) {
299
-                case 'lower' :
300
-                    $translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
-                    break;
302
-                case 'sentence' :
303
-                    $translation[$id] = ucwords($translation[$id]);
304
-                    break;
305
-                case 'upper' :
306
-                    $translation[$id] = strtoupper($translation[$id]);
307
-                    break;
308
-            }
309
-        }
297
+			//schema
298
+			switch ($schema) {
299
+				case 'lower' :
300
+					$translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
+					break;
302
+				case 'sentence' :
303
+					$translation[$id] = ucwords($translation[$id]);
304
+					break;
305
+				case 'upper' :
306
+					$translation[$id] = strtoupper($translation[$id]);
307
+					break;
308
+			}
309
+		}
310 310
 
311
-        return $translation;
312
-    }
311
+		return $translation;
312
+	}
313 313
 
314 314
 
315 315
 }
Please login to merge, or discard this patch.
admin_pages/messages/EE_Message_List_Table.class.php 2 patches
Indentation   +427 added lines, -427 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 
6 6
 /**
@@ -15,430 +15,430 @@  discard block
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * @return Messages_Admin_Page
20
-     */
21
-    public function get_admin_page()
22
-    {
23
-        return $this->_admin_page;
24
-    }
25
-
26
-
27
-    protected function _setup_data()
28
-    {
29
-        $this->_data           = $this->_get_messages($this->_per_page, $this->_view);
30
-        $this->_all_data_count = $this->_get_messages($this->_per_page, $this->_view, true);
31
-    }
32
-
33
-
34
-    protected function _set_properties()
35
-    {
36
-        $this->_wp_list_args = array(
37
-            'singular' => __('Message', 'event_espresso'),
38
-            'plural'   => __('Messages', 'event_espresso'),
39
-            'ajax'     => true,
40
-            'screen'   => $this->get_admin_page()->get_current_screen()->id,
41
-        );
42
-
43
-        $this->_columns = array(
44
-            'cb'           => '<input type="checkbox" />',
45
-            'to'           => __('To', 'event_espresso'),
46
-            'from'         => __('From', 'event_espresso'),
47
-            'messenger'    => __('Messenger', 'event_espresso'),
48
-            'message_type' => __('Message Type', 'event_espresso'),
49
-            'context'      => __('Context', 'event_espresso'),
50
-            'modified'     => __('Modified', 'event_espresso'),
51
-            'action'       => __('Actions', 'event_espresso'),
52
-            'msg_id'       => __('ID', 'event_espresso'),
53
-        );
54
-
55
-        $this->_sortable_columns = array(
56
-            'modified'     => array('MSG_modified' => true),
57
-            'message_type' => array('MSG_message_type' => false),
58
-            'messenger'    => array('MSG_messenger' => false),
59
-            'to'           => array('MSG_to' => false),
60
-            'from'         => array('MSG_from' => false),
61
-            'context'      => array('MSG_context' => false),
62
-            'msg_id'       => array('MSG_ID', false),
63
-        );
64
-
65
-        $this->_primary_column = 'to';
66
-
67
-        $this->_hidden_columns = array(
68
-            'msg_id',
69
-        );
70
-    }
71
-
72
-
73
-    /**
74
-     * This simply sets up the row class for the table rows.
75
-     * Allows for easier overriding of child methods for setting up sorting.
76
-     *
77
-     * @param  object $item the current item
78
-     * @return string
79
-     */
80
-    protected function _get_row_class($item)
81
-    {
82
-        $class = parent::_get_row_class($item);
83
-        //add status class
84
-        $class .= ' ee-status-strip msg-status-' . $item->STS_ID();
85
-        if ($this->_has_checkbox_column) {
86
-            $class .= ' has-checkbox-column';
87
-        }
88
-        return $class;
89
-    }
90
-
91
-
92
-    /**
93
-     * _get_table_filters
94
-     * We use this to assemble and return any filters that are associated with this table that help further refine what
95
-     * get's shown in the table.
96
-     *
97
-     * @abstract
98
-     * @access protected
99
-     * @return string
100
-     * @throws \EE_Error
101
-     */
102
-    protected function _get_table_filters()
103
-    {
104
-        $filters = array();
105
-
106
-        //get select_inputs
107
-        $select_inputs = array(
108
-            $this->_get_messengers_dropdown_filter(),
109
-            $this->_get_message_types_dropdown_filter(),
110
-            $this->_get_contexts_for_message_types_dropdown_filter(),
111
-        );
112
-
113
-        //set filters to select inputs if they aren't empty
114
-        foreach ($select_inputs as $select_input) {
115
-            if ($select_input) {
116
-                $filters[] = $select_input;
117
-            }
118
-        }
119
-        return $filters;
120
-    }
121
-
122
-
123
-    protected function _add_view_counts()
124
-    {
125
-        foreach ($this->_views as $view => $args) {
126
-            $this->_views[$view]['count'] = $this->_get_messages($this->_per_page, $view, true, true);
127
-        }
128
-    }
129
-
130
-
131
-    /**
132
-     * @param EE_Message $message
133
-     * @return string   checkbox
134
-     * @throws \EE_Error
135
-     */
136
-    public function column_cb($message)
137
-    {
138
-        return sprintf('<input type="checkbox" name="MSG_ID[%s]" value="1" />', $message->ID());
139
-    }
140
-
141
-
142
-    /**
143
-     * @param EE_Message $message
144
-     * @return string
145
-     * @throws \EE_Error
146
-     */
147
-    public function column_msg_id(EE_Message $message)
148
-    {
149
-        return $message->ID();
150
-    }
151
-
152
-
153
-    /**
154
-     * @param EE_Message $message
155
-     * @return string    The recipient of the message
156
-     * @throws \EE_Error
157
-     */
158
-    public function column_to(EE_Message $message)
159
-    {
160
-        EE_Registry::instance()->load_helper('URL');
161
-        $actions           = array();
162
-        $actions['delete'] = '<a href="'
163
-                             . EEH_URL::add_query_args_and_nonce(
164
-                array(
165
-                    'page'   => 'espresso_messages',
166
-                    'action' => 'delete_ee_message',
167
-                    'MSG_ID' => $message->ID(),
168
-                ),
169
-                admin_url('admin.php')
170
-            )
171
-                             . '">' . __('Delete', 'event_espresso') . '</a>';
172
-        return esc_html($message->to()) . $this->row_actions($actions);
173
-    }
174
-
175
-
176
-    /**
177
-     * @param EE_Message $message
178
-     * @return string   The sender of the message
179
-     */
180
-    public function column_from(EE_Message $message)
181
-    {
182
-        return esc_html($message->from());
183
-    }
184
-
185
-
186
-    /**
187
-     * @param EE_Message $message
188
-     * @return string  The messenger used to send the message.
189
-     */
190
-    public function column_messenger(EE_Message $message)
191
-    {
192
-        return ucwords($message->messenger_label());
193
-    }
194
-
195
-
196
-    /**
197
-     * @param EE_Message $message
198
-     * @return string  The message type used to generate the message.
199
-     */
200
-    public function column_message_type(EE_Message $message)
201
-    {
202
-        return ucwords($message->message_type_label());
203
-    }
204
-
205
-
206
-    /**
207
-     * @param EE_Message $message
208
-     * @return string  The context the message was generated for.
209
-     */
210
-    public function column_context(EE_Message $message)
211
-    {
212
-        return $message->context_label();
213
-    }
214
-
215
-
216
-    /**
217
-     * @param EE_Message $message
218
-     * @return string    The timestamp when this message was last modified.
219
-     */
220
-    public function column_modified(EE_Message $message)
221
-    {
222
-        return $message->modified();
223
-    }
224
-
225
-
226
-    /**
227
-     * @param EE_Message $message
228
-     * @return string   Actions that can be done on the current message.
229
-     */
230
-    public function column_action(EE_Message $message)
231
-    {
232
-        EE_Registry::instance()->load_helper('MSG_Template');
233
-        $action_links = array(
234
-            'view'                => EEH_MSG_Template::get_message_action_link('view', $message),
235
-            'error'               => EEH_MSG_Template::get_message_action_link('error', $message),
236
-            'generate_now'        => EEH_MSG_Template::get_message_action_link('generate_now', $message),
237
-            'send_now'            => EEH_MSG_Template::get_message_action_link('send_now', $message),
238
-            'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239
-            'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240
-        );
241
-        $content      = '';
242
-        switch ($message->STS_ID()) {
243
-            case EEM_Message::status_sent :
244
-                $content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
245
-                break;
246
-            case EEM_Message::status_resend :
247
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
248
-                break;
249
-            case EEM_Message::status_retry :
250
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
251
-                break;
252
-            case EEM_Message::status_failed :
253
-            case EEM_Message::status_debug_only :
254
-                $content = $action_links['error'] . $action_links['view_transaction'];
255
-                break;
256
-            case EEM_Message::status_idle :
257
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
258
-                break;
259
-            case EEM_Message::status_incomplete;
260
-                $content = $action_links['generate_now'] . $action_links['view_transaction'];
261
-                break;
262
-        }
263
-        return $content;
264
-    }
265
-
266
-
267
-    /**
268
-     * Retrieve the EE_Message objects for the list table.
269
-     *
270
-     * @param int    $perpage The number of items per page
271
-     * @param string $view    The view items are being retrieved for
272
-     * @param bool   $count   Whether to just return a count or not.
273
-     * @param bool   $all     Disregard any paging info (no limit on data returned).
274
-     * @return int|EE_Message[]
275
-     * @throws \EE_Error
276
-     */
277
-    protected function _get_messages($perpage = 10, $view = 'all', $count = false, $all = false)
278
-    {
279
-
280
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
281
-            ? $this->_req_data['paged']
282
-            : 1;
283
-
284
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
285
-            ? $this->_req_data['perpage']
286
-            : $perpage;
287
-
288
-        $offset       = ($current_page - 1) * $per_page;
289
-        $limit        = $all || $count ? null : array($offset, $per_page);
290
-        $query_params = array(
291
-            'order_by' => empty($this->_req_data['orderby']) ? 'MSG_modified' : $this->_req_data['orderby'],
292
-            'order'    => empty($this->_req_data['order']) ? 'DESC' : $this->_req_data['order'],
293
-            'limit'    => $limit,
294
-        );
295
-
296
-        /**
297
-         * Any filters coming in from other routes?
298
-         */
299
-        if (isset($this->_req_data['filterby'])) {
300
-            $query_params = array_merge($query_params, EEM_Message::instance()->filter_by_query_params());
301
-            if ( ! $count) {
302
-                $query_params['group_by'] = 'MSG_ID';
303
-            }
304
-        }
305
-
306
-        //view conditionals
307
-        if ($view !== 'all' && $count && $all) {
308
-            $query_params[0]['AND*view_conditional'] = array(
309
-                'STS_ID' => strtoupper($view),
310
-            );
311
-        }
312
-
313
-        if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314
-            $query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315
-                ? array(
316
-                    'STS_ID' => array(
317
-                        'IN',
318
-                        array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319
-                    )
320
-                )
321
-                : array( 'STS_ID' => strtoupper($this->_req_data['status']) );
322
-        }
323
-
324
-        if (! $all && ! empty($this->_req_data['s'])) {
325
-            $search_string         = '%' . $this->_req_data['s'] . '%';
326
-            $query_params[0]['OR'] = array(
327
-                'MSG_to'      => array('LIKE', $search_string),
328
-                'MSG_from'    => array('LIKE', $search_string),
329
-                'MSG_subject' => array('LIKE', $search_string),
330
-                'MSG_content' => array('LIKE', $search_string),
331
-            );
332
-        }
333
-
334
-        //account for debug only status.  We don't show Messages with the EEM_Message::status_debug_only to clients when
335
-        //the messages system is in debug mode.
336
-        //Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337
-        //messages in the database.
338
-        if (! EEM_Message::debug()) {
339
-            $query_params[0]['AND*debug_only_conditional'] = array(
340
-                'STS_ID' => array('!=', EEM_Message::status_debug_only),
341
-            );
342
-        }
343
-
344
-        //account for filters
345
-        if (! $all
346
-            && isset($this->_req_data['ee_messenger_filter_by'])
347
-            && $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348
-        ) {
349
-            $query_params[0]['AND*messenger_filter'] = array(
350
-                'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351
-            );
352
-        }
353
-        if (! $all
354
-            && ! empty($this->_req_data['ee_message_type_filter_by'])
355
-            && $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356
-        ) {
357
-            $query_params[0]['AND*message_type_filter'] = array(
358
-                'MSG_message_type' => $this->_req_data['ee_message_type_filter_by'],
359
-            );
360
-        }
361
-
362
-        if (! $all
363
-            && ! empty($this->_req_data['ee_context_filter_by'])
364
-            && $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365
-        ) {
366
-            $query_params[0]['AND*context_filter'] = array(
367
-                'MSG_context' => array('IN', explode(',', $this->_req_data['ee_context_filter_by'])),
368
-            );
369
-        }
370
-
371
-        return $count
372
-            /** @type int */
373
-            ? EEM_Message::instance()->count($query_params, null, true)
374
-            /** @type EE_Message[] */
375
-            : EEM_Message::instance()->get_all($query_params);
376
-    }
377
-
378
-
379
-    /**
380
-     * Generate dropdown filter select input for messengers.
381
-     *
382
-     * @return string
383
-     */
384
-    protected function _get_messengers_dropdown_filter()
385
-    {
386
-        $messenger_options                    = array();
387
-        $active_messages_grouped_by_messenger = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
388
-
389
-        //setup array of messenger options
390
-        foreach ($active_messages_grouped_by_messenger as $active_message) {
391
-            if ($active_message instanceof EE_Message) {
392
-                $messenger_options[$active_message->messenger()] = ucwords($active_message->messenger_label());
393
-            }
394
-        }
395
-        return $this->get_admin_page()->get_messengers_select_input($messenger_options);
396
-    }
397
-
398
-
399
-    /**
400
-     * Generate dropdown filter select input for message types
401
-     *
402
-     * @return string
403
-     */
404
-    protected function _get_message_types_dropdown_filter()
405
-    {
406
-        $message_type_options                    = array();
407
-        $active_messages_grouped_by_message_type = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
408
-
409
-        //setup array of message type options
410
-        foreach ($active_messages_grouped_by_message_type as $active_message) {
411
-            if ($active_message instanceof EE_Message) {
412
-                $message_type_options[$active_message->message_type()] = ucwords($active_message->message_type_label());
413
-            }
414
-        }
415
-        return $this->get_admin_page()->get_message_types_select_input($message_type_options);
416
-    }
417
-
418
-
419
-    /**
420
-     * Generate dropdown filter select input for message type contexts
421
-     *
422
-     * @return string
423
-     */
424
-    protected function _get_contexts_for_message_types_dropdown_filter()
425
-    {
426
-        $context_options                    = array();
427
-        $active_messages_grouped_by_context = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
428
-
429
-        //setup array of context options
430
-        foreach ($active_messages_grouped_by_context as $active_message) {
431
-            if ($active_message instanceof EE_Message) {
432
-                $message_type = $active_message->message_type_object();
433
-                if ($message_type instanceof EE_message_type) {
434
-                    foreach ($message_type->get_contexts() as $context => $context_details) {
435
-                        if (isset($context_details['label'])) {
436
-                            $context_options[$context] = $context_details['label'];
437
-                        }
438
-                    }
439
-                }
440
-            }
441
-        }
442
-        return $this->get_admin_page()->get_contexts_for_message_types_select_input($context_options);
443
-    }
18
+	/**
19
+	 * @return Messages_Admin_Page
20
+	 */
21
+	public function get_admin_page()
22
+	{
23
+		return $this->_admin_page;
24
+	}
25
+
26
+
27
+	protected function _setup_data()
28
+	{
29
+		$this->_data           = $this->_get_messages($this->_per_page, $this->_view);
30
+		$this->_all_data_count = $this->_get_messages($this->_per_page, $this->_view, true);
31
+	}
32
+
33
+
34
+	protected function _set_properties()
35
+	{
36
+		$this->_wp_list_args = array(
37
+			'singular' => __('Message', 'event_espresso'),
38
+			'plural'   => __('Messages', 'event_espresso'),
39
+			'ajax'     => true,
40
+			'screen'   => $this->get_admin_page()->get_current_screen()->id,
41
+		);
42
+
43
+		$this->_columns = array(
44
+			'cb'           => '<input type="checkbox" />',
45
+			'to'           => __('To', 'event_espresso'),
46
+			'from'         => __('From', 'event_espresso'),
47
+			'messenger'    => __('Messenger', 'event_espresso'),
48
+			'message_type' => __('Message Type', 'event_espresso'),
49
+			'context'      => __('Context', 'event_espresso'),
50
+			'modified'     => __('Modified', 'event_espresso'),
51
+			'action'       => __('Actions', 'event_espresso'),
52
+			'msg_id'       => __('ID', 'event_espresso'),
53
+		);
54
+
55
+		$this->_sortable_columns = array(
56
+			'modified'     => array('MSG_modified' => true),
57
+			'message_type' => array('MSG_message_type' => false),
58
+			'messenger'    => array('MSG_messenger' => false),
59
+			'to'           => array('MSG_to' => false),
60
+			'from'         => array('MSG_from' => false),
61
+			'context'      => array('MSG_context' => false),
62
+			'msg_id'       => array('MSG_ID', false),
63
+		);
64
+
65
+		$this->_primary_column = 'to';
66
+
67
+		$this->_hidden_columns = array(
68
+			'msg_id',
69
+		);
70
+	}
71
+
72
+
73
+	/**
74
+	 * This simply sets up the row class for the table rows.
75
+	 * Allows for easier overriding of child methods for setting up sorting.
76
+	 *
77
+	 * @param  object $item the current item
78
+	 * @return string
79
+	 */
80
+	protected function _get_row_class($item)
81
+	{
82
+		$class = parent::_get_row_class($item);
83
+		//add status class
84
+		$class .= ' ee-status-strip msg-status-' . $item->STS_ID();
85
+		if ($this->_has_checkbox_column) {
86
+			$class .= ' has-checkbox-column';
87
+		}
88
+		return $class;
89
+	}
90
+
91
+
92
+	/**
93
+	 * _get_table_filters
94
+	 * We use this to assemble and return any filters that are associated with this table that help further refine what
95
+	 * get's shown in the table.
96
+	 *
97
+	 * @abstract
98
+	 * @access protected
99
+	 * @return string
100
+	 * @throws \EE_Error
101
+	 */
102
+	protected function _get_table_filters()
103
+	{
104
+		$filters = array();
105
+
106
+		//get select_inputs
107
+		$select_inputs = array(
108
+			$this->_get_messengers_dropdown_filter(),
109
+			$this->_get_message_types_dropdown_filter(),
110
+			$this->_get_contexts_for_message_types_dropdown_filter(),
111
+		);
112
+
113
+		//set filters to select inputs if they aren't empty
114
+		foreach ($select_inputs as $select_input) {
115
+			if ($select_input) {
116
+				$filters[] = $select_input;
117
+			}
118
+		}
119
+		return $filters;
120
+	}
121
+
122
+
123
+	protected function _add_view_counts()
124
+	{
125
+		foreach ($this->_views as $view => $args) {
126
+			$this->_views[$view]['count'] = $this->_get_messages($this->_per_page, $view, true, true);
127
+		}
128
+	}
129
+
130
+
131
+	/**
132
+	 * @param EE_Message $message
133
+	 * @return string   checkbox
134
+	 * @throws \EE_Error
135
+	 */
136
+	public function column_cb($message)
137
+	{
138
+		return sprintf('<input type="checkbox" name="MSG_ID[%s]" value="1" />', $message->ID());
139
+	}
140
+
141
+
142
+	/**
143
+	 * @param EE_Message $message
144
+	 * @return string
145
+	 * @throws \EE_Error
146
+	 */
147
+	public function column_msg_id(EE_Message $message)
148
+	{
149
+		return $message->ID();
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param EE_Message $message
155
+	 * @return string    The recipient of the message
156
+	 * @throws \EE_Error
157
+	 */
158
+	public function column_to(EE_Message $message)
159
+	{
160
+		EE_Registry::instance()->load_helper('URL');
161
+		$actions           = array();
162
+		$actions['delete'] = '<a href="'
163
+							 . EEH_URL::add_query_args_and_nonce(
164
+				array(
165
+					'page'   => 'espresso_messages',
166
+					'action' => 'delete_ee_message',
167
+					'MSG_ID' => $message->ID(),
168
+				),
169
+				admin_url('admin.php')
170
+			)
171
+							 . '">' . __('Delete', 'event_espresso') . '</a>';
172
+		return esc_html($message->to()) . $this->row_actions($actions);
173
+	}
174
+
175
+
176
+	/**
177
+	 * @param EE_Message $message
178
+	 * @return string   The sender of the message
179
+	 */
180
+	public function column_from(EE_Message $message)
181
+	{
182
+		return esc_html($message->from());
183
+	}
184
+
185
+
186
+	/**
187
+	 * @param EE_Message $message
188
+	 * @return string  The messenger used to send the message.
189
+	 */
190
+	public function column_messenger(EE_Message $message)
191
+	{
192
+		return ucwords($message->messenger_label());
193
+	}
194
+
195
+
196
+	/**
197
+	 * @param EE_Message $message
198
+	 * @return string  The message type used to generate the message.
199
+	 */
200
+	public function column_message_type(EE_Message $message)
201
+	{
202
+		return ucwords($message->message_type_label());
203
+	}
204
+
205
+
206
+	/**
207
+	 * @param EE_Message $message
208
+	 * @return string  The context the message was generated for.
209
+	 */
210
+	public function column_context(EE_Message $message)
211
+	{
212
+		return $message->context_label();
213
+	}
214
+
215
+
216
+	/**
217
+	 * @param EE_Message $message
218
+	 * @return string    The timestamp when this message was last modified.
219
+	 */
220
+	public function column_modified(EE_Message $message)
221
+	{
222
+		return $message->modified();
223
+	}
224
+
225
+
226
+	/**
227
+	 * @param EE_Message $message
228
+	 * @return string   Actions that can be done on the current message.
229
+	 */
230
+	public function column_action(EE_Message $message)
231
+	{
232
+		EE_Registry::instance()->load_helper('MSG_Template');
233
+		$action_links = array(
234
+			'view'                => EEH_MSG_Template::get_message_action_link('view', $message),
235
+			'error'               => EEH_MSG_Template::get_message_action_link('error', $message),
236
+			'generate_now'        => EEH_MSG_Template::get_message_action_link('generate_now', $message),
237
+			'send_now'            => EEH_MSG_Template::get_message_action_link('send_now', $message),
238
+			'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239
+			'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240
+		);
241
+		$content      = '';
242
+		switch ($message->STS_ID()) {
243
+			case EEM_Message::status_sent :
244
+				$content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
245
+				break;
246
+			case EEM_Message::status_resend :
247
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
248
+				break;
249
+			case EEM_Message::status_retry :
250
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
251
+				break;
252
+			case EEM_Message::status_failed :
253
+			case EEM_Message::status_debug_only :
254
+				$content = $action_links['error'] . $action_links['view_transaction'];
255
+				break;
256
+			case EEM_Message::status_idle :
257
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
258
+				break;
259
+			case EEM_Message::status_incomplete;
260
+				$content = $action_links['generate_now'] . $action_links['view_transaction'];
261
+				break;
262
+		}
263
+		return $content;
264
+	}
265
+
266
+
267
+	/**
268
+	 * Retrieve the EE_Message objects for the list table.
269
+	 *
270
+	 * @param int    $perpage The number of items per page
271
+	 * @param string $view    The view items are being retrieved for
272
+	 * @param bool   $count   Whether to just return a count or not.
273
+	 * @param bool   $all     Disregard any paging info (no limit on data returned).
274
+	 * @return int|EE_Message[]
275
+	 * @throws \EE_Error
276
+	 */
277
+	protected function _get_messages($perpage = 10, $view = 'all', $count = false, $all = false)
278
+	{
279
+
280
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
281
+			? $this->_req_data['paged']
282
+			: 1;
283
+
284
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
285
+			? $this->_req_data['perpage']
286
+			: $perpage;
287
+
288
+		$offset       = ($current_page - 1) * $per_page;
289
+		$limit        = $all || $count ? null : array($offset, $per_page);
290
+		$query_params = array(
291
+			'order_by' => empty($this->_req_data['orderby']) ? 'MSG_modified' : $this->_req_data['orderby'],
292
+			'order'    => empty($this->_req_data['order']) ? 'DESC' : $this->_req_data['order'],
293
+			'limit'    => $limit,
294
+		);
295
+
296
+		/**
297
+		 * Any filters coming in from other routes?
298
+		 */
299
+		if (isset($this->_req_data['filterby'])) {
300
+			$query_params = array_merge($query_params, EEM_Message::instance()->filter_by_query_params());
301
+			if ( ! $count) {
302
+				$query_params['group_by'] = 'MSG_ID';
303
+			}
304
+		}
305
+
306
+		//view conditionals
307
+		if ($view !== 'all' && $count && $all) {
308
+			$query_params[0]['AND*view_conditional'] = array(
309
+				'STS_ID' => strtoupper($view),
310
+			);
311
+		}
312
+
313
+		if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314
+			$query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315
+				? array(
316
+					'STS_ID' => array(
317
+						'IN',
318
+						array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319
+					)
320
+				)
321
+				: array( 'STS_ID' => strtoupper($this->_req_data['status']) );
322
+		}
323
+
324
+		if (! $all && ! empty($this->_req_data['s'])) {
325
+			$search_string         = '%' . $this->_req_data['s'] . '%';
326
+			$query_params[0]['OR'] = array(
327
+				'MSG_to'      => array('LIKE', $search_string),
328
+				'MSG_from'    => array('LIKE', $search_string),
329
+				'MSG_subject' => array('LIKE', $search_string),
330
+				'MSG_content' => array('LIKE', $search_string),
331
+			);
332
+		}
333
+
334
+		//account for debug only status.  We don't show Messages with the EEM_Message::status_debug_only to clients when
335
+		//the messages system is in debug mode.
336
+		//Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337
+		//messages in the database.
338
+		if (! EEM_Message::debug()) {
339
+			$query_params[0]['AND*debug_only_conditional'] = array(
340
+				'STS_ID' => array('!=', EEM_Message::status_debug_only),
341
+			);
342
+		}
343
+
344
+		//account for filters
345
+		if (! $all
346
+			&& isset($this->_req_data['ee_messenger_filter_by'])
347
+			&& $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348
+		) {
349
+			$query_params[0]['AND*messenger_filter'] = array(
350
+				'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351
+			);
352
+		}
353
+		if (! $all
354
+			&& ! empty($this->_req_data['ee_message_type_filter_by'])
355
+			&& $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356
+		) {
357
+			$query_params[0]['AND*message_type_filter'] = array(
358
+				'MSG_message_type' => $this->_req_data['ee_message_type_filter_by'],
359
+			);
360
+		}
361
+
362
+		if (! $all
363
+			&& ! empty($this->_req_data['ee_context_filter_by'])
364
+			&& $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365
+		) {
366
+			$query_params[0]['AND*context_filter'] = array(
367
+				'MSG_context' => array('IN', explode(',', $this->_req_data['ee_context_filter_by'])),
368
+			);
369
+		}
370
+
371
+		return $count
372
+			/** @type int */
373
+			? EEM_Message::instance()->count($query_params, null, true)
374
+			/** @type EE_Message[] */
375
+			: EEM_Message::instance()->get_all($query_params);
376
+	}
377
+
378
+
379
+	/**
380
+	 * Generate dropdown filter select input for messengers.
381
+	 *
382
+	 * @return string
383
+	 */
384
+	protected function _get_messengers_dropdown_filter()
385
+	{
386
+		$messenger_options                    = array();
387
+		$active_messages_grouped_by_messenger = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
388
+
389
+		//setup array of messenger options
390
+		foreach ($active_messages_grouped_by_messenger as $active_message) {
391
+			if ($active_message instanceof EE_Message) {
392
+				$messenger_options[$active_message->messenger()] = ucwords($active_message->messenger_label());
393
+			}
394
+		}
395
+		return $this->get_admin_page()->get_messengers_select_input($messenger_options);
396
+	}
397
+
398
+
399
+	/**
400
+	 * Generate dropdown filter select input for message types
401
+	 *
402
+	 * @return string
403
+	 */
404
+	protected function _get_message_types_dropdown_filter()
405
+	{
406
+		$message_type_options                    = array();
407
+		$active_messages_grouped_by_message_type = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
408
+
409
+		//setup array of message type options
410
+		foreach ($active_messages_grouped_by_message_type as $active_message) {
411
+			if ($active_message instanceof EE_Message) {
412
+				$message_type_options[$active_message->message_type()] = ucwords($active_message->message_type_label());
413
+			}
414
+		}
415
+		return $this->get_admin_page()->get_message_types_select_input($message_type_options);
416
+	}
417
+
418
+
419
+	/**
420
+	 * Generate dropdown filter select input for message type contexts
421
+	 *
422
+	 * @return string
423
+	 */
424
+	protected function _get_contexts_for_message_types_dropdown_filter()
425
+	{
426
+		$context_options                    = array();
427
+		$active_messages_grouped_by_context = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
428
+
429
+		//setup array of context options
430
+		foreach ($active_messages_grouped_by_context as $active_message) {
431
+			if ($active_message instanceof EE_Message) {
432
+				$message_type = $active_message->message_type_object();
433
+				if ($message_type instanceof EE_message_type) {
434
+					foreach ($message_type->get_contexts() as $context => $context_details) {
435
+						if (isset($context_details['label'])) {
436
+							$context_options[$context] = $context_details['label'];
437
+						}
438
+					}
439
+				}
440
+			}
441
+		}
442
+		return $this->get_admin_page()->get_contexts_for_message_types_select_input($context_options);
443
+	}
444 444
 } //end EE_Message_List_Table class
445 445
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('NO direct script access allowed');
4 4
 }
5 5
 
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
     {
82 82
         $class = parent::_get_row_class($item);
83 83
         //add status class
84
-        $class .= ' ee-status-strip msg-status-' . $item->STS_ID();
84
+        $class .= ' ee-status-strip msg-status-'.$item->STS_ID();
85 85
         if ($this->_has_checkbox_column) {
86 86
             $class .= ' has-checkbox-column';
87 87
         }
@@ -168,8 +168,8 @@  discard block
 block discarded – undo
168 168
                 ),
169 169
                 admin_url('admin.php')
170 170
             )
171
-                             . '">' . __('Delete', 'event_espresso') . '</a>';
172
-        return esc_html($message->to()) . $this->row_actions($actions);
171
+                             . '">'.__('Delete', 'event_espresso').'</a>';
172
+        return esc_html($message->to()).$this->row_actions($actions);
173 173
     }
174 174
 
175 175
 
@@ -238,26 +238,26 @@  discard block
 block discarded – undo
238 238
             'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239 239
             'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240 240
         );
241
-        $content      = '';
241
+        $content = '';
242 242
         switch ($message->STS_ID()) {
243 243
             case EEM_Message::status_sent :
244
-                $content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
244
+                $content = $action_links['view'].$action_links['queue_for_resending'].$action_links['view_transaction'];
245 245
                 break;
246 246
             case EEM_Message::status_resend :
247
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
247
+                $content = $action_links['view'].$action_links['send_now'].$action_links['view_transaction'];
248 248
                 break;
249 249
             case EEM_Message::status_retry :
250
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
250
+                $content = $action_links['view'].$action_links['send_now'].$action_links['error'].$action_links['view_transaction'];
251 251
                 break;
252 252
             case EEM_Message::status_failed :
253 253
             case EEM_Message::status_debug_only :
254
-                $content = $action_links['error'] . $action_links['view_transaction'];
254
+                $content = $action_links['error'].$action_links['view_transaction'];
255 255
                 break;
256 256
             case EEM_Message::status_idle :
257
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
257
+                $content = $action_links['view'].$action_links['send_now'].$action_links['view_transaction'];
258 258
                 break;
259 259
             case EEM_Message::status_incomplete;
260
-                $content = $action_links['generate_now'] . $action_links['view_transaction'];
260
+                $content = $action_links['generate_now'].$action_links['view_transaction'];
261 261
                 break;
262 262
         }
263 263
         return $content;
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
             );
311 311
         }
312 312
 
313
-        if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
313
+        if ( ! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314 314
             $query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315 315
                 ? array(
316 316
                     'STS_ID' => array(
@@ -318,11 +318,11 @@  discard block
 block discarded – undo
318 318
                         array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319 319
                     )
320 320
                 )
321
-                : array( 'STS_ID' => strtoupper($this->_req_data['status']) );
321
+                : array('STS_ID' => strtoupper($this->_req_data['status']));
322 322
         }
323 323
 
324
-        if (! $all && ! empty($this->_req_data['s'])) {
325
-            $search_string         = '%' . $this->_req_data['s'] . '%';
324
+        if ( ! $all && ! empty($this->_req_data['s'])) {
325
+            $search_string         = '%'.$this->_req_data['s'].'%';
326 326
             $query_params[0]['OR'] = array(
327 327
                 'MSG_to'      => array('LIKE', $search_string),
328 328
                 'MSG_from'    => array('LIKE', $search_string),
@@ -335,14 +335,14 @@  discard block
 block discarded – undo
335 335
         //the messages system is in debug mode.
336 336
         //Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337 337
         //messages in the database.
338
-        if (! EEM_Message::debug()) {
338
+        if ( ! EEM_Message::debug()) {
339 339
             $query_params[0]['AND*debug_only_conditional'] = array(
340 340
                 'STS_ID' => array('!=', EEM_Message::status_debug_only),
341 341
             );
342 342
         }
343 343
 
344 344
         //account for filters
345
-        if (! $all
345
+        if ( ! $all
346 346
             && isset($this->_req_data['ee_messenger_filter_by'])
347 347
             && $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348 348
         ) {
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
                 'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351 351
             );
352 352
         }
353
-        if (! $all
353
+        if ( ! $all
354 354
             && ! empty($this->_req_data['ee_message_type_filter_by'])
355 355
             && $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356 356
         ) {
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
             );
360 360
         }
361 361
 
362
-        if (! $all
362
+        if ( ! $all
363 363
             && ! empty($this->_req_data['ee_context_filter_by'])
364 364
             && $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365 365
         ) {
Please login to merge, or discard this patch.
admin/extend/registration_form/Extend_Registration_Form_Admin_Page.core.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -504,7 +504,7 @@
 block discarded – undo
504 504
      *
505 505
      * @param int                  $id
506 506
      * @param EEM_Soft_Delete_Base $model
507
-     * @return boolean
507
+     * @return integer
508 508
      */
509 509
     protected function _delete_item($id, $model)
510 510
     {
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('NO direct script access allowed');
4 4
 }
5 5
 
@@ -32,11 +32,11 @@  discard block
 block discarded – undo
32 32
      */
33 33
     public function __construct($routing = true)
34 34
     {
35
-        define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form' . DS);
36
-        define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets' . DS);
37
-        define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
38
-        define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates' . DS);
39
-        define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
35
+        define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND.'registration_form'.DS);
36
+        define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN.'assets'.DS);
37
+        define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'registration_form/assets/');
38
+        define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN.'templates'.DS);
39
+        define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'registration_form/templates/');
40 40
         parent::__construct($routing);
41 41
     }
42 42
 
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
         $qst_id = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
48 48
         $qsg_id = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID']) ? $this->_req_data['QSG_ID'] : 0;
49 49
 
50
-        $new_page_routes    = array(
50
+        $new_page_routes = array(
51 51
             'question_groups'    => array(
52 52
                 'func'       => '_question_groups_overview_list_table',
53 53
                 'capability' => 'ee_read_question_groups',
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 
311 311
 
312 312
         //additional labels
313
-        $new_labels               = array(
313
+        $new_labels = array(
314 314
             'add_question'          => esc_html__('Add New Question', 'event_espresso'),
315 315
             'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
316 316
             'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
      */
355 355
     public function load_sortable_question_script()
356 356
     {
357
-        wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
357
+        wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL.'ee_question_order.js',
358 358
             array('jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
359 359
         wp_enqueue_script('ee-question-sortable');
360 360
     }
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
 
421 421
     protected function _questions_overview_list_table()
422 422
     {
423
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
423
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
424 424
                 'add_question',
425 425
                 'add_question',
426 426
                 array(),
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
     protected function _question_groups_overview_list_table()
434 434
     {
435 435
         $this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
436
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
436
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
437 437
                 'add_question_group',
438 438
                 'add_question_group',
439 439
                 array(),
@@ -477,20 +477,20 @@  discard block
 block discarded – undo
477 477
     {
478 478
         $success = 0;
479 479
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
480
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
480
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
481 481
             // if array has more than one element than success message should be plural
482 482
             $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
483 483
             // cycle thru bulk action checkboxes
484 484
             while (list($ID, $value) = each($this->_req_data['checkbox'])) {
485
-                if (! $this->_delete_item($ID, $model)) {
485
+                if ( ! $this->_delete_item($ID, $model)) {
486 486
                     $success = 0;
487 487
                 }
488 488
             }
489 489
 
490
-        } elseif (! empty($this->_req_data['QSG_ID'])) {
490
+        } elseif ( ! empty($this->_req_data['QSG_ID'])) {
491 491
             $success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
492 492
 
493
-        } elseif (! empty($this->_req_data['QST_ID'])) {
493
+        } elseif ( ! empty($this->_req_data['QST_ID'])) {
494 494
             $success = $this->_delete_item($this->_req_data['QST_ID'], $model);
495 495
         } else {
496 496
             EE_Error::add_error(sprintf(esc_html__("No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
@@ -534,7 +534,7 @@  discard block
 block discarded – undo
534 534
                 $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
535 535
         }
536 536
         // add ID to title if editing
537
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
537
+        $this->_admin_page_title = $ID ? $this->_admin_page_title.' # '.$ID : $this->_admin_page_title;
538 538
         if ($ID) {
539 539
             /** @var EE_Question_Group $questionGroup */
540 540
             $questionGroup            = $this->_question_group_model->get_one_by_ID($ID);
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
 
554 554
         $redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
555 555
         $this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
556
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
556
+        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH.'question_groups_main_meta_box.template.php',
557 557
             $this->_template_args, true);
558 558
 
559 559
         // the details template wrapper
@@ -600,13 +600,13 @@  discard block
 block discarded – undo
600 600
         $question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
601 601
         $questions      = $question_group->questions();
602 602
         // make sure system phone question is added to list of questions for this group
603
-        if (! isset($questions[$phone_question_id])) {
603
+        if ( ! isset($questions[$phone_question_id])) {
604 604
             $questions[$phone_question_id] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
605 605
         }
606 606
 
607 607
         foreach ($questions as $question_ID => $question) {
608 608
             // first we always check for order.
609
-            if (! empty($this->_req_data['question_orders'][$question_ID])) {
609
+            if ( ! empty($this->_req_data['question_orders'][$question_ID])) {
610 610
                 //update question order
611 611
                 $question_group->update_question_order($question_ID, $this->_req_data['question_orders'][$question_ID]);
612 612
             }
@@ -654,7 +654,7 @@  discard block
 block discarded – undo
654 654
      */
655 655
     public function _duplicate_question()
656 656
     {
657
-        $question_ID = (int)$this->_req_data['QST_ID'];
657
+        $question_ID = (int) $this->_req_data['QST_ID'];
658 658
         $question    = EEM_Question::instance()->get_one_by_ID($question_ID);
659 659
         if ($question instanceof EE_Question) {
660 660
             $new_question = $question->duplicate();
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
      */
691 691
     protected function _trash_question()
692 692
     {
693
-        $success    = $this->_question_model->delete_by_ID((int)$this->_req_data['QST_ID']);
693
+        $success    = $this->_question_model->delete_by_ID((int) $this->_req_data['QST_ID']);
694 694
         $query_args = array('action' => 'default', 'status' => 'all');
695 695
         $this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
696 696
     }
@@ -722,12 +722,12 @@  discard block
 block discarded – undo
722 722
         //echo "trash $trash";
723 723
         //var_dump($this->_req_data['checkbox']);die;
724 724
         if (isset($this->_req_data['checkbox'])) {
725
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
725
+            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
726 726
                 // if array has more than one element than success message should be plural
727 727
                 $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
728 728
                 // cycle thru bulk action checkboxes
729 729
                 while (list($ID, $value) = each($this->_req_data['checkbox'])) {
730
-                    if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
730
+                    if ( ! $model->delete_or_restore_by_ID($trash, absint($ID))) {
731 731
                         $success = 0;
732 732
                     }
733 733
                 }
@@ -735,7 +735,7 @@  discard block
 block discarded – undo
735 735
             } else {
736 736
                 // grab single id and delete
737 737
                 $ID = absint($this->_req_data['checkbox']);
738
-                if (! $model->delete_or_restore_by_ID($trash, $ID)) {
738
+                if ( ! $model->delete_or_restore_by_ID($trash, $ID)) {
739 739
                     $success = 0;
740 740
                 }
741 741
             }
@@ -744,14 +744,14 @@  discard block
 block discarded – undo
744 744
             // delete via trash link
745 745
             // grab single id and delete
746 746
             $ID = absint($this->_req_data[$model->primary_key_name()]);
747
-            if (! $model->delete_or_restore_by_ID($trash, $ID)) {
747
+            if ( ! $model->delete_or_restore_by_ID($trash, $ID)) {
748 748
                 $success = 0;
749 749
             }
750 750
 
751 751
         }
752 752
 
753 753
 
754
-        $action = $model instanceof EEM_Question ? 'default' : 'question_groups';//strtolower( $model->item_name(2) );
754
+        $action = $model instanceof EEM_Question ? 'default' : 'question_groups'; //strtolower( $model->item_name(2) );
755 755
         //echo "action :$action";
756 756
         //$action = 'questions' ? 'default' : $action;
757 757
         if ($trash) {
@@ -845,13 +845,13 @@  discard block
 block discarded – undo
845 845
             : array();
846 846
 
847 847
         $perpage = ! empty($this->_req_data['perpage'])
848
-            ? (int)$this->_req_data['perpage']
848
+            ? (int) $this->_req_data['perpage']
849 849
             : null;
850 850
         $curpage = ! empty($this->_req_data['curpage'])
851
-            ? (int)$this->_req_data['curpage']
851
+            ? (int) $this->_req_data['curpage']
852 852
             : null;
853 853
 
854
-        if (! empty($row_ids)) {
854
+        if ( ! empty($row_ids)) {
855 855
             //figure out where we start the row_id count at for the current page.
856 856
             $qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
857 857
 
@@ -898,14 +898,14 @@  discard block
 block discarded – undo
898 898
             array($this, 'email_validation_settings_form'),
899 899
             2
900 900
         );
901
-        $this->_template_args = (array)apply_filters(
901
+        $this->_template_args = (array) apply_filters(
902 902
             'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
903 903
             $this->_template_args
904 904
         );
905 905
         $this->_set_add_edit_form_tags('update_reg_form_settings');
906 906
         $this->_set_publish_post_box_vars(null, false, false, null, false);
907 907
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
908
-            REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
908
+            REGISTRATION_FORM_CAF_TEMPLATE_PATH.'reg_form_settings.template.php',
909 909
             $this->_template_args,
910 910
             true
911 911
         );
@@ -925,7 +925,7 @@  discard block
 block discarded – undo
925 925
             'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
926 926
             EE_Registry::instance()->CFG->registration
927 927
         );
928
-        $success                                   = $this->_update_espresso_configuration(
928
+        $success = $this->_update_espresso_configuration(
929 929
             esc_html__('Registration Form Options', 'event_espresso'),
930 930
             EE_Registry::instance()->CFG,
931 931
             __FILE__, __FUNCTION__, __LINE__
@@ -1022,7 +1022,7 @@  discard block
 block discarded – undo
1022 1022
                                 $prev_email_validation_level = 'basic';
1023 1023
                             }
1024 1024
                             // confirm our i18n email validation will work on the server
1025
-                            if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1025
+                            if ( ! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1026 1026
                                 // or reset email validation level to previous value
1027 1027
                                 $email_validation_level = $prev_email_validation_level;
1028 1028
                             }
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
     private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1065 1065
     {
1066 1066
         // first check that PCRE is enabled
1067
-        if (! defined('PREG_BAD_UTF8_ERROR')) {
1067
+        if ( ! defined('PREG_BAD_UTF8_ERROR')) {
1068 1068
             EE_Error::add_error(
1069 1069
                 sprintf(
1070 1070
                     esc_html__(
Please login to merge, or discard this patch.
Indentation   +1088 added lines, -1088 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 
6 6
 /**
@@ -25,1093 +25,1093 @@  discard block
 block discarded – undo
25 25
 {
26 26
 
27 27
 
28
-    /**
29
-     * @Constructor
30
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
31
-     * @access public
32
-     */
33
-    public function __construct($routing = true)
34
-    {
35
-        define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form' . DS);
36
-        define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets' . DS);
37
-        define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
38
-        define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates' . DS);
39
-        define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
40
-        parent::__construct($routing);
41
-    }
42
-
43
-
44
-    protected function _extend_page_config()
45
-    {
46
-        $this->_admin_base_path = REGISTRATION_FORM_CAF_ADMIN;
47
-        $qst_id = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
48
-        $qsg_id = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID']) ? $this->_req_data['QSG_ID'] : 0;
49
-
50
-        $new_page_routes    = array(
51
-            'question_groups'    => array(
52
-                'func'       => '_question_groups_overview_list_table',
53
-                'capability' => 'ee_read_question_groups',
54
-            ),
55
-            'add_question'       => array(
56
-                'func'       => '_edit_question',
57
-                'capability' => 'ee_edit_questions',
58
-            ),
59
-            'insert_question'    => array(
60
-                'func'       => '_insert_or_update_question',
61
-                'args'       => array('new_question' => true),
62
-                'capability' => 'ee_edit_questions',
63
-                'noheader'   => true,
64
-            ),
65
-            'duplicate_question' => array(
66
-                'func'       => '_duplicate_question',
67
-                'capability' => 'ee_edit_questions',
68
-                'noheader'   => true,
69
-            ),
70
-            'trash_question'     => array(
71
-                'func'       => '_trash_question',
72
-                'capability' => 'ee_delete_question',
73
-                'obj_id'     => $qst_id,
74
-                'noheader'   => true,
75
-            ),
76
-
77
-            'restore_question' => array(
78
-                'func'       => '_trash_or_restore_questions',
79
-                'capability' => 'ee_delete_question',
80
-                'obj_id'     => $qst_id,
81
-                'args'       => array('trash' => false),
82
-                'noheader'   => true,
83
-            ),
84
-
85
-            'delete_question' => array(
86
-                'func'       => '_delete_question',
87
-                'capability' => 'ee_delete_question',
88
-                'obj_id'     => $qst_id,
89
-                'noheader'   => true,
90
-            ),
91
-
92
-            'trash_questions' => array(
93
-                'func'       => '_trash_or_restore_questions',
94
-                'capability' => 'ee_delete_questions',
95
-                'args'       => array('trash' => true),
96
-                'noheader'   => true,
97
-            ),
98
-
99
-            'restore_questions' => array(
100
-                'func'       => '_trash_or_restore_questions',
101
-                'capability' => 'ee_delete_questions',
102
-                'args'       => array('trash' => false),
103
-                'noheader'   => true,
104
-            ),
105
-
106
-            'delete_questions' => array(
107
-                'func'       => '_delete_questions',
108
-                'args'       => array(),
109
-                'capability' => 'ee_delete_questions',
110
-                'noheader'   => true,
111
-            ),
112
-
113
-            'add_question_group' => array(
114
-                'func'       => '_edit_question_group',
115
-                'capability' => 'ee_edit_question_groups',
116
-            ),
117
-
118
-            'edit_question_group' => array(
119
-                'func'       => '_edit_question_group',
120
-                'capability' => 'ee_edit_question_group',
121
-                'obj_id'     => $qsg_id,
122
-                'args'       => array('edit'),
123
-            ),
124
-
125
-            'delete_question_groups' => array(
126
-                'func'       => '_delete_question_groups',
127
-                'capability' => 'ee_delete_question_groups',
128
-                'noheader'   => true,
129
-            ),
130
-
131
-            'delete_question_group' => array(
132
-                'func'       => '_delete_question_groups',
133
-                'capability' => 'ee_delete_question_group',
134
-                'obj_id'     => $qsg_id,
135
-                'noheader'   => true,
136
-            ),
137
-
138
-            'trash_question_group' => array(
139
-                'func'       => '_trash_or_restore_question_groups',
140
-                'args'       => array('trash' => true),
141
-                'capability' => 'ee_delete_question_group',
142
-                'obj_id'     => $qsg_id,
143
-                'noheader'   => true,
144
-            ),
145
-
146
-            'restore_question_group' => array(
147
-                'func'       => '_trash_or_restore_question_groups',
148
-                'args'       => array('trash' => false),
149
-                'capability' => 'ee_delete_question_group',
150
-                'obj_id'     => $qsg_id,
151
-                'noheader'   => true,
152
-            ),
153
-
154
-            'insert_question_group' => array(
155
-                'func'       => '_insert_or_update_question_group',
156
-                'args'       => array('new_question_group' => true),
157
-                'capability' => 'ee_edit_question_groups',
158
-                'noheader'   => true,
159
-            ),
160
-
161
-            'update_question_group' => array(
162
-                'func'       => '_insert_or_update_question_group',
163
-                'args'       => array('new_question_group' => false),
164
-                'capability' => 'ee_edit_question_group',
165
-                'obj_id'     => $qsg_id,
166
-                'noheader'   => true,
167
-            ),
168
-
169
-            'trash_question_groups' => array(
170
-                'func'       => '_trash_or_restore_question_groups',
171
-                'args'       => array('trash' => true),
172
-                'capability' => 'ee_delete_question_groups',
173
-                'noheader'   => array('trash' => false),
174
-            ),
175
-
176
-            'restore_question_groups' => array(
177
-                'func'       => '_trash_or_restore_question_groups',
178
-                'args'       => array('trash' => false),
179
-                'capability' => 'ee_delete_question_groups',
180
-                'noheader'   => true,
181
-            ),
182
-
183
-
184
-            'espresso_update_question_group_order' => array(
185
-                'func'       => 'update_question_group_order',
186
-                'capability' => 'ee_edit_question_groups',
187
-                'noheader'   => true,
188
-            ),
189
-
190
-            'view_reg_form_settings' => array(
191
-                'func'       => '_reg_form_settings',
192
-                'capability' => 'manage_options',
193
-            ),
194
-
195
-            'update_reg_form_settings' => array(
196
-                'func'       => '_update_reg_form_settings',
197
-                'capability' => 'manage_options',
198
-                'noheader'   => true,
199
-            ),
200
-        );
201
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
202
-
203
-        $new_page_config    = array(
204
-
205
-            'question_groups' => array(
206
-                'nav'           => array(
207
-                    'label' => esc_html__('Question Groups', 'event_espresso'),
208
-                    'order' => 20,
209
-                ),
210
-                'list_table'    => 'Registration_Form_Question_Groups_Admin_List_Table',
211
-                'help_tabs'     => array(
212
-                    'registration_form_question_groups_help_tab'                           => array(
213
-                        'title'    => esc_html__('Question Groups', 'event_espresso'),
214
-                        'filename' => 'registration_form_question_groups',
215
-                    ),
216
-                    'registration_form_question_groups_table_column_headings_help_tab'     => array(
217
-                        'title'    => esc_html__('Question Groups Table Column Headings', 'event_espresso'),
218
-                        'filename' => 'registration_form_question_groups_table_column_headings',
219
-                    ),
220
-                    'registration_form_question_groups_views_bulk_actions_search_help_tab' => array(
221
-                        'title'    => esc_html__('Question Groups Views & Bulk Actions & Search', 'event_espresso'),
222
-                        'filename' => 'registration_form_question_groups_views_bulk_actions_search',
223
-                    ),
224
-                ),
225
-                'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
226
-                'metaboxes'     => $this->_default_espresso_metaboxes,
227
-                'require_nonce' => false,
228
-                'qtips'         => array(
229
-                    'EE_Registration_Form_Tips',
230
-                ),
231
-            ),
232
-
233
-            'add_question' => array(
234
-                'nav'           => array(
235
-                    'label'      => esc_html__('Add Question', 'event_espresso'),
236
-                    'order'      => 5,
237
-                    'persistent' => false,
238
-                ),
239
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
240
-                'help_tabs'     => array(
241
-                    'registration_form_add_question_help_tab' => array(
242
-                        'title'    => esc_html__('Add Question', 'event_espresso'),
243
-                        'filename' => 'registration_form_add_question',
244
-                    ),
245
-                ),
246
-                'help_tour'     => array('Registration_Form_Add_Question_Help_Tour'),
247
-                'require_nonce' => false,
248
-            ),
249
-
250
-            'add_question_group' => array(
251
-                'nav'           => array(
252
-                    'label'      => esc_html__('Add Question Group', 'event_espresso'),
253
-                    'order'      => 5,
254
-                    'persistent' => false,
255
-                ),
256
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
257
-                'help_tabs'     => array(
258
-                    'registration_form_add_question_group_help_tab' => array(
259
-                        'title'    => esc_html__('Add Question Group', 'event_espresso'),
260
-                        'filename' => 'registration_form_add_question_group',
261
-                    ),
262
-                ),
263
-                'help_tour'     => array('Registration_Form_Add_Question_Group_Help_Tour'),
264
-                'require_nonce' => false,
265
-            ),
266
-
267
-            'edit_question_group' => array(
268
-                'nav'           => array(
269
-                    'label'      => esc_html__('Edit Question Group', 'event_espresso'),
270
-                    'order'      => 5,
271
-                    'persistent' => false,
272
-                    'url'        => isset($this->_req_data['question_group_id']) ? add_query_arg(array('question_group_id' => $this->_req_data['question_group_id']),
273
-                        $this->_current_page_view_url) : $this->_admin_base_url,
274
-                ),
275
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
276
-                'help_tabs'     => array(
277
-                    'registration_form_edit_question_group_help_tab' => array(
278
-                        'title'    => esc_html__('Edit Question Group', 'event_espresso'),
279
-                        'filename' => 'registration_form_edit_question_group',
280
-                    ),
281
-                ),
282
-                'help_tour'     => array('Registration_Form_Edit_Question_Group_Help_Tour'),
283
-                'require_nonce' => false,
284
-            ),
285
-
286
-            'view_reg_form_settings' => array(
287
-                'nav'           => array(
288
-                    'label' => esc_html__('Reg Form Settings', 'event_espresso'),
289
-                    'order' => 40,
290
-                ),
291
-                'labels'        => array(
292
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
293
-                ),
294
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
295
-                'help_tabs'     => array(
296
-                    'registration_form_reg_form_settings_help_tab' => array(
297
-                        'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
298
-                        'filename' => 'registration_form_reg_form_settings',
299
-                    ),
300
-                ),
301
-                'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
302
-                'require_nonce' => false,
303
-            ),
304
-
305
-        );
306
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
307
-
308
-        //change the list table we're going to use so it's the NEW list table!
309
-        $this->_page_config['default']['list_table'] = 'Extend_Registration_Form_Questions_Admin_List_Table';
310
-
311
-
312
-        //additional labels
313
-        $new_labels               = array(
314
-            'add_question'          => esc_html__('Add New Question', 'event_espresso'),
315
-            'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
316
-            'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
317
-            'edit_question_group'   => esc_html__('Edit Question Group', 'event_espresso'),
318
-            'delete_question_group' => esc_html__('Delete Question Group', 'event_espresso'),
319
-        );
320
-        $this->_labels['buttons'] = array_merge($this->_labels['buttons'], $new_labels);
321
-
322
-    }
323
-
324
-
325
-    protected function _ajax_hooks()
326
-    {
327
-        add_action('wp_ajax_espresso_update_question_group_order', array($this, 'update_question_group_order'));
328
-    }
329
-
330
-
331
-    public function load_scripts_styles_question_groups()
332
-    {
333
-        wp_enqueue_script('espresso_ajax_table_sorting');
334
-    }
335
-
336
-
337
-    public function load_scripts_styles_add_question_group()
338
-    {
339
-        $this->load_scripts_styles_forms();
340
-        $this->load_sortable_question_script();
341
-    }
342
-
343
-    public function load_scripts_styles_edit_question_group()
344
-    {
345
-        $this->load_scripts_styles_forms();
346
-        $this->load_sortable_question_script();
347
-    }
348
-
349
-
350
-    /**
351
-     * registers and enqueues script for questions
352
-     *
353
-     * @return void
354
-     */
355
-    public function load_sortable_question_script()
356
-    {
357
-        wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
358
-            array('jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
359
-        wp_enqueue_script('ee-question-sortable');
360
-    }
361
-
362
-
363
-    protected function _set_list_table_views_default()
364
-    {
365
-        $this->_views = array(
366
-            'all' => array(
367
-                'slug'        => 'all',
368
-                'label'       => esc_html__('View All Questions', 'event_espresso'),
369
-                'count'       => 0,
370
-                'bulk_action' => array(
371
-                    'trash_questions' => esc_html__('Trash', 'event_espresso'),
372
-                ),
373
-            ),
374
-        );
375
-
376
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_questions',
377
-            'espresso_registration_form_trash_questions')
378
-        ) {
379
-            $this->_views['trash'] = array(
380
-                'slug'        => 'trash',
381
-                'label'       => esc_html__('Trash', 'event_espresso'),
382
-                'count'       => 0,
383
-                'bulk_action' => array(
384
-                    'delete_questions'  => esc_html__('Delete Permanently', 'event_espresso'),
385
-                    'restore_questions' => esc_html__('Restore', 'event_espresso'),
386
-                ),
387
-            );
388
-        }
389
-    }
390
-
391
-
392
-    protected function _set_list_table_views_question_groups()
393
-    {
394
-        $this->_views = array(
395
-            'all' => array(
396
-                'slug'        => 'all',
397
-                'label'       => esc_html__('All', 'event_espresso'),
398
-                'count'       => 0,
399
-                'bulk_action' => array(
400
-                    'trash_question_groups' => esc_html__('Trash', 'event_espresso'),
401
-                ),
402
-            ),
403
-        );
404
-
405
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_question_groups',
406
-            'espresso_registration_form_trash_question_groups')
407
-        ) {
408
-            $this->_views['trash'] = array(
409
-                'slug'        => 'trash',
410
-                'label'       => esc_html__('Trash', 'event_espresso'),
411
-                'count'       => 0,
412
-                'bulk_action' => array(
413
-                    'delete_question_groups'  => esc_html__('Delete Permanently', 'event_espresso'),
414
-                    'restore_question_groups' => esc_html__('Restore', 'event_espresso'),
415
-                ),
416
-            );
417
-        }
418
-    }
419
-
420
-
421
-    protected function _questions_overview_list_table()
422
-    {
423
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
424
-                'add_question',
425
-                'add_question',
426
-                array(),
427
-                'add-new-h2'
428
-            );
429
-        parent::_questions_overview_list_table();
430
-    }
431
-
432
-
433
-    protected function _question_groups_overview_list_table()
434
-    {
435
-        $this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
436
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
437
-                'add_question_group',
438
-                'add_question_group',
439
-                array(),
440
-                'add-new-h2'
441
-            );
442
-        $this->display_admin_list_table_page_with_sidebar();
443
-    }
444
-
445
-
446
-    protected function _delete_question()
447
-    {
448
-        $success = $this->_delete_items($this->_question_model);
449
-        $this->_redirect_after_action(
450
-            $success,
451
-            $this->_question_model->item_name($success),
452
-            'deleted',
453
-            array('action' => 'default', 'status' => 'all')
454
-        );
455
-    }
456
-
457
-
458
-    protected function _delete_questions()
459
-    {
460
-        $success = $this->_delete_items($this->_question_model);
461
-        $this->_redirect_after_action(
462
-            $success,
463
-            $this->_question_model->item_name($success),
464
-            'deleted permanently',
465
-            array('action' => 'default', 'status' => 'trash')
466
-        );
467
-    }
468
-
469
-
470
-    /**
471
-     * Performs the deletion of a single or multiple questions or question groups.
472
-     *
473
-     * @param EEM_Soft_Delete_Base $model
474
-     * @return int number of items deleted permanently
475
-     */
476
-    private function _delete_items(EEM_Soft_Delete_Base $model)
477
-    {
478
-        $success = 0;
479
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
480
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
481
-            // if array has more than one element than success message should be plural
482
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
483
-            // cycle thru bulk action checkboxes
484
-            while (list($ID, $value) = each($this->_req_data['checkbox'])) {
485
-                if (! $this->_delete_item($ID, $model)) {
486
-                    $success = 0;
487
-                }
488
-            }
489
-
490
-        } elseif (! empty($this->_req_data['QSG_ID'])) {
491
-            $success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
492
-
493
-        } elseif (! empty($this->_req_data['QST_ID'])) {
494
-            $success = $this->_delete_item($this->_req_data['QST_ID'], $model);
495
-        } else {
496
-            EE_Error::add_error(sprintf(esc_html__("No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
497
-                "event_espresso")), __FILE__, __FUNCTION__, __LINE__);
498
-        }
499
-        return $success;
500
-    }
501
-
502
-    /**
503
-     * Deletes the specified question (and its associated question options) or question group
504
-     *
505
-     * @param int                  $id
506
-     * @param EEM_Soft_Delete_Base $model
507
-     * @return boolean
508
-     */
509
-    protected function _delete_item($id, $model)
510
-    {
511
-        if ($model instanceof EEM_Question) {
512
-            EEM_Question_Option::instance()->delete_permanently(array(array('QST_ID' => absint($id))));
513
-        }
514
-        return $model->delete_permanently_by_ID(absint($id));
515
-    }
516
-
517
-
518
-    /******************************    QUESTION GROUPS    ******************************/
519
-
520
-
521
-    protected function _edit_question_group($type = 'add')
522
-    {
523
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
-        $ID = isset($this->_req_data['QSG_ID']) && ! empty($this->_req_data['QSG_ID']) ? absint($this->_req_data['QSG_ID']) : false;
525
-
526
-        switch ($this->_req_action) {
527
-            case 'add_question_group' :
528
-                $this->_admin_page_title = esc_html__('Add Question Group', 'event_espresso');
529
-                break;
530
-            case 'edit_question_group' :
531
-                $this->_admin_page_title = esc_html__('Edit Question Group', 'event_espresso');
532
-                break;
533
-            default :
534
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
535
-        }
536
-        // add ID to title if editing
537
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
538
-        if ($ID) {
539
-            /** @var EE_Question_Group $questionGroup */
540
-            $questionGroup            = $this->_question_group_model->get_one_by_ID($ID);
541
-            $additional_hidden_fields = array('QSG_ID' => array('type' => 'hidden', 'value' => $ID));
542
-            $this->_set_add_edit_form_tags('update_question_group', $additional_hidden_fields);
543
-        } else {
544
-            /** @var EE_Question_Group $questionGroup */
545
-            $questionGroup = EEM_Question_Group::instance()->create_default_object();
546
-            $questionGroup->set_order_to_latest();
547
-            $this->_set_add_edit_form_tags('insert_question_group');
548
-        }
549
-        $this->_template_args['values']         = $this->_yes_no_values;
550
-        $this->_template_args['all_questions']  = $questionGroup->questions_in_and_not_in_group();
551
-        $this->_template_args['QSG_ID']         = $ID ? $ID : true;
552
-        $this->_template_args['question_group'] = $questionGroup;
553
-
554
-        $redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
555
-        $this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
556
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
557
-            $this->_template_args, true);
558
-
559
-        // the details template wrapper
560
-        $this->display_admin_page_with_sidebar();
561
-    }
562
-
563
-
564
-    protected function _delete_question_groups()
565
-    {
566
-        $success = $this->_delete_items($this->_question_group_model);
567
-        $this->_redirect_after_action($success, $this->_question_group_model->item_name($success),
568
-            'deleted permanently', array('action' => 'question_groups', 'status' => 'trash'));
569
-    }
570
-
571
-
572
-    /**
573
-     * @param bool $new_question_group
574
-     */
575
-    protected function _insert_or_update_question_group($new_question_group = true)
576
-    {
577
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
-        $set_column_values = $this->_set_column_values_for($this->_question_group_model);
579
-        if ($new_question_group) {
580
-            $QSG_ID  = $this->_question_group_model->insert($set_column_values);
581
-            $success = $QSG_ID ? 1 : 0;
582
-        } else {
583
-            $QSG_ID = absint($this->_req_data['QSG_ID']);
584
-            unset($set_column_values['QSG_ID']);
585
-            $success = $this->_question_group_model->update($set_column_values, array(array('QSG_ID' => $QSG_ID)));
586
-        }
587
-        $phone_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(EEM_Attendee::system_question_phone);
588
-        // update the existing related questions
589
-        // BUT FIRST...  delete the phone question from the Question_Group_Question if it is being added to this question group (therefore removed from the existing group)
590
-        if (isset($this->_req_data['questions'], $this->_req_data['questions'][$phone_question_id])) {
591
-            // delete where QST ID = system phone question ID and Question Group ID is NOT this group
592
-            EEM_Question_Group_Question::instance()->delete(array(
593
-                array(
594
-                    'QST_ID' => $phone_question_id,
595
-                    'QSG_ID' => array('!=', $QSG_ID),
596
-                ),
597
-            ));
598
-        }
599
-        /** @type EE_Question_Group $question_group */
600
-        $question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
601
-        $questions      = $question_group->questions();
602
-        // make sure system phone question is added to list of questions for this group
603
-        if (! isset($questions[$phone_question_id])) {
604
-            $questions[$phone_question_id] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
605
-        }
606
-
607
-        foreach ($questions as $question_ID => $question) {
608
-            // first we always check for order.
609
-            if (! empty($this->_req_data['question_orders'][$question_ID])) {
610
-                //update question order
611
-                $question_group->update_question_order($question_ID, $this->_req_data['question_orders'][$question_ID]);
612
-            }
613
-
614
-            // then we always check if adding or removing.
615
-            if (isset($this->_req_data['questions'], $this->_req_data['questions'][$question_ID])) {
616
-                $question_group->add_question($question_ID);
617
-            } else {
618
-                // not found, remove it (but only if not a system question for the personal group with the exception of lname system question - we allow removal of it)
619
-                if (
620
-                in_array(
621
-                    $question->system_ID(),
622
-                    EEM_Question::instance()->required_system_questions_in_system_question_group($question_group->system_group())
623
-                )
624
-                ) {
625
-                    continue;
626
-                } else {
627
-                    $question_group->remove_question($question_ID);
628
-                }
629
-            }
630
-        }
631
-        // save new related questions
632
-        if (isset($this->_req_data['questions'])) {
633
-            foreach ($this->_req_data['questions'] as $QST_ID) {
634
-                $question_group->add_question($QST_ID);
635
-                if (isset($this->_req_data['question_orders'][$QST_ID])) {
636
-                    $question_group->update_question_order($QST_ID, $this->_req_data['question_orders'][$QST_ID]);
637
-                }
638
-            }
639
-        }
640
-
641
-        if ($success !== false) {
642
-            $msg = $new_question_group ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
643
-                $this->_question_group_model->item_name()) : sprintf(esc_html__('The %s has been updated',
644
-                'event_espresso'), $this->_question_group_model->item_name());
645
-            EE_Error::add_success($msg);
646
-        }
647
-        $this->_redirect_after_action(false, '', '', array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
648
-            true);
649
-
650
-    }
651
-
652
-    /**
653
-     * duplicates a question and all its question options and redirects to the new question.
654
-     */
655
-    public function _duplicate_question()
656
-    {
657
-        $question_ID = (int)$this->_req_data['QST_ID'];
658
-        $question    = EEM_Question::instance()->get_one_by_ID($question_ID);
659
-        if ($question instanceof EE_Question) {
660
-            $new_question = $question->duplicate();
661
-            if ($new_question instanceof EE_Question) {
662
-                $this->_redirect_after_action(true, esc_html__('Question', 'event_espresso'),
663
-                    esc_html__('Duplicated', 'event_espresso'),
664
-                    array('action' => 'edit_question', 'QST_ID' => $new_question->ID()), true);
665
-            } else {
666
-                global $wpdb;
667
-                EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %1$d because: %2$s',
668
-                    'event_espresso'), $question_ID, $wpdb->last_error), __FILE__, __FUNCTION__, __LINE__);
669
-                $this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
670
-            }
671
-        } else {
672
-            EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %d because it didn\'t exist!',
673
-                'event_espresso'), $question_ID), __FILE__, __FUNCTION__, __LINE__);
674
-            $this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
675
-        }
676
-    }
677
-
678
-
679
-    /**
680
-     * @param bool $trash
681
-     */
682
-    protected function _trash_or_restore_question_groups($trash = true)
683
-    {
684
-        $this->_trash_or_restore_items($this->_question_group_model, $trash);
685
-    }
686
-
687
-
688
-    /**
689
-     *_trash_question
690
-     */
691
-    protected function _trash_question()
692
-    {
693
-        $success    = $this->_question_model->delete_by_ID((int)$this->_req_data['QST_ID']);
694
-        $query_args = array('action' => 'default', 'status' => 'all');
695
-        $this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
696
-    }
697
-
698
-
699
-    /**
700
-     * @param bool $trash
701
-     */
702
-    protected function _trash_or_restore_questions($trash = true)
703
-    {
704
-        $this->_trash_or_restore_items($this->_question_model, $trash);
705
-    }
706
-
707
-
708
-    /**
709
-     * Internally used to delete or restore items, using the request data. Meant to be
710
-     * flexible between question or question groups
711
-     *
712
-     * @param EEM_Soft_Delete_Base $model
713
-     * @param boolean              $trash whether to trash or restore
714
-     */
715
-    private function _trash_or_restore_items(EEM_Soft_Delete_Base $model, $trash = true)
716
-    {
717
-
718
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
719
-
720
-        $success = 1;
721
-        //Checkboxes
722
-        //echo "trash $trash";
723
-        //var_dump($this->_req_data['checkbox']);die;
724
-        if (isset($this->_req_data['checkbox'])) {
725
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
726
-                // if array has more than one element than success message should be plural
727
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
728
-                // cycle thru bulk action checkboxes
729
-                while (list($ID, $value) = each($this->_req_data['checkbox'])) {
730
-                    if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
731
-                        $success = 0;
732
-                    }
733
-                }
734
-
735
-            } else {
736
-                // grab single id and delete
737
-                $ID = absint($this->_req_data['checkbox']);
738
-                if (! $model->delete_or_restore_by_ID($trash, $ID)) {
739
-                    $success = 0;
740
-                }
741
-            }
742
-
743
-        } else {
744
-            // delete via trash link
745
-            // grab single id and delete
746
-            $ID = absint($this->_req_data[$model->primary_key_name()]);
747
-            if (! $model->delete_or_restore_by_ID($trash, $ID)) {
748
-                $success = 0;
749
-            }
750
-
751
-        }
752
-
753
-
754
-        $action = $model instanceof EEM_Question ? 'default' : 'question_groups';//strtolower( $model->item_name(2) );
755
-        //echo "action :$action";
756
-        //$action = 'questions' ? 'default' : $action;
757
-        if ($trash) {
758
-            $action_desc = 'trashed';
759
-            $status      = 'trash';
760
-        } else {
761
-            $action_desc = 'restored';
762
-            $status      = 'all';
763
-        }
764
-        $this->_redirect_after_action($success, $model->item_name($success), $action_desc,
765
-            array('action' => $action, 'status' => $status));
766
-    }
767
-
768
-
769
-    /**
770
-     * @param            $per_page
771
-     * @param int        $current_page
772
-     * @param bool|false $count
773
-     * @return \EE_Soft_Delete_Base_Class[]|int
774
-     */
775
-    public function get_trashed_questions($per_page, $current_page = 1, $count = false)
776
-    {
777
-        $query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
778
-
779
-        if ($count) {
780
-            //note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
781
-            $where   = isset($query_params[0]) ? array($query_params[0]) : array();
782
-            $results = $this->_question_model->count_deleted($where);
783
-        } else {
784
-            //note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
785
-            $results = $this->_question_model->get_all_deleted($query_params);
786
-        }
787
-        return $results;
788
-    }
789
-
790
-
791
-    /**
792
-     * @param            $per_page
793
-     * @param int        $current_page
794
-     * @param bool|false $count
795
-     * @return \EE_Soft_Delete_Base_Class[]
796
-     */
797
-    public function get_question_groups($per_page, $current_page = 1, $count = false)
798
-    {
799
-        $questionGroupModel = EEM_Question_Group::instance();
800
-        $query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
801
-        if ($count) {
802
-            $where   = isset($query_params[0]) ? array($query_params[0]) : array();
803
-            $results = $questionGroupModel->count($where);
804
-        } else {
805
-            $results = $questionGroupModel->get_all($query_params);
806
-        }
807
-        return $results;
808
-    }
809
-
810
-
811
-    /**
812
-     * @param      $per_page
813
-     * @param int  $current_page
814
-     * @param bool $count
815
-     * @return \EE_Soft_Delete_Base_Class[]|int
816
-     */
817
-    public function get_trashed_question_groups($per_page, $current_page = 1, $count = false)
818
-    {
819
-        $questionGroupModel = EEM_Question_Group::instance();
820
-        $query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
821
-        if ($count) {
822
-            $where                 = isset($query_params[0]) ? array($query_params[0]) : array();
823
-            $query_params['limit'] = null;
824
-            $results               = $questionGroupModel->count_deleted($where);
825
-        } else {
826
-            $results = $questionGroupModel->get_all_deleted($query_params);
827
-        }
828
-        return $results;
829
-    }
830
-
831
-
832
-    /**
833
-     * method for performing updates to question order
834
-     *
835
-     * @return array results array
836
-     */
837
-    public function update_question_group_order()
838
-    {
839
-
840
-        $success = esc_html__('Question group order was updated successfully.', 'event_espresso');
841
-
842
-        // grab our row IDs
843
-        $row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids'])
844
-            ? explode(',', rtrim($this->_req_data['row_ids'], ','))
845
-            : array();
846
-
847
-        $perpage = ! empty($this->_req_data['perpage'])
848
-            ? (int)$this->_req_data['perpage']
849
-            : null;
850
-        $curpage = ! empty($this->_req_data['curpage'])
851
-            ? (int)$this->_req_data['curpage']
852
-            : null;
853
-
854
-        if (! empty($row_ids)) {
855
-            //figure out where we start the row_id count at for the current page.
856
-            $qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
857
-
858
-            $row_count = count($row_ids);
859
-            for ($i = 0; $i < $row_count; $i++) {
860
-                //Update the questions when re-ordering
861
-                $updated = EEM_Question_Group::instance()->update(
862
-                    array('QSG_order' => $qsgcount),
863
-                    array(array('QSG_ID' => $row_ids[$i]))
864
-                );
865
-                if ($updated === false) {
866
-                    $success = false;
867
-                }
868
-                $qsgcount++;
869
-            }
870
-        } else {
871
-            $success = false;
872
-        }
873
-
874
-        $errors = ! $success
875
-            ? esc_html__('An error occurred. The question group order was not updated.', 'event_espresso')
876
-            : false;
877
-
878
-        echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
879
-        die();
880
-
881
-    }
882
-
883
-
884
-
885
-    /***************************************        REGISTRATION SETTINGS        ***************************************/
886
-
887
-
888
-    /**
889
-     * _reg_form_settings
890
-     *
891
-     * @throws \EE_Error
892
-     */
893
-    protected function _reg_form_settings()
894
-    {
895
-        $this->_template_args['values'] = $this->_yes_no_values;
896
-        add_action(
897
-            'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
898
-            array($this, 'email_validation_settings_form'),
899
-            2
900
-        );
901
-        $this->_template_args = (array)apply_filters(
902
-            'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
903
-            $this->_template_args
904
-        );
905
-        $this->_set_add_edit_form_tags('update_reg_form_settings');
906
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
907
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
908
-            REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
909
-            $this->_template_args,
910
-            true
911
-        );
912
-        $this->display_admin_page_with_sidebar();
913
-    }
914
-
915
-
916
-    /**
917
-     * _update_reg_form_settings
918
-     */
919
-    protected function _update_reg_form_settings()
920
-    {
921
-        EE_Registry::instance()->CFG->registration = $this->update_email_validation_settings_form(
922
-            EE_Registry::instance()->CFG->registration
923
-        );
924
-        EE_Registry::instance()->CFG->registration = apply_filters(
925
-            'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
926
-            EE_Registry::instance()->CFG->registration
927
-        );
928
-        $success                                   = $this->_update_espresso_configuration(
929
-            esc_html__('Registration Form Options', 'event_espresso'),
930
-            EE_Registry::instance()->CFG,
931
-            __FILE__, __FUNCTION__, __LINE__
932
-        );
933
-        $this->_redirect_after_action($success, esc_html__('Registration Form Options', 'event_espresso'), 'updated',
934
-            array('action' => 'view_reg_form_settings'));
935
-    }
936
-
937
-
938
-    /**
939
-     * email_validation_settings_form
940
-     *
941
-     * @access    public
942
-     * @return    void
943
-     * @throws \EE_Error
944
-     */
945
-    public function email_validation_settings_form()
946
-    {
947
-        echo $this->_email_validation_settings_form()->get_html();
948
-    }
949
-
950
-
951
-    /**
952
-     * _email_validation_settings_form
953
-     *
954
-     * @access protected
955
-     * @return EE_Form_Section_Proper
956
-     * @throws \EE_Error
957
-     */
958
-    protected function _email_validation_settings_form()
959
-    {
960
-        return new EE_Form_Section_Proper(
961
-            array(
962
-                'name'            => 'email_validation_settings',
963
-                'html_id'         => 'email_validation_settings',
964
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
965
-                'subsections'     => apply_filters(
966
-                    'FHEE__Extend_Registration_Form_Admin_Page___email_validation_settings_form__form_subsections',
967
-                    array(
968
-                        'email_validation_hdr'   => new EE_Form_Section_HTML(
969
-                            EEH_HTML::h2(esc_html__('Email Validation Settings', 'event_espresso'))
970
-                        ),
971
-                        'email_validation_level' => new EE_Select_Input(
972
-                            array(
973
-                                'basic'      => esc_html__('Basic', 'event_espresso'),
974
-                                'wp_default' => esc_html__('WordPress Default', 'event_espresso'),
975
-                                'i18n'       => esc_html__('International', 'event_espresso'),
976
-                                'i18n_dns'   => esc_html__('International + DNS Check', 'event_espresso'),
977
-                            ),
978
-                            array(
979
-                                'html_label_text' => esc_html__('Email Validation Level', 'event_espresso')
980
-                                                     . EEH_Template::get_help_tab_link('email_validation_info'),
981
-                                'html_help_text'  => esc_html__('These levels range from basic validation ( ie: [email protected] ) to more advanced checks against international email addresses (ie: üñîçøðé@example.com ) with additional MX and A record checks to confirm the domain actually exists. More information on on each level can be found within the help section.',
982
-                                    'event_espresso'),
983
-                                'default'         => isset(EE_Registry::instance()->CFG->registration->email_validation_level)
984
-                                    ? EE_Registry::instance()->CFG->registration->email_validation_level
985
-                                    : 'wp_default',
986
-                                'required'        => false,
987
-                            )
988
-                        ),
989
-                    )
990
-                ),
991
-            )
992
-        );
993
-    }
994
-
995
-
996
-    /**
997
-     * update_email_validation_settings_form
998
-     *
999
-     * @access    public
1000
-     * @param \EE_Registration_Config $EE_Registration_Config
1001
-     * @return \EE_Registration_Config
1002
-     */
1003
-    public function update_email_validation_settings_form(EE_Registration_Config $EE_Registration_Config)
1004
-    {
1005
-        $prev_email_validation_level = $EE_Registration_Config->email_validation_level;
1006
-        try {
1007
-            $email_validation_settings_form = $this->_email_validation_settings_form();
1008
-            // if not displaying a form, then check for form submission
1009
-            if ($email_validation_settings_form->was_submitted()) {
1010
-                // capture form data
1011
-                $email_validation_settings_form->receive_form_submission();
1012
-                // validate form data
1013
-                if ($email_validation_settings_form->is_valid()) {
1014
-                    // grab validated data from form
1015
-                    $valid_data = $email_validation_settings_form->valid_data();
1016
-                    if (isset($valid_data['email_validation_level'])) {
1017
-                        $email_validation_level = $valid_data['email_validation_level'];
1018
-                        // now if they want to use international email addresses
1019
-                        if ($email_validation_level === 'i18n' || $email_validation_level === 'i18n_dns') {
1020
-                            // in case we need to reset their email validation level,
1021
-                            // make sure that the previous value wasn't already set to one of the i18n options.
1022
-                            if ($prev_email_validation_level === 'i18n' || $prev_email_validation_level === 'i18n_dns') {
1023
-                                // if so, then reset it back to "basic" since that is the only other option that,
1024
-                                // despite offering poor validation, supports i18n email addresses
1025
-                                $prev_email_validation_level = 'basic';
1026
-                            }
1027
-                            // confirm our i18n email validation will work on the server
1028
-                            if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1029
-                                // or reset email validation level to previous value
1030
-                                $email_validation_level = $prev_email_validation_level;
1031
-                            }
1032
-                        }
1033
-                        $EE_Registration_Config->email_validation_level = $email_validation_level;
1034
-                    } else {
1035
-                        EE_Error::add_error(
1036
-                            esc_html__(
1037
-                                'Invalid or missing Email Validation settings. Please refresh the form and try again.',
1038
-                                'event_espresso'
1039
-                            ),
1040
-                            __FILE__, __FUNCTION__, __LINE__
1041
-                        );
1042
-                    }
1043
-                } else {
1044
-                    if ($email_validation_settings_form->submission_error_message() !== '') {
1045
-                        EE_Error::add_error(
1046
-                            $email_validation_settings_form->submission_error_message(),
1047
-                            __FILE__, __FUNCTION__, __LINE__
1048
-                        );
1049
-                    }
1050
-                }
1051
-            }
1052
-        } catch (EE_Error $e) {
1053
-            $e->get_error();
1054
-        }
1055
-        return $EE_Registration_Config;
1056
-    }
1057
-
1058
-
1059
-    /**
1060
-     * confirms that the server's PHP version has the PCRE module enabled,
1061
-     * and that the PCRE version works with our i18n email validation
1062
-     *
1063
-     * @param \EE_Registration_Config $EE_Registration_Config
1064
-     * @param string                  $email_validation_level
1065
-     * @return bool
1066
-     */
1067
-    private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1068
-    {
1069
-        // first check that PCRE is enabled
1070
-        if (! defined('PREG_BAD_UTF8_ERROR')) {
1071
-            EE_Error::add_error(
1072
-                sprintf(
1073
-                    esc_html__(
1074
-                        'We\'re sorry, but it appears that your server\'s version of PHP was not compiled with PCRE unicode support.%1$sPlease contact your hosting company and ask them whether the PCRE compiled with your version of PHP on your server can be been built with the "--enable-unicode-properties" and "--enable-utf8" configuration switches to enable more complex regex expressions.%1$sIf they are unable, or unwilling to do so, then your server will not support international email addresses using UTF-8 unicode characters. This means you will either have to lower your email validation level to "Basic" or "WordPress Default", or switch to a hosting company that has/can enable PCRE unicode support on the server.',
1075
-                        'event_espresso'
1076
-                    ),
1077
-                    '<br />'
1078
-                ),
1079
-                __FILE__,
1080
-                __FUNCTION__,
1081
-                __LINE__
1082
-            );
1083
-            return false;
1084
-        } else {
1085
-            // PCRE support is enabled, but let's still
1086
-            // perform a test to see if the server will support it.
1087
-            // but first, save the updated validation level to the config,
1088
-            // so that the validation strategy picks it up.
1089
-            // this will get bumped back down if it doesn't work
1090
-            $EE_Registration_Config->email_validation_level = $email_validation_level;
1091
-            try {
1092
-                $email_validator    = new EE_Email_Validation_Strategy();
1093
-                $i18n_email_address = apply_filters(
1094
-                    'FHEE__Extend_Registration_Form_Admin_Page__update_email_validation_settings_form__i18n_email_address',
1095
-                    'jägerjü[email protected]'
1096
-                );
1097
-                $email_validator->validate($i18n_email_address);
1098
-            } catch (Exception $e) {
1099
-                EE_Error::add_error(
1100
-                    sprintf(
1101
-                        esc_html__(
1102
-                            'We\'re sorry, but it appears that your server\'s configuration will not support the "International" or "International + DNS Check" email validation levels.%1$sTo correct this issue, please consult with your hosting company regarding your server\'s PCRE settings.%1$sIt is recommended that your PHP version be configured to use PCRE 8.10 or newer.%1$sMore information regarding PCRE versions and installation can be found here: %2$s',
1103
-                            'event_espresso'
1104
-                        ),
1105
-                        '<br />',
1106
-                        '<a href="http://php.net/manual/en/pcre.installation.php" target="_blank">http://php.net/manual/en/pcre.installation.php</a>'
1107
-                    ),
1108
-                    __FILE__, __FUNCTION__, __LINE__
1109
-                );
1110
-                return false;
1111
-            }
1112
-        }
1113
-        return true;
1114
-    }
28
+	/**
29
+	 * @Constructor
30
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
31
+	 * @access public
32
+	 */
33
+	public function __construct($routing = true)
34
+	{
35
+		define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form' . DS);
36
+		define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets' . DS);
37
+		define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
38
+		define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates' . DS);
39
+		define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
40
+		parent::__construct($routing);
41
+	}
42
+
43
+
44
+	protected function _extend_page_config()
45
+	{
46
+		$this->_admin_base_path = REGISTRATION_FORM_CAF_ADMIN;
47
+		$qst_id = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
48
+		$qsg_id = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID']) ? $this->_req_data['QSG_ID'] : 0;
49
+
50
+		$new_page_routes    = array(
51
+			'question_groups'    => array(
52
+				'func'       => '_question_groups_overview_list_table',
53
+				'capability' => 'ee_read_question_groups',
54
+			),
55
+			'add_question'       => array(
56
+				'func'       => '_edit_question',
57
+				'capability' => 'ee_edit_questions',
58
+			),
59
+			'insert_question'    => array(
60
+				'func'       => '_insert_or_update_question',
61
+				'args'       => array('new_question' => true),
62
+				'capability' => 'ee_edit_questions',
63
+				'noheader'   => true,
64
+			),
65
+			'duplicate_question' => array(
66
+				'func'       => '_duplicate_question',
67
+				'capability' => 'ee_edit_questions',
68
+				'noheader'   => true,
69
+			),
70
+			'trash_question'     => array(
71
+				'func'       => '_trash_question',
72
+				'capability' => 'ee_delete_question',
73
+				'obj_id'     => $qst_id,
74
+				'noheader'   => true,
75
+			),
76
+
77
+			'restore_question' => array(
78
+				'func'       => '_trash_or_restore_questions',
79
+				'capability' => 'ee_delete_question',
80
+				'obj_id'     => $qst_id,
81
+				'args'       => array('trash' => false),
82
+				'noheader'   => true,
83
+			),
84
+
85
+			'delete_question' => array(
86
+				'func'       => '_delete_question',
87
+				'capability' => 'ee_delete_question',
88
+				'obj_id'     => $qst_id,
89
+				'noheader'   => true,
90
+			),
91
+
92
+			'trash_questions' => array(
93
+				'func'       => '_trash_or_restore_questions',
94
+				'capability' => 'ee_delete_questions',
95
+				'args'       => array('trash' => true),
96
+				'noheader'   => true,
97
+			),
98
+
99
+			'restore_questions' => array(
100
+				'func'       => '_trash_or_restore_questions',
101
+				'capability' => 'ee_delete_questions',
102
+				'args'       => array('trash' => false),
103
+				'noheader'   => true,
104
+			),
105
+
106
+			'delete_questions' => array(
107
+				'func'       => '_delete_questions',
108
+				'args'       => array(),
109
+				'capability' => 'ee_delete_questions',
110
+				'noheader'   => true,
111
+			),
112
+
113
+			'add_question_group' => array(
114
+				'func'       => '_edit_question_group',
115
+				'capability' => 'ee_edit_question_groups',
116
+			),
117
+
118
+			'edit_question_group' => array(
119
+				'func'       => '_edit_question_group',
120
+				'capability' => 'ee_edit_question_group',
121
+				'obj_id'     => $qsg_id,
122
+				'args'       => array('edit'),
123
+			),
124
+
125
+			'delete_question_groups' => array(
126
+				'func'       => '_delete_question_groups',
127
+				'capability' => 'ee_delete_question_groups',
128
+				'noheader'   => true,
129
+			),
130
+
131
+			'delete_question_group' => array(
132
+				'func'       => '_delete_question_groups',
133
+				'capability' => 'ee_delete_question_group',
134
+				'obj_id'     => $qsg_id,
135
+				'noheader'   => true,
136
+			),
137
+
138
+			'trash_question_group' => array(
139
+				'func'       => '_trash_or_restore_question_groups',
140
+				'args'       => array('trash' => true),
141
+				'capability' => 'ee_delete_question_group',
142
+				'obj_id'     => $qsg_id,
143
+				'noheader'   => true,
144
+			),
145
+
146
+			'restore_question_group' => array(
147
+				'func'       => '_trash_or_restore_question_groups',
148
+				'args'       => array('trash' => false),
149
+				'capability' => 'ee_delete_question_group',
150
+				'obj_id'     => $qsg_id,
151
+				'noheader'   => true,
152
+			),
153
+
154
+			'insert_question_group' => array(
155
+				'func'       => '_insert_or_update_question_group',
156
+				'args'       => array('new_question_group' => true),
157
+				'capability' => 'ee_edit_question_groups',
158
+				'noheader'   => true,
159
+			),
160
+
161
+			'update_question_group' => array(
162
+				'func'       => '_insert_or_update_question_group',
163
+				'args'       => array('new_question_group' => false),
164
+				'capability' => 'ee_edit_question_group',
165
+				'obj_id'     => $qsg_id,
166
+				'noheader'   => true,
167
+			),
168
+
169
+			'trash_question_groups' => array(
170
+				'func'       => '_trash_or_restore_question_groups',
171
+				'args'       => array('trash' => true),
172
+				'capability' => 'ee_delete_question_groups',
173
+				'noheader'   => array('trash' => false),
174
+			),
175
+
176
+			'restore_question_groups' => array(
177
+				'func'       => '_trash_or_restore_question_groups',
178
+				'args'       => array('trash' => false),
179
+				'capability' => 'ee_delete_question_groups',
180
+				'noheader'   => true,
181
+			),
182
+
183
+
184
+			'espresso_update_question_group_order' => array(
185
+				'func'       => 'update_question_group_order',
186
+				'capability' => 'ee_edit_question_groups',
187
+				'noheader'   => true,
188
+			),
189
+
190
+			'view_reg_form_settings' => array(
191
+				'func'       => '_reg_form_settings',
192
+				'capability' => 'manage_options',
193
+			),
194
+
195
+			'update_reg_form_settings' => array(
196
+				'func'       => '_update_reg_form_settings',
197
+				'capability' => 'manage_options',
198
+				'noheader'   => true,
199
+			),
200
+		);
201
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
202
+
203
+		$new_page_config    = array(
204
+
205
+			'question_groups' => array(
206
+				'nav'           => array(
207
+					'label' => esc_html__('Question Groups', 'event_espresso'),
208
+					'order' => 20,
209
+				),
210
+				'list_table'    => 'Registration_Form_Question_Groups_Admin_List_Table',
211
+				'help_tabs'     => array(
212
+					'registration_form_question_groups_help_tab'                           => array(
213
+						'title'    => esc_html__('Question Groups', 'event_espresso'),
214
+						'filename' => 'registration_form_question_groups',
215
+					),
216
+					'registration_form_question_groups_table_column_headings_help_tab'     => array(
217
+						'title'    => esc_html__('Question Groups Table Column Headings', 'event_espresso'),
218
+						'filename' => 'registration_form_question_groups_table_column_headings',
219
+					),
220
+					'registration_form_question_groups_views_bulk_actions_search_help_tab' => array(
221
+						'title'    => esc_html__('Question Groups Views & Bulk Actions & Search', 'event_espresso'),
222
+						'filename' => 'registration_form_question_groups_views_bulk_actions_search',
223
+					),
224
+				),
225
+				'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
226
+				'metaboxes'     => $this->_default_espresso_metaboxes,
227
+				'require_nonce' => false,
228
+				'qtips'         => array(
229
+					'EE_Registration_Form_Tips',
230
+				),
231
+			),
232
+
233
+			'add_question' => array(
234
+				'nav'           => array(
235
+					'label'      => esc_html__('Add Question', 'event_espresso'),
236
+					'order'      => 5,
237
+					'persistent' => false,
238
+				),
239
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
240
+				'help_tabs'     => array(
241
+					'registration_form_add_question_help_tab' => array(
242
+						'title'    => esc_html__('Add Question', 'event_espresso'),
243
+						'filename' => 'registration_form_add_question',
244
+					),
245
+				),
246
+				'help_tour'     => array('Registration_Form_Add_Question_Help_Tour'),
247
+				'require_nonce' => false,
248
+			),
249
+
250
+			'add_question_group' => array(
251
+				'nav'           => array(
252
+					'label'      => esc_html__('Add Question Group', 'event_espresso'),
253
+					'order'      => 5,
254
+					'persistent' => false,
255
+				),
256
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
257
+				'help_tabs'     => array(
258
+					'registration_form_add_question_group_help_tab' => array(
259
+						'title'    => esc_html__('Add Question Group', 'event_espresso'),
260
+						'filename' => 'registration_form_add_question_group',
261
+					),
262
+				),
263
+				'help_tour'     => array('Registration_Form_Add_Question_Group_Help_Tour'),
264
+				'require_nonce' => false,
265
+			),
266
+
267
+			'edit_question_group' => array(
268
+				'nav'           => array(
269
+					'label'      => esc_html__('Edit Question Group', 'event_espresso'),
270
+					'order'      => 5,
271
+					'persistent' => false,
272
+					'url'        => isset($this->_req_data['question_group_id']) ? add_query_arg(array('question_group_id' => $this->_req_data['question_group_id']),
273
+						$this->_current_page_view_url) : $this->_admin_base_url,
274
+				),
275
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
276
+				'help_tabs'     => array(
277
+					'registration_form_edit_question_group_help_tab' => array(
278
+						'title'    => esc_html__('Edit Question Group', 'event_espresso'),
279
+						'filename' => 'registration_form_edit_question_group',
280
+					),
281
+				),
282
+				'help_tour'     => array('Registration_Form_Edit_Question_Group_Help_Tour'),
283
+				'require_nonce' => false,
284
+			),
285
+
286
+			'view_reg_form_settings' => array(
287
+				'nav'           => array(
288
+					'label' => esc_html__('Reg Form Settings', 'event_espresso'),
289
+					'order' => 40,
290
+				),
291
+				'labels'        => array(
292
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
293
+				),
294
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
295
+				'help_tabs'     => array(
296
+					'registration_form_reg_form_settings_help_tab' => array(
297
+						'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
298
+						'filename' => 'registration_form_reg_form_settings',
299
+					),
300
+				),
301
+				'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
302
+				'require_nonce' => false,
303
+			),
304
+
305
+		);
306
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
307
+
308
+		//change the list table we're going to use so it's the NEW list table!
309
+		$this->_page_config['default']['list_table'] = 'Extend_Registration_Form_Questions_Admin_List_Table';
310
+
311
+
312
+		//additional labels
313
+		$new_labels               = array(
314
+			'add_question'          => esc_html__('Add New Question', 'event_espresso'),
315
+			'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
316
+			'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
317
+			'edit_question_group'   => esc_html__('Edit Question Group', 'event_espresso'),
318
+			'delete_question_group' => esc_html__('Delete Question Group', 'event_espresso'),
319
+		);
320
+		$this->_labels['buttons'] = array_merge($this->_labels['buttons'], $new_labels);
321
+
322
+	}
323
+
324
+
325
+	protected function _ajax_hooks()
326
+	{
327
+		add_action('wp_ajax_espresso_update_question_group_order', array($this, 'update_question_group_order'));
328
+	}
329
+
330
+
331
+	public function load_scripts_styles_question_groups()
332
+	{
333
+		wp_enqueue_script('espresso_ajax_table_sorting');
334
+	}
335
+
336
+
337
+	public function load_scripts_styles_add_question_group()
338
+	{
339
+		$this->load_scripts_styles_forms();
340
+		$this->load_sortable_question_script();
341
+	}
342
+
343
+	public function load_scripts_styles_edit_question_group()
344
+	{
345
+		$this->load_scripts_styles_forms();
346
+		$this->load_sortable_question_script();
347
+	}
348
+
349
+
350
+	/**
351
+	 * registers and enqueues script for questions
352
+	 *
353
+	 * @return void
354
+	 */
355
+	public function load_sortable_question_script()
356
+	{
357
+		wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
358
+			array('jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
359
+		wp_enqueue_script('ee-question-sortable');
360
+	}
361
+
362
+
363
+	protected function _set_list_table_views_default()
364
+	{
365
+		$this->_views = array(
366
+			'all' => array(
367
+				'slug'        => 'all',
368
+				'label'       => esc_html__('View All Questions', 'event_espresso'),
369
+				'count'       => 0,
370
+				'bulk_action' => array(
371
+					'trash_questions' => esc_html__('Trash', 'event_espresso'),
372
+				),
373
+			),
374
+		);
375
+
376
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_questions',
377
+			'espresso_registration_form_trash_questions')
378
+		) {
379
+			$this->_views['trash'] = array(
380
+				'slug'        => 'trash',
381
+				'label'       => esc_html__('Trash', 'event_espresso'),
382
+				'count'       => 0,
383
+				'bulk_action' => array(
384
+					'delete_questions'  => esc_html__('Delete Permanently', 'event_espresso'),
385
+					'restore_questions' => esc_html__('Restore', 'event_espresso'),
386
+				),
387
+			);
388
+		}
389
+	}
390
+
391
+
392
+	protected function _set_list_table_views_question_groups()
393
+	{
394
+		$this->_views = array(
395
+			'all' => array(
396
+				'slug'        => 'all',
397
+				'label'       => esc_html__('All', 'event_espresso'),
398
+				'count'       => 0,
399
+				'bulk_action' => array(
400
+					'trash_question_groups' => esc_html__('Trash', 'event_espresso'),
401
+				),
402
+			),
403
+		);
404
+
405
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_question_groups',
406
+			'espresso_registration_form_trash_question_groups')
407
+		) {
408
+			$this->_views['trash'] = array(
409
+				'slug'        => 'trash',
410
+				'label'       => esc_html__('Trash', 'event_espresso'),
411
+				'count'       => 0,
412
+				'bulk_action' => array(
413
+					'delete_question_groups'  => esc_html__('Delete Permanently', 'event_espresso'),
414
+					'restore_question_groups' => esc_html__('Restore', 'event_espresso'),
415
+				),
416
+			);
417
+		}
418
+	}
419
+
420
+
421
+	protected function _questions_overview_list_table()
422
+	{
423
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
424
+				'add_question',
425
+				'add_question',
426
+				array(),
427
+				'add-new-h2'
428
+			);
429
+		parent::_questions_overview_list_table();
430
+	}
431
+
432
+
433
+	protected function _question_groups_overview_list_table()
434
+	{
435
+		$this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
436
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
437
+				'add_question_group',
438
+				'add_question_group',
439
+				array(),
440
+				'add-new-h2'
441
+			);
442
+		$this->display_admin_list_table_page_with_sidebar();
443
+	}
444
+
445
+
446
+	protected function _delete_question()
447
+	{
448
+		$success = $this->_delete_items($this->_question_model);
449
+		$this->_redirect_after_action(
450
+			$success,
451
+			$this->_question_model->item_name($success),
452
+			'deleted',
453
+			array('action' => 'default', 'status' => 'all')
454
+		);
455
+	}
456
+
457
+
458
+	protected function _delete_questions()
459
+	{
460
+		$success = $this->_delete_items($this->_question_model);
461
+		$this->_redirect_after_action(
462
+			$success,
463
+			$this->_question_model->item_name($success),
464
+			'deleted permanently',
465
+			array('action' => 'default', 'status' => 'trash')
466
+		);
467
+	}
468
+
469
+
470
+	/**
471
+	 * Performs the deletion of a single or multiple questions or question groups.
472
+	 *
473
+	 * @param EEM_Soft_Delete_Base $model
474
+	 * @return int number of items deleted permanently
475
+	 */
476
+	private function _delete_items(EEM_Soft_Delete_Base $model)
477
+	{
478
+		$success = 0;
479
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
480
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
481
+			// if array has more than one element than success message should be plural
482
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
483
+			// cycle thru bulk action checkboxes
484
+			while (list($ID, $value) = each($this->_req_data['checkbox'])) {
485
+				if (! $this->_delete_item($ID, $model)) {
486
+					$success = 0;
487
+				}
488
+			}
489
+
490
+		} elseif (! empty($this->_req_data['QSG_ID'])) {
491
+			$success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
492
+
493
+		} elseif (! empty($this->_req_data['QST_ID'])) {
494
+			$success = $this->_delete_item($this->_req_data['QST_ID'], $model);
495
+		} else {
496
+			EE_Error::add_error(sprintf(esc_html__("No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
497
+				"event_espresso")), __FILE__, __FUNCTION__, __LINE__);
498
+		}
499
+		return $success;
500
+	}
501
+
502
+	/**
503
+	 * Deletes the specified question (and its associated question options) or question group
504
+	 *
505
+	 * @param int                  $id
506
+	 * @param EEM_Soft_Delete_Base $model
507
+	 * @return boolean
508
+	 */
509
+	protected function _delete_item($id, $model)
510
+	{
511
+		if ($model instanceof EEM_Question) {
512
+			EEM_Question_Option::instance()->delete_permanently(array(array('QST_ID' => absint($id))));
513
+		}
514
+		return $model->delete_permanently_by_ID(absint($id));
515
+	}
516
+
517
+
518
+	/******************************    QUESTION GROUPS    ******************************/
519
+
520
+
521
+	protected function _edit_question_group($type = 'add')
522
+	{
523
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
+		$ID = isset($this->_req_data['QSG_ID']) && ! empty($this->_req_data['QSG_ID']) ? absint($this->_req_data['QSG_ID']) : false;
525
+
526
+		switch ($this->_req_action) {
527
+			case 'add_question_group' :
528
+				$this->_admin_page_title = esc_html__('Add Question Group', 'event_espresso');
529
+				break;
530
+			case 'edit_question_group' :
531
+				$this->_admin_page_title = esc_html__('Edit Question Group', 'event_espresso');
532
+				break;
533
+			default :
534
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
535
+		}
536
+		// add ID to title if editing
537
+		$this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
538
+		if ($ID) {
539
+			/** @var EE_Question_Group $questionGroup */
540
+			$questionGroup            = $this->_question_group_model->get_one_by_ID($ID);
541
+			$additional_hidden_fields = array('QSG_ID' => array('type' => 'hidden', 'value' => $ID));
542
+			$this->_set_add_edit_form_tags('update_question_group', $additional_hidden_fields);
543
+		} else {
544
+			/** @var EE_Question_Group $questionGroup */
545
+			$questionGroup = EEM_Question_Group::instance()->create_default_object();
546
+			$questionGroup->set_order_to_latest();
547
+			$this->_set_add_edit_form_tags('insert_question_group');
548
+		}
549
+		$this->_template_args['values']         = $this->_yes_no_values;
550
+		$this->_template_args['all_questions']  = $questionGroup->questions_in_and_not_in_group();
551
+		$this->_template_args['QSG_ID']         = $ID ? $ID : true;
552
+		$this->_template_args['question_group'] = $questionGroup;
553
+
554
+		$redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
555
+		$this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
556
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
557
+			$this->_template_args, true);
558
+
559
+		// the details template wrapper
560
+		$this->display_admin_page_with_sidebar();
561
+	}
562
+
563
+
564
+	protected function _delete_question_groups()
565
+	{
566
+		$success = $this->_delete_items($this->_question_group_model);
567
+		$this->_redirect_after_action($success, $this->_question_group_model->item_name($success),
568
+			'deleted permanently', array('action' => 'question_groups', 'status' => 'trash'));
569
+	}
570
+
571
+
572
+	/**
573
+	 * @param bool $new_question_group
574
+	 */
575
+	protected function _insert_or_update_question_group($new_question_group = true)
576
+	{
577
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
+		$set_column_values = $this->_set_column_values_for($this->_question_group_model);
579
+		if ($new_question_group) {
580
+			$QSG_ID  = $this->_question_group_model->insert($set_column_values);
581
+			$success = $QSG_ID ? 1 : 0;
582
+		} else {
583
+			$QSG_ID = absint($this->_req_data['QSG_ID']);
584
+			unset($set_column_values['QSG_ID']);
585
+			$success = $this->_question_group_model->update($set_column_values, array(array('QSG_ID' => $QSG_ID)));
586
+		}
587
+		$phone_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(EEM_Attendee::system_question_phone);
588
+		// update the existing related questions
589
+		// BUT FIRST...  delete the phone question from the Question_Group_Question if it is being added to this question group (therefore removed from the existing group)
590
+		if (isset($this->_req_data['questions'], $this->_req_data['questions'][$phone_question_id])) {
591
+			// delete where QST ID = system phone question ID and Question Group ID is NOT this group
592
+			EEM_Question_Group_Question::instance()->delete(array(
593
+				array(
594
+					'QST_ID' => $phone_question_id,
595
+					'QSG_ID' => array('!=', $QSG_ID),
596
+				),
597
+			));
598
+		}
599
+		/** @type EE_Question_Group $question_group */
600
+		$question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
601
+		$questions      = $question_group->questions();
602
+		// make sure system phone question is added to list of questions for this group
603
+		if (! isset($questions[$phone_question_id])) {
604
+			$questions[$phone_question_id] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
605
+		}
606
+
607
+		foreach ($questions as $question_ID => $question) {
608
+			// first we always check for order.
609
+			if (! empty($this->_req_data['question_orders'][$question_ID])) {
610
+				//update question order
611
+				$question_group->update_question_order($question_ID, $this->_req_data['question_orders'][$question_ID]);
612
+			}
613
+
614
+			// then we always check if adding or removing.
615
+			if (isset($this->_req_data['questions'], $this->_req_data['questions'][$question_ID])) {
616
+				$question_group->add_question($question_ID);
617
+			} else {
618
+				// not found, remove it (but only if not a system question for the personal group with the exception of lname system question - we allow removal of it)
619
+				if (
620
+				in_array(
621
+					$question->system_ID(),
622
+					EEM_Question::instance()->required_system_questions_in_system_question_group($question_group->system_group())
623
+				)
624
+				) {
625
+					continue;
626
+				} else {
627
+					$question_group->remove_question($question_ID);
628
+				}
629
+			}
630
+		}
631
+		// save new related questions
632
+		if (isset($this->_req_data['questions'])) {
633
+			foreach ($this->_req_data['questions'] as $QST_ID) {
634
+				$question_group->add_question($QST_ID);
635
+				if (isset($this->_req_data['question_orders'][$QST_ID])) {
636
+					$question_group->update_question_order($QST_ID, $this->_req_data['question_orders'][$QST_ID]);
637
+				}
638
+			}
639
+		}
640
+
641
+		if ($success !== false) {
642
+			$msg = $new_question_group ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
643
+				$this->_question_group_model->item_name()) : sprintf(esc_html__('The %s has been updated',
644
+				'event_espresso'), $this->_question_group_model->item_name());
645
+			EE_Error::add_success($msg);
646
+		}
647
+		$this->_redirect_after_action(false, '', '', array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
648
+			true);
649
+
650
+	}
651
+
652
+	/**
653
+	 * duplicates a question and all its question options and redirects to the new question.
654
+	 */
655
+	public function _duplicate_question()
656
+	{
657
+		$question_ID = (int)$this->_req_data['QST_ID'];
658
+		$question    = EEM_Question::instance()->get_one_by_ID($question_ID);
659
+		if ($question instanceof EE_Question) {
660
+			$new_question = $question->duplicate();
661
+			if ($new_question instanceof EE_Question) {
662
+				$this->_redirect_after_action(true, esc_html__('Question', 'event_espresso'),
663
+					esc_html__('Duplicated', 'event_espresso'),
664
+					array('action' => 'edit_question', 'QST_ID' => $new_question->ID()), true);
665
+			} else {
666
+				global $wpdb;
667
+				EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %1$d because: %2$s',
668
+					'event_espresso'), $question_ID, $wpdb->last_error), __FILE__, __FUNCTION__, __LINE__);
669
+				$this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
670
+			}
671
+		} else {
672
+			EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %d because it didn\'t exist!',
673
+				'event_espresso'), $question_ID), __FILE__, __FUNCTION__, __LINE__);
674
+			$this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
675
+		}
676
+	}
677
+
678
+
679
+	/**
680
+	 * @param bool $trash
681
+	 */
682
+	protected function _trash_or_restore_question_groups($trash = true)
683
+	{
684
+		$this->_trash_or_restore_items($this->_question_group_model, $trash);
685
+	}
686
+
687
+
688
+	/**
689
+	 *_trash_question
690
+	 */
691
+	protected function _trash_question()
692
+	{
693
+		$success    = $this->_question_model->delete_by_ID((int)$this->_req_data['QST_ID']);
694
+		$query_args = array('action' => 'default', 'status' => 'all');
695
+		$this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
696
+	}
697
+
698
+
699
+	/**
700
+	 * @param bool $trash
701
+	 */
702
+	protected function _trash_or_restore_questions($trash = true)
703
+	{
704
+		$this->_trash_or_restore_items($this->_question_model, $trash);
705
+	}
706
+
707
+
708
+	/**
709
+	 * Internally used to delete or restore items, using the request data. Meant to be
710
+	 * flexible between question or question groups
711
+	 *
712
+	 * @param EEM_Soft_Delete_Base $model
713
+	 * @param boolean              $trash whether to trash or restore
714
+	 */
715
+	private function _trash_or_restore_items(EEM_Soft_Delete_Base $model, $trash = true)
716
+	{
717
+
718
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
719
+
720
+		$success = 1;
721
+		//Checkboxes
722
+		//echo "trash $trash";
723
+		//var_dump($this->_req_data['checkbox']);die;
724
+		if (isset($this->_req_data['checkbox'])) {
725
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
726
+				// if array has more than one element than success message should be plural
727
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
728
+				// cycle thru bulk action checkboxes
729
+				while (list($ID, $value) = each($this->_req_data['checkbox'])) {
730
+					if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
731
+						$success = 0;
732
+					}
733
+				}
734
+
735
+			} else {
736
+				// grab single id and delete
737
+				$ID = absint($this->_req_data['checkbox']);
738
+				if (! $model->delete_or_restore_by_ID($trash, $ID)) {
739
+					$success = 0;
740
+				}
741
+			}
742
+
743
+		} else {
744
+			// delete via trash link
745
+			// grab single id and delete
746
+			$ID = absint($this->_req_data[$model->primary_key_name()]);
747
+			if (! $model->delete_or_restore_by_ID($trash, $ID)) {
748
+				$success = 0;
749
+			}
750
+
751
+		}
752
+
753
+
754
+		$action = $model instanceof EEM_Question ? 'default' : 'question_groups';//strtolower( $model->item_name(2) );
755
+		//echo "action :$action";
756
+		//$action = 'questions' ? 'default' : $action;
757
+		if ($trash) {
758
+			$action_desc = 'trashed';
759
+			$status      = 'trash';
760
+		} else {
761
+			$action_desc = 'restored';
762
+			$status      = 'all';
763
+		}
764
+		$this->_redirect_after_action($success, $model->item_name($success), $action_desc,
765
+			array('action' => $action, 'status' => $status));
766
+	}
767
+
768
+
769
+	/**
770
+	 * @param            $per_page
771
+	 * @param int        $current_page
772
+	 * @param bool|false $count
773
+	 * @return \EE_Soft_Delete_Base_Class[]|int
774
+	 */
775
+	public function get_trashed_questions($per_page, $current_page = 1, $count = false)
776
+	{
777
+		$query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
778
+
779
+		if ($count) {
780
+			//note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
781
+			$where   = isset($query_params[0]) ? array($query_params[0]) : array();
782
+			$results = $this->_question_model->count_deleted($where);
783
+		} else {
784
+			//note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
785
+			$results = $this->_question_model->get_all_deleted($query_params);
786
+		}
787
+		return $results;
788
+	}
789
+
790
+
791
+	/**
792
+	 * @param            $per_page
793
+	 * @param int        $current_page
794
+	 * @param bool|false $count
795
+	 * @return \EE_Soft_Delete_Base_Class[]
796
+	 */
797
+	public function get_question_groups($per_page, $current_page = 1, $count = false)
798
+	{
799
+		$questionGroupModel = EEM_Question_Group::instance();
800
+		$query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
801
+		if ($count) {
802
+			$where   = isset($query_params[0]) ? array($query_params[0]) : array();
803
+			$results = $questionGroupModel->count($where);
804
+		} else {
805
+			$results = $questionGroupModel->get_all($query_params);
806
+		}
807
+		return $results;
808
+	}
809
+
810
+
811
+	/**
812
+	 * @param      $per_page
813
+	 * @param int  $current_page
814
+	 * @param bool $count
815
+	 * @return \EE_Soft_Delete_Base_Class[]|int
816
+	 */
817
+	public function get_trashed_question_groups($per_page, $current_page = 1, $count = false)
818
+	{
819
+		$questionGroupModel = EEM_Question_Group::instance();
820
+		$query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
821
+		if ($count) {
822
+			$where                 = isset($query_params[0]) ? array($query_params[0]) : array();
823
+			$query_params['limit'] = null;
824
+			$results               = $questionGroupModel->count_deleted($where);
825
+		} else {
826
+			$results = $questionGroupModel->get_all_deleted($query_params);
827
+		}
828
+		return $results;
829
+	}
830
+
831
+
832
+	/**
833
+	 * method for performing updates to question order
834
+	 *
835
+	 * @return array results array
836
+	 */
837
+	public function update_question_group_order()
838
+	{
839
+
840
+		$success = esc_html__('Question group order was updated successfully.', 'event_espresso');
841
+
842
+		// grab our row IDs
843
+		$row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids'])
844
+			? explode(',', rtrim($this->_req_data['row_ids'], ','))
845
+			: array();
846
+
847
+		$perpage = ! empty($this->_req_data['perpage'])
848
+			? (int)$this->_req_data['perpage']
849
+			: null;
850
+		$curpage = ! empty($this->_req_data['curpage'])
851
+			? (int)$this->_req_data['curpage']
852
+			: null;
853
+
854
+		if (! empty($row_ids)) {
855
+			//figure out where we start the row_id count at for the current page.
856
+			$qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
857
+
858
+			$row_count = count($row_ids);
859
+			for ($i = 0; $i < $row_count; $i++) {
860
+				//Update the questions when re-ordering
861
+				$updated = EEM_Question_Group::instance()->update(
862
+					array('QSG_order' => $qsgcount),
863
+					array(array('QSG_ID' => $row_ids[$i]))
864
+				);
865
+				if ($updated === false) {
866
+					$success = false;
867
+				}
868
+				$qsgcount++;
869
+			}
870
+		} else {
871
+			$success = false;
872
+		}
873
+
874
+		$errors = ! $success
875
+			? esc_html__('An error occurred. The question group order was not updated.', 'event_espresso')
876
+			: false;
877
+
878
+		echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
879
+		die();
880
+
881
+	}
882
+
883
+
884
+
885
+	/***************************************        REGISTRATION SETTINGS        ***************************************/
886
+
887
+
888
+	/**
889
+	 * _reg_form_settings
890
+	 *
891
+	 * @throws \EE_Error
892
+	 */
893
+	protected function _reg_form_settings()
894
+	{
895
+		$this->_template_args['values'] = $this->_yes_no_values;
896
+		add_action(
897
+			'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
898
+			array($this, 'email_validation_settings_form'),
899
+			2
900
+		);
901
+		$this->_template_args = (array)apply_filters(
902
+			'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
903
+			$this->_template_args
904
+		);
905
+		$this->_set_add_edit_form_tags('update_reg_form_settings');
906
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
907
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
908
+			REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
909
+			$this->_template_args,
910
+			true
911
+		);
912
+		$this->display_admin_page_with_sidebar();
913
+	}
914
+
915
+
916
+	/**
917
+	 * _update_reg_form_settings
918
+	 */
919
+	protected function _update_reg_form_settings()
920
+	{
921
+		EE_Registry::instance()->CFG->registration = $this->update_email_validation_settings_form(
922
+			EE_Registry::instance()->CFG->registration
923
+		);
924
+		EE_Registry::instance()->CFG->registration = apply_filters(
925
+			'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
926
+			EE_Registry::instance()->CFG->registration
927
+		);
928
+		$success                                   = $this->_update_espresso_configuration(
929
+			esc_html__('Registration Form Options', 'event_espresso'),
930
+			EE_Registry::instance()->CFG,
931
+			__FILE__, __FUNCTION__, __LINE__
932
+		);
933
+		$this->_redirect_after_action($success, esc_html__('Registration Form Options', 'event_espresso'), 'updated',
934
+			array('action' => 'view_reg_form_settings'));
935
+	}
936
+
937
+
938
+	/**
939
+	 * email_validation_settings_form
940
+	 *
941
+	 * @access    public
942
+	 * @return    void
943
+	 * @throws \EE_Error
944
+	 */
945
+	public function email_validation_settings_form()
946
+	{
947
+		echo $this->_email_validation_settings_form()->get_html();
948
+	}
949
+
950
+
951
+	/**
952
+	 * _email_validation_settings_form
953
+	 *
954
+	 * @access protected
955
+	 * @return EE_Form_Section_Proper
956
+	 * @throws \EE_Error
957
+	 */
958
+	protected function _email_validation_settings_form()
959
+	{
960
+		return new EE_Form_Section_Proper(
961
+			array(
962
+				'name'            => 'email_validation_settings',
963
+				'html_id'         => 'email_validation_settings',
964
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
965
+				'subsections'     => apply_filters(
966
+					'FHEE__Extend_Registration_Form_Admin_Page___email_validation_settings_form__form_subsections',
967
+					array(
968
+						'email_validation_hdr'   => new EE_Form_Section_HTML(
969
+							EEH_HTML::h2(esc_html__('Email Validation Settings', 'event_espresso'))
970
+						),
971
+						'email_validation_level' => new EE_Select_Input(
972
+							array(
973
+								'basic'      => esc_html__('Basic', 'event_espresso'),
974
+								'wp_default' => esc_html__('WordPress Default', 'event_espresso'),
975
+								'i18n'       => esc_html__('International', 'event_espresso'),
976
+								'i18n_dns'   => esc_html__('International + DNS Check', 'event_espresso'),
977
+							),
978
+							array(
979
+								'html_label_text' => esc_html__('Email Validation Level', 'event_espresso')
980
+													 . EEH_Template::get_help_tab_link('email_validation_info'),
981
+								'html_help_text'  => esc_html__('These levels range from basic validation ( ie: [email protected] ) to more advanced checks against international email addresses (ie: üñîçøðé@example.com ) with additional MX and A record checks to confirm the domain actually exists. More information on on each level can be found within the help section.',
982
+									'event_espresso'),
983
+								'default'         => isset(EE_Registry::instance()->CFG->registration->email_validation_level)
984
+									? EE_Registry::instance()->CFG->registration->email_validation_level
985
+									: 'wp_default',
986
+								'required'        => false,
987
+							)
988
+						),
989
+					)
990
+				),
991
+			)
992
+		);
993
+	}
994
+
995
+
996
+	/**
997
+	 * update_email_validation_settings_form
998
+	 *
999
+	 * @access    public
1000
+	 * @param \EE_Registration_Config $EE_Registration_Config
1001
+	 * @return \EE_Registration_Config
1002
+	 */
1003
+	public function update_email_validation_settings_form(EE_Registration_Config $EE_Registration_Config)
1004
+	{
1005
+		$prev_email_validation_level = $EE_Registration_Config->email_validation_level;
1006
+		try {
1007
+			$email_validation_settings_form = $this->_email_validation_settings_form();
1008
+			// if not displaying a form, then check for form submission
1009
+			if ($email_validation_settings_form->was_submitted()) {
1010
+				// capture form data
1011
+				$email_validation_settings_form->receive_form_submission();
1012
+				// validate form data
1013
+				if ($email_validation_settings_form->is_valid()) {
1014
+					// grab validated data from form
1015
+					$valid_data = $email_validation_settings_form->valid_data();
1016
+					if (isset($valid_data['email_validation_level'])) {
1017
+						$email_validation_level = $valid_data['email_validation_level'];
1018
+						// now if they want to use international email addresses
1019
+						if ($email_validation_level === 'i18n' || $email_validation_level === 'i18n_dns') {
1020
+							// in case we need to reset their email validation level,
1021
+							// make sure that the previous value wasn't already set to one of the i18n options.
1022
+							if ($prev_email_validation_level === 'i18n' || $prev_email_validation_level === 'i18n_dns') {
1023
+								// if so, then reset it back to "basic" since that is the only other option that,
1024
+								// despite offering poor validation, supports i18n email addresses
1025
+								$prev_email_validation_level = 'basic';
1026
+							}
1027
+							// confirm our i18n email validation will work on the server
1028
+							if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1029
+								// or reset email validation level to previous value
1030
+								$email_validation_level = $prev_email_validation_level;
1031
+							}
1032
+						}
1033
+						$EE_Registration_Config->email_validation_level = $email_validation_level;
1034
+					} else {
1035
+						EE_Error::add_error(
1036
+							esc_html__(
1037
+								'Invalid or missing Email Validation settings. Please refresh the form and try again.',
1038
+								'event_espresso'
1039
+							),
1040
+							__FILE__, __FUNCTION__, __LINE__
1041
+						);
1042
+					}
1043
+				} else {
1044
+					if ($email_validation_settings_form->submission_error_message() !== '') {
1045
+						EE_Error::add_error(
1046
+							$email_validation_settings_form->submission_error_message(),
1047
+							__FILE__, __FUNCTION__, __LINE__
1048
+						);
1049
+					}
1050
+				}
1051
+			}
1052
+		} catch (EE_Error $e) {
1053
+			$e->get_error();
1054
+		}
1055
+		return $EE_Registration_Config;
1056
+	}
1057
+
1058
+
1059
+	/**
1060
+	 * confirms that the server's PHP version has the PCRE module enabled,
1061
+	 * and that the PCRE version works with our i18n email validation
1062
+	 *
1063
+	 * @param \EE_Registration_Config $EE_Registration_Config
1064
+	 * @param string                  $email_validation_level
1065
+	 * @return bool
1066
+	 */
1067
+	private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1068
+	{
1069
+		// first check that PCRE is enabled
1070
+		if (! defined('PREG_BAD_UTF8_ERROR')) {
1071
+			EE_Error::add_error(
1072
+				sprintf(
1073
+					esc_html__(
1074
+						'We\'re sorry, but it appears that your server\'s version of PHP was not compiled with PCRE unicode support.%1$sPlease contact your hosting company and ask them whether the PCRE compiled with your version of PHP on your server can be been built with the "--enable-unicode-properties" and "--enable-utf8" configuration switches to enable more complex regex expressions.%1$sIf they are unable, or unwilling to do so, then your server will not support international email addresses using UTF-8 unicode characters. This means you will either have to lower your email validation level to "Basic" or "WordPress Default", or switch to a hosting company that has/can enable PCRE unicode support on the server.',
1075
+						'event_espresso'
1076
+					),
1077
+					'<br />'
1078
+				),
1079
+				__FILE__,
1080
+				__FUNCTION__,
1081
+				__LINE__
1082
+			);
1083
+			return false;
1084
+		} else {
1085
+			// PCRE support is enabled, but let's still
1086
+			// perform a test to see if the server will support it.
1087
+			// but first, save the updated validation level to the config,
1088
+			// so that the validation strategy picks it up.
1089
+			// this will get bumped back down if it doesn't work
1090
+			$EE_Registration_Config->email_validation_level = $email_validation_level;
1091
+			try {
1092
+				$email_validator    = new EE_Email_Validation_Strategy();
1093
+				$i18n_email_address = apply_filters(
1094
+					'FHEE__Extend_Registration_Form_Admin_Page__update_email_validation_settings_form__i18n_email_address',
1095
+					'jägerjü[email protected]'
1096
+				);
1097
+				$email_validator->validate($i18n_email_address);
1098
+			} catch (Exception $e) {
1099
+				EE_Error::add_error(
1100
+					sprintf(
1101
+						esc_html__(
1102
+							'We\'re sorry, but it appears that your server\'s configuration will not support the "International" or "International + DNS Check" email validation levels.%1$sTo correct this issue, please consult with your hosting company regarding your server\'s PCRE settings.%1$sIt is recommended that your PHP version be configured to use PCRE 8.10 or newer.%1$sMore information regarding PCRE versions and installation can be found here: %2$s',
1103
+							'event_espresso'
1104
+						),
1105
+						'<br />',
1106
+						'<a href="http://php.net/manual/en/pcre.installation.php" target="_blank">http://php.net/manual/en/pcre.installation.php</a>'
1107
+					),
1108
+					__FILE__, __FUNCTION__, __LINE__
1109
+				);
1110
+				return false;
1111
+			}
1112
+		}
1113
+		return true;
1114
+	}
1115 1115
 
1116 1116
 
1117 1117
 }
Please login to merge, or discard this patch.
core/wordpress-shims.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -5,51 +5,51 @@
 block discarded – undo
5 5
  * it does not override any existing definition of the function in WP.
6 6
  */
7 7
 if ( ! function_exists( 'get_preview_post_link' ) ) {
8
-    /**
9
-     * Function was added in WordPress 4.4.0
10
-     * @param null   $post
11
-     * @param array  $query_args
12
-     * @param string $preview_link
13
-     * @return mixed
14
-     */
15
-    function get_preview_post_link($post = null, $query_args = array(), $preview_link = '')
16
-    {
17
-        $post = get_post($post);
18
-        if (! $post) {
19
-            return '';
20
-        }
8
+	/**
9
+	 * Function was added in WordPress 4.4.0
10
+	 * @param null   $post
11
+	 * @param array  $query_args
12
+	 * @param string $preview_link
13
+	 * @return mixed
14
+	 */
15
+	function get_preview_post_link($post = null, $query_args = array(), $preview_link = '')
16
+	{
17
+		$post = get_post($post);
18
+		if (! $post) {
19
+			return '';
20
+		}
21 21
 
22
-        $post_type_object = get_post_type_object($post->post_type);
23
-        if (is_post_type_viewable($post_type_object)) {
24
-            if (! $preview_link) {
25
-                $preview_link = set_url_scheme(get_permalink($post));
26
-            }
22
+		$post_type_object = get_post_type_object($post->post_type);
23
+		if (is_post_type_viewable($post_type_object)) {
24
+			if (! $preview_link) {
25
+				$preview_link = set_url_scheme(get_permalink($post));
26
+			}
27 27
 
28
-            $query_args['preview'] = 'true';
29
-            $preview_link          = add_query_arg($query_args, $preview_link);
30
-        }
28
+			$query_args['preview'] = 'true';
29
+			$preview_link          = add_query_arg($query_args, $preview_link);
30
+		}
31 31
 
32
-        /**
33
-         * Filters the URL used for a post preview.
34
-         *
35
-         * @since 2.0.5
36
-         * @since 4.0.0 Added the `$post` parameter.
37
-         * @param string  $preview_link URL used for the post preview.
38
-         * @param WP_Post $post         Post object.
39
-         */
40
-        return apply_filters('preview_post_link', $preview_link, $post);
41
-    }
32
+		/**
33
+		 * Filters the URL used for a post preview.
34
+		 *
35
+		 * @since 2.0.5
36
+		 * @since 4.0.0 Added the `$post` parameter.
37
+		 * @param string  $preview_link URL used for the post preview.
38
+		 * @param WP_Post $post         Post object.
39
+		 */
40
+		return apply_filters('preview_post_link', $preview_link, $post);
41
+	}
42 42
 }
43 43
 
44 44
 if ( ! function_exists( 'is_post_type_viewable' ) ) {
45
-    function is_post_type_viewable( $post_type ) {
46
-        if ( is_scalar( $post_type ) ) {
47
-            $post_type = get_post_type_object( $post_type );
48
-            if ( ! $post_type ) {
49
-                return false;
50
-            }
51
-        }
45
+	function is_post_type_viewable( $post_type ) {
46
+		if ( is_scalar( $post_type ) ) {
47
+			$post_type = get_post_type_object( $post_type );
48
+			if ( ! $post_type ) {
49
+				return false;
50
+			}
51
+		}
52 52
      
53
-        return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
54
-    }
53
+		return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
54
+	}
55 55
 }
56 56
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
  * Note: this file should only be required right before calling the function the shim is for.  This is to ensure that
5 5
  * it does not override any existing definition of the function in WP.
6 6
  */
7
-if ( ! function_exists( 'get_preview_post_link' ) ) {
7
+if ( ! function_exists('get_preview_post_link')) {
8 8
     /**
9 9
      * Function was added in WordPress 4.4.0
10 10
      * @param null   $post
@@ -15,13 +15,13 @@  discard block
 block discarded – undo
15 15
     function get_preview_post_link($post = null, $query_args = array(), $preview_link = '')
16 16
     {
17 17
         $post = get_post($post);
18
-        if (! $post) {
18
+        if ( ! $post) {
19 19
             return '';
20 20
         }
21 21
 
22 22
         $post_type_object = get_post_type_object($post->post_type);
23 23
         if (is_post_type_viewable($post_type_object)) {
24
-            if (! $preview_link) {
24
+            if ( ! $preview_link) {
25 25
                 $preview_link = set_url_scheme(get_permalink($post));
26 26
             }
27 27
 
@@ -41,15 +41,15 @@  discard block
 block discarded – undo
41 41
     }
42 42
 }
43 43
 
44
-if ( ! function_exists( 'is_post_type_viewable' ) ) {
45
-    function is_post_type_viewable( $post_type ) {
46
-        if ( is_scalar( $post_type ) ) {
47
-            $post_type = get_post_type_object( $post_type );
48
-            if ( ! $post_type ) {
44
+if ( ! function_exists('is_post_type_viewable')) {
45
+    function is_post_type_viewable($post_type) {
46
+        if (is_scalar($post_type)) {
47
+            $post_type = get_post_type_object($post_type);
48
+            if ( ! $post_type) {
49 49
                 return false;
50 50
             }
51 51
         }
52 52
      
53
-        return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
53
+        return $post_type->publicly_queryable || ($post_type->_builtin && $post_type->public);
54 54
     }
55 55
 }
56 56
\ No newline at end of file
Please login to merge, or discard this patch.
core/helpers/EEH_File.helper.php 4 patches
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -325,8 +325,8 @@
 block discarded – undo
325 325
 		//eg if given "/var/something/somewhere/", we want to get "somewhere"'s
326 326
 		//parent folder, "/var/something/"
327 327
 		$ds = strlen($file_or_folder_path) > 1
328
-            ? strrpos($file_or_folder_path, DS, -2)
329
-            : strlen($file_or_folder_path);
328
+			? strrpos($file_or_folder_path, DS, -2)
329
+			: strlen($file_or_folder_path);
330 330
 		return substr($file_or_folder_path, 0, $ds + 1);
331 331
 	}
332 332
 
Please login to merge, or discard this patch.
Doc Comments   -2 removed lines patch added patch discarded remove patch
@@ -658,8 +658,6 @@
 block discarded – undo
658 658
 	 * converts it into a "remote" filepath (the filepath the currently-in-use
659 659
 	 * $wp_filesystem needs to use access the folder or file).
660 660
 	 * See http://wordpress.stackexchange.com/questions/124900/using-wp-filesystem-in-plugins
661
-	 * @param WP_Filesystem_Base $wp_filesystem we aren't initially sure which one
662
-	 * is in use, so you need to provide it
663 661
 	 * @param string $local_filepath the filepath to the folder/file locally
664 662
 	 * @throws EE_Error if filesystem credentials are required
665 663
 	 * @return string the remote filepath (eg the filepath the filesystem method, eg
Please login to merge, or discard this patch.
Spacing   +174 added lines, -174 removed lines patch added patch discarded remove patch
@@ -38,30 +38,30 @@  discard block
 block discarded – undo
38 38
 	 * @throws EE_Error if filesystem credentials are required
39 39
 	 * @return WP_Filesystem_Base
40 40
 	 */
41
-	private static function _get_wp_filesystem( $filepath = null) {
42
-		if( apply_filters(
41
+	private static function _get_wp_filesystem($filepath = null) {
42
+		if (apply_filters(
43 43
 				'FHEE__EEH_File___get_wp_filesystem__allow_using_filesystem_direct',
44
-				$filepath && EEH_File::is_in_uploads_folder( $filepath ),
45
-				$filepath ) ) {
46
-			if( ! EEH_File::$_wp_filesystem_direct instanceof WP_Filesystem_Direct ) {
47
-				require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
44
+				$filepath && EEH_File::is_in_uploads_folder($filepath),
45
+				$filepath )) {
46
+			if ( ! EEH_File::$_wp_filesystem_direct instanceof WP_Filesystem_Direct) {
47
+				require_once(ABSPATH.'wp-admin/includes/class-wp-filesystem-base.php');
48 48
 				$method = 'direct';
49
-				$wp_filesystem_direct_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method );
49
+				$wp_filesystem_direct_file = apply_filters('filesystem_method_file', ABSPATH.'wp-admin/includes/class-wp-filesystem-'.$method.'.php', $method);
50 50
 				//check constants defined, just like in wp-admin/includes/file.php's WP_Filesystem()
51
-				if ( ! defined('FS_CHMOD_DIR') ) {
52
-					define('FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
51
+				if ( ! defined('FS_CHMOD_DIR')) {
52
+					define('FS_CHMOD_DIR', (fileperms(ABSPATH) & 0777 | 0755));
53 53
 				}
54
-				if ( ! defined('FS_CHMOD_FILE') ) {
55
-					define('FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
54
+				if ( ! defined('FS_CHMOD_FILE')) {
55
+					define('FS_CHMOD_FILE', (fileperms(ABSPATH.'index.php') & 0777 | 0644));
56 56
 				}
57
-				require_once( $wp_filesystem_direct_file );
58
-				EEH_File::$_wp_filesystem_direct = new WP_Filesystem_Direct( array() );
57
+				require_once($wp_filesystem_direct_file);
58
+				EEH_File::$_wp_filesystem_direct = new WP_Filesystem_Direct(array());
59 59
 			}
60 60
 			return EEH_File::$_wp_filesystem_direct;
61 61
 		}
62 62
 		global $wp_filesystem;
63 63
 		// no filesystem setup ???
64
-		if ( ! $wp_filesystem instanceof WP_Filesystem_Base ) {
64
+		if ( ! $wp_filesystem instanceof WP_Filesystem_Base) {
65 65
 			// if some eager beaver's just trying to get in there too early...
66 66
 			// let them do it, because we are one of those eager beavers! :P
67 67
 			/**
@@ -74,34 +74,34 @@  discard block
 block discarded – undo
74 74
 			 * and there may be troubles if the WP files are owned by a different user
75 75
 			 * than the server user. But both of these issues should exist in 4.4 and earlier too
76 76
 			 */
77
-			if ( FALSE && ! did_action( 'wp_loaded' )) {
77
+			if (FALSE && ! did_action('wp_loaded')) {
78 78
 				$msg = __('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso');
79
-				if ( WP_DEBUG ) {
80
-					$msg .= '<br />' .  __('The WP Filesystem can not be accessed until after the "wp_loaded" hook has run, so it\'s best not to attempt access until the "admin_init" hookpoint.', 'event_espresso');
79
+				if (WP_DEBUG) {
80
+					$msg .= '<br />'.__('The WP Filesystem can not be accessed until after the "wp_loaded" hook has run, so it\'s best not to attempt access until the "admin_init" hookpoint.', 'event_espresso');
81 81
 				}
82
-				throw new EE_Error( $msg );
82
+				throw new EE_Error($msg);
83 83
 			} else {
84 84
 				// should be loaded if we are past the wp_loaded hook...
85
-				if ( ! function_exists( 'WP_Filesystem' )) {
86
-					require_once( ABSPATH . 'wp-admin/includes/file.php' );
87
-					require_once( ABSPATH . 'wp-admin/includes/template.php' );
85
+				if ( ! function_exists('WP_Filesystem')) {
86
+					require_once(ABSPATH.'wp-admin/includes/file.php');
87
+					require_once(ABSPATH.'wp-admin/includes/template.php');
88 88
 				}
89 89
 				// turn on output buffering so that we can capture the credentials form
90 90
 				ob_start();
91
-				$credentials = request_filesystem_credentials( '' );
91
+				$credentials = request_filesystem_credentials('');
92 92
 				// store credentials form for the time being
93 93
 				EEH_File::$_credentials_form = ob_get_clean();
94 94
 				// basically check for direct or previously configured access
95
-				if ( ! WP_Filesystem( $credentials ) ) {
95
+				if ( ! WP_Filesystem($credentials)) {
96 96
 					// if credentials do NOT exist
97
-					if ( $credentials === FALSE ) {
98
-						add_action( 'admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999 );
99
-						throw new EE_Error( __('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso'));
100
-					} elseif( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->get_error_code() ) {
101
-						add_action( 'admin_notices', array( 'EEH_File', 'display_request_filesystem_credentials_form' ), 999 );
97
+					if ($credentials === FALSE) {
98
+						add_action('admin_notices', array('EEH_File', 'display_request_filesystem_credentials_form'), 999);
99
+						throw new EE_Error(__('An attempt to access and/or write to a file on the server could not be completed due to a lack of sufficient credentials.', 'event_espresso'));
100
+					} elseif (is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code()) {
101
+						add_action('admin_notices', array('EEH_File', 'display_request_filesystem_credentials_form'), 999);
102 102
 						throw new EE_Error(
103 103
 								sprintf(
104
-										__( 'WP Filesystem Error: $1%s', 'event_espresso' ),
104
+										__('WP Filesystem Error: $1%s', 'event_espresso'),
105 105
 										$wp_filesystem->errors->get_error_message() ) );
106 106
 					}
107 107
 				}
@@ -114,8 +114,8 @@  discard block
 block discarded – undo
114 114
 	 * display_request_filesystem_credentials_form
115 115
 	 */
116 116
 	public static function display_request_filesystem_credentials_form() {
117
-		if ( ! empty( EEH_File::$_credentials_form )) {
118
-			echo '<div class="updated espresso-notices-attention"><p>' . EEH_File::$_credentials_form . '</p></div>';
117
+		if ( ! empty(EEH_File::$_credentials_form)) {
118
+			echo '<div class="updated espresso-notices-attention"><p>'.EEH_File::$_credentials_form.'</p></div>';
119 119
 		}
120 120
 	}
121 121
 
@@ -133,29 +133,29 @@  discard block
 block discarded – undo
133 133
 	 * @throws EE_Error if filesystem credentials are required
134 134
 	 * @return bool
135 135
 	 */
136
-	public static function verify_filepath_and_permissions( $full_file_path = '', $file_name = '', $file_ext = '', $type_of_file = '' ) {
136
+	public static function verify_filepath_and_permissions($full_file_path = '', $file_name = '', $file_ext = '', $type_of_file = '') {
137 137
 		// load WP_Filesystem and set file permissions
138
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
139
-		$full_file_path = EEH_File::standardise_directory_separators( $full_file_path );
140
-		if ( ! $wp_filesystem->is_readable( EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) )) {
141
-			$file_name = ! empty( $type_of_file ) ? $file_name . ' ' . $type_of_file : $file_name;
142
-			$file_name .= ! empty( $file_ext ) ? ' file' : ' folder';
138
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
139
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
140
+		if ( ! $wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
141
+			$file_name = ! empty($type_of_file) ? $file_name.' '.$type_of_file : $file_name;
142
+			$file_name .= ! empty($file_ext) ? ' file' : ' folder';
143 143
 			$msg = sprintf(
144
-				__( 'The requested %1$s could not be found or is not readable, possibly due to an incorrect filepath, or incorrect file permissions.%2$s', 'event_espresso' ),
144
+				__('The requested %1$s could not be found or is not readable, possibly due to an incorrect filepath, or incorrect file permissions.%2$s', 'event_espresso'),
145 145
 				$file_name,
146 146
 				'<br />'
147 147
 			);
148
-			if ( EEH_File::exists( $full_file_path )) {
149
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_file_path, $type_of_file );
148
+			if (EEH_File::exists($full_file_path)) {
149
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, $type_of_file);
150 150
 			} else {
151 151
 				// no file permissions means the file was not found
152 152
 				$msg .= sprintf(
153
-					__( 'Please ensure the following path is correct: "%s".', 'event_espresso' ),
153
+					__('Please ensure the following path is correct: "%s".', 'event_espresso'),
154 154
 					$full_file_path
155 155
 				);
156 156
 			}
157
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
158
-				throw new EE_Error( $msg . '||' . $msg );
157
+			if (defined('WP_DEBUG') && WP_DEBUG) {
158
+				throw new EE_Error($msg.'||'.$msg);
159 159
 			}
160 160
 			return FALSE;
161 161
 		}
@@ -173,24 +173,24 @@  discard block
 block discarded – undo
173 173
 	 * @throws EE_Error if filesystem credentials are required
174 174
 	 * @return string
175 175
 	 */
176
-	private static function _permissions_error_for_unreadable_filepath( $full_file_path = '', $type_of_file = '' ){
176
+	private static function _permissions_error_for_unreadable_filepath($full_file_path = '', $type_of_file = '') {
177 177
 		// load WP_Filesystem and set file permissions
178
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
178
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
179 179
 		// check file permissions
180
-		$perms = $wp_filesystem->getchmod( EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) );
181
-		if ( $perms ) {
180
+		$perms = $wp_filesystem->getchmod(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
181
+		if ($perms) {
182 182
 			// file permissions exist, but way be set incorrectly
183
-			$type_of_file = ! empty( $type_of_file ) ? $type_of_file . ' ' : '';
184
-			$type_of_file .= ! empty( $type_of_file ) ? 'file' : 'folder';
183
+			$type_of_file = ! empty($type_of_file) ? $type_of_file.' ' : '';
184
+			$type_of_file .= ! empty($type_of_file) ? 'file' : 'folder';
185 185
 			return sprintf(
186
-				__( 'File permissions for the requested %1$s are currently set at "%2$s". The recommended permissions are 644 for files and 755 for folders.', 'event_espresso' ),
186
+				__('File permissions for the requested %1$s are currently set at "%2$s". The recommended permissions are 644 for files and 755 for folders.', 'event_espresso'),
187 187
 				$type_of_file,
188 188
 				$perms
189 189
 			);
190 190
 		} else {
191 191
 			// file exists but file permissions could not be read ?!?!
192 192
 			return sprintf(
193
-				__( 'Please ensure that the server and/or PHP configuration allows the current process to access the following file: "%s".', 'event_espresso' ),
193
+				__('Please ensure that the server and/or PHP configuration allows the current process to access the following file: "%s".', 'event_espresso'),
194 194
 				$full_file_path
195 195
 			);
196 196
 		}
@@ -208,35 +208,35 @@  discard block
 block discarded – undo
208 208
 	 * can't write to it
209 209
 	 * @return bool false if folder isn't writable; true if it exists and is writeable,
210 210
 	 */
211
-	public static function ensure_folder_exists_and_is_writable( $folder = '' ){
212
-		if ( empty( $folder )) {
211
+	public static function ensure_folder_exists_and_is_writable($folder = '') {
212
+		if (empty($folder)) {
213 213
 			return false;
214 214
 		}
215 215
 		// remove ending DS
216
-		$folder = EEH_File::standardise_directory_separators( rtrim( $folder, '/\\' ));
217
-		$parent_folder = EEH_File::get_parent_folder( $folder );
216
+		$folder = EEH_File::standardise_directory_separators(rtrim($folder, '/\\'));
217
+		$parent_folder = EEH_File::get_parent_folder($folder);
218 218
 		// add DS to folder
219
-		$folder = EEH_File::end_with_directory_separator( $folder );
220
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $folder );
221
-		if ( ! $wp_filesystem->is_dir( EEH_File::convert_local_filepath_to_remote_filepath( $folder ) ) ) {
219
+		$folder = EEH_File::end_with_directory_separator($folder);
220
+		$wp_filesystem = EEH_File::_get_wp_filesystem($folder);
221
+		if ( ! $wp_filesystem->is_dir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
222 222
 			//ok so it doesn't exist. Does its parent? Can we write to it?
223
-			if(	! EEH_File::ensure_folder_exists_and_is_writable( $parent_folder ) ) {
223
+			if ( ! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
224 224
 				return false;
225 225
 			}
226
-			if ( ! EEH_File::verify_is_writable( $parent_folder, 'folder' )) {
226
+			if ( ! EEH_File::verify_is_writable($parent_folder, 'folder')) {
227 227
 				return false;
228 228
 			} else {
229
-				if ( ! $wp_filesystem->mkdir( EEH_File::convert_local_filepath_to_remote_filepath(  $folder ) ) ) {
230
-					if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
231
-						$msg = sprintf( __( '"%s" could not be created.', 'event_espresso' ), $folder );
232
-						$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $folder );
233
-						throw new EE_Error( $msg );
229
+				if ( ! $wp_filesystem->mkdir(EEH_File::convert_local_filepath_to_remote_filepath($folder))) {
230
+					if (defined('WP_DEBUG') && WP_DEBUG) {
231
+						$msg = sprintf(__('"%s" could not be created.', 'event_espresso'), $folder);
232
+						$msg .= EEH_File::_permissions_error_for_unreadable_filepath($folder);
233
+						throw new EE_Error($msg);
234 234
 					}
235 235
 					return false;
236 236
 				}
237
-				EEH_File::add_index_file( $folder );
237
+				EEH_File::add_index_file($folder);
238 238
 			}
239
-		} elseif ( ! EEH_File::verify_is_writable( $folder, 'folder' )) {
239
+		} elseif ( ! EEH_File::verify_is_writable($folder, 'folder')) {
240 240
 			return false;
241 241
 		}
242 242
 		return true;
@@ -251,15 +251,15 @@  discard block
 block discarded – undo
251 251
 	 * @throws EE_Error if filesystem credentials are required
252 252
 	 * @return bool
253 253
 	 */
254
-	public static function verify_is_writable( $full_path = '', $file_or_folder = 'folder' ){
254
+	public static function verify_is_writable($full_path = '', $file_or_folder = 'folder') {
255 255
 		// load WP_Filesystem and set file permissions
256
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_path );
257
-		$full_path = EEH_File::standardise_directory_separators( $full_path );
258
-		if ( ! $wp_filesystem->is_writable( EEH_File::convert_local_filepath_to_remote_filepath( $full_path ) ) ) {
259
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
260
-				$msg = sprintf( __( 'The "%1$s" %2$s is not writable.', 'event_espresso' ), $full_path, $file_or_folder );
261
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_path );
262
-				throw new EE_Error( $msg );
256
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_path);
257
+		$full_path = EEH_File::standardise_directory_separators($full_path);
258
+		if ( ! $wp_filesystem->is_writable(EEH_File::convert_local_filepath_to_remote_filepath($full_path))) {
259
+			if (defined('WP_DEBUG') && WP_DEBUG) {
260
+				$msg = sprintf(__('The "%1$s" %2$s is not writable.', 'event_espresso'), $full_path, $file_or_folder);
261
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_path);
262
+				throw new EE_Error($msg);
263 263
 			}
264 264
 			return FALSE;
265 265
 		}
@@ -276,25 +276,25 @@  discard block
 block discarded – undo
276 276
 	 * @throws EE_Error if filesystem credentials are required
277 277
 	 * @return bool
278 278
 	 */
279
-	public static function ensure_file_exists_and_is_writable( $full_file_path = '' ) {
279
+	public static function ensure_file_exists_and_is_writable($full_file_path = '') {
280 280
 		// load WP_Filesystem and set file permissions
281
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
282
-		$full_file_path = EEH_File::standardise_directory_separators( $full_file_path );
283
-		$parent_folder = EEH_File::get_parent_folder( $full_file_path );
284
-		if ( ! EEH_File::exists( $full_file_path )) {
285
-			if( ! EEH_File::ensure_folder_exists_and_is_writable( $parent_folder ) ) {
281
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
282
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
283
+		$parent_folder = EEH_File::get_parent_folder($full_file_path);
284
+		if ( ! EEH_File::exists($full_file_path)) {
285
+			if ( ! EEH_File::ensure_folder_exists_and_is_writable($parent_folder)) {
286 286
 				return false;
287 287
 			}
288
-			if ( ! $wp_filesystem->touch( EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) ) ) {
289
-				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
290
-					$msg = sprintf( __( 'The "%s" file could not be created.', 'event_espresso' ), $full_file_path );
291
-					$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_file_path );
292
-					throw new EE_Error( $msg );
288
+			if ( ! $wp_filesystem->touch(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
289
+				if (defined('WP_DEBUG') && WP_DEBUG) {
290
+					$msg = sprintf(__('The "%s" file could not be created.', 'event_espresso'), $full_file_path);
291
+					$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
292
+					throw new EE_Error($msg);
293 293
 				}
294 294
 				return false;
295 295
 			}
296 296
 		}
297
-		if ( ! EEH_File::verify_is_writable( $full_file_path, 'file' )) {
297
+		if ( ! EEH_File::verify_is_writable($full_file_path, 'file')) {
298 298
 			return false;
299 299
 		}
300 300
 		return true;
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 	 * @param string $file_or_folder_path
307 307
 	 * @return string parent folder, ENDING with a directory separator
308 308
 	 */
309
-	public static function get_parent_folder( $file_or_folder_path ) {
309
+	public static function get_parent_folder($file_or_folder_path) {
310 310
 		//find the last DS, ignoring a DS on the very end
311 311
 		//eg if given "/var/something/somewhere/", we want to get "somewhere"'s
312 312
 		//parent folder, "/var/something/"
@@ -328,12 +328,12 @@  discard block
 block discarded – undo
328 328
 	 * @throws EE_Error if filesystem credentials are required
329 329
 	 * @return string
330 330
 	 */
331
-	public static function get_file_contents( $full_file_path = '' ){
332
-		$full_file_path = EEH_File::standardise_directory_separators( $full_file_path );
333
-		if ( EEH_File::verify_filepath_and_permissions( $full_file_path, EEH_File::get_filename_from_filepath( $full_file_path ) , EEH_File::get_file_extension( $full_file_path ))) {
331
+	public static function get_file_contents($full_file_path = '') {
332
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
333
+		if (EEH_File::verify_filepath_and_permissions($full_file_path, EEH_File::get_filename_from_filepath($full_file_path), EEH_File::get_file_extension($full_file_path))) {
334 334
 			// load WP_Filesystem and set file permissions
335
-			$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
336
-			return $wp_filesystem->get_contents(EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) );
335
+			$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
336
+			return $wp_filesystem->get_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path));
337 337
 		}
338 338
 		return '';
339 339
 	}
@@ -348,26 +348,26 @@  discard block
 block discarded – undo
348 348
 	 * @throws EE_Error if filesystem credentials are required
349 349
 	 * @return bool
350 350
 	 */
351
-	public static function write_to_file( $full_file_path = '', $file_contents = '', $file_type = '' ){
352
-		$full_file_path = EEH_File::standardise_directory_separators( $full_file_path );
353
-		$file_type = ! empty( $file_type ) ? rtrim( $file_type, ' ' ) . ' ' : '';
354
-		$folder = EEH_File::remove_filename_from_filepath( $full_file_path );
355
-		if ( ! EEH_File::verify_is_writable( $folder, 'folder' )) {
356
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
357
-				$msg = sprintf( __( 'The %1$sfile located at "%2$s" is not writable.', 'event_espresso' ), $file_type, $full_file_path );
358
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_file_path );
359
-				throw new EE_Error( $msg );
351
+	public static function write_to_file($full_file_path = '', $file_contents = '', $file_type = '') {
352
+		$full_file_path = EEH_File::standardise_directory_separators($full_file_path);
353
+		$file_type = ! empty($file_type) ? rtrim($file_type, ' ').' ' : '';
354
+		$folder = EEH_File::remove_filename_from_filepath($full_file_path);
355
+		if ( ! EEH_File::verify_is_writable($folder, 'folder')) {
356
+			if (defined('WP_DEBUG') && WP_DEBUG) {
357
+				$msg = sprintf(__('The %1$sfile located at "%2$s" is not writable.', 'event_espresso'), $file_type, $full_file_path);
358
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path);
359
+				throw new EE_Error($msg);
360 360
 			}
361 361
 			return FALSE;
362 362
 		}
363 363
 		// load WP_Filesystem and set file permissions
364
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
364
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
365 365
 		// write the file
366
-		if ( ! $wp_filesystem->put_contents(EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ), $file_contents )) {
367
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
368
-				$msg = sprintf( __( 'The %1$sfile located at "%2$s" could not be written to.', 'event_espresso' ), $file_type, $full_file_path );
369
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_file_path, 'f' );
370
-				throw new EE_Error( $msg );
366
+		if ( ! $wp_filesystem->put_contents(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path), $file_contents)) {
367
+			if (defined('WP_DEBUG') && WP_DEBUG) {
368
+				$msg = sprintf(__('The %1$sfile located at "%2$s" could not be written to.', 'event_espresso'), $file_type, $full_file_path);
369
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_file_path, 'f');
370
+				throw new EE_Error($msg);
371 371
 			}
372 372
 			return FALSE;
373 373
 		}
@@ -383,9 +383,9 @@  discard block
 block discarded – undo
383 383
 	 * @throws EE_Error if filesystem credentials are required
384 384
 	 * @return boolean
385 385
 	 */
386
-	public static function delete( $filepath, $recursive = false, $type = false ) {
386
+	public static function delete($filepath, $recursive = false, $type = false) {
387 387
 		$wp_filesystem = EEH_File::_get_wp_filesystem();
388
-		return $wp_filesystem->delete( $filepath, $recursive, $type ) ? TRUE : FALSE;
388
+		return $wp_filesystem->delete($filepath, $recursive, $type) ? TRUE : FALSE;
389 389
 	}
390 390
 
391 391
 
@@ -397,9 +397,9 @@  discard block
 block discarded – undo
397 397
 	 * @throws EE_Error if filesystem credentials are required
398 398
 	 * @return bool
399 399
 	 */
400
-	public static function exists( $full_file_path = '' ) {
401
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
402
-		return $wp_filesystem->exists( EEH_File::convert_local_filepath_to_remote_filepath( $full_file_path ) ) ? TRUE : FALSE;
400
+	public static function exists($full_file_path = '') {
401
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
402
+		return $wp_filesystem->exists(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path)) ? TRUE : FALSE;
403 403
 	}
404 404
 
405 405
 
@@ -412,9 +412,9 @@  discard block
 block discarded – undo
412 412
 	 * @throws EE_Error if filesystem credentials are required
413 413
 	 * @return bool
414 414
 	 */
415
-	public static function is_readable( $full_file_path = '' ) {
416
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $full_file_path );
417
-		if( $wp_filesystem->is_readable( EEH_File::convert_local_filepath_to_remote_filepath(  $full_file_path ) ) ) {
415
+	public static function is_readable($full_file_path = '') {
416
+		$wp_filesystem = EEH_File::_get_wp_filesystem($full_file_path);
417
+		if ($wp_filesystem->is_readable(EEH_File::convert_local_filepath_to_remote_filepath($full_file_path))) {
418 418
 			return true;
419 419
 		} else {
420 420
 			return false;
@@ -430,8 +430,8 @@  discard block
 block discarded – undo
430 430
 	 * @param string $full_file_path
431 431
 	 * @return string
432 432
 	 */
433
-	public static function remove_filename_from_filepath( $full_file_path = '' ) {
434
-		return pathinfo( $full_file_path, PATHINFO_DIRNAME );
433
+	public static function remove_filename_from_filepath($full_file_path = '') {
434
+		return pathinfo($full_file_path, PATHINFO_DIRNAME);
435 435
 	}
436 436
 
437 437
 
@@ -441,8 +441,8 @@  discard block
 block discarded – undo
441 441
 	 * @param string $full_file_path
442 442
 	 * @return string
443 443
 	 */
444
-	public static function get_filename_from_filepath( $full_file_path = '' ) {
445
-		return pathinfo( $full_file_path, PATHINFO_BASENAME );
444
+	public static function get_filename_from_filepath($full_file_path = '') {
445
+		return pathinfo($full_file_path, PATHINFO_BASENAME);
446 446
 	}
447 447
 
448 448
 
@@ -452,8 +452,8 @@  discard block
 block discarded – undo
452 452
 	 * @param string $full_file_path
453 453
 	 * @return string
454 454
 	 */
455
-	public static function get_file_extension( $full_file_path = '' ) {
456
-		return pathinfo( $full_file_path, PATHINFO_EXTENSION );
455
+	public static function get_file_extension($full_file_path = '') {
456
+		return pathinfo($full_file_path, PATHINFO_EXTENSION);
457 457
 	}
458 458
 
459 459
 
@@ -464,10 +464,10 @@  discard block
 block discarded – undo
464 464
 	 * @throws EE_Error if filesystem credentials are required
465 465
 	 * @return bool
466 466
 	 */
467
-	public static function add_htaccess_deny_from_all( $folder = '' ) {
468
-		$folder = EEH_File::standardise_and_end_with_directory_separator( $folder );
469
-		if ( ! EEH_File::exists( $folder . '.htaccess' ) ) {
470
-			if ( ! EEH_File::write_to_file( $folder . '.htaccess', 'deny from all', '.htaccess' )) {
467
+	public static function add_htaccess_deny_from_all($folder = '') {
468
+		$folder = EEH_File::standardise_and_end_with_directory_separator($folder);
469
+		if ( ! EEH_File::exists($folder.'.htaccess')) {
470
+			if ( ! EEH_File::write_to_file($folder.'.htaccess', 'deny from all', '.htaccess')) {
471 471
 				return FALSE;
472 472
 			}
473 473
 		}
@@ -481,10 +481,10 @@  discard block
 block discarded – undo
481 481
 	 * @throws EE_Error if filesystem credentials are required
482 482
 	 * @return boolean
483 483
 	 */
484
-	public static function add_index_file( $folder ) {
485
-		$folder = EEH_File::standardise_and_end_with_directory_separator( $folder );
486
-		if ( ! EEH_File::exists( $folder . 'index.php' ) ) {
487
-			if ( ! EEH_File::write_to_file( $folder . 'index.php', 'You are not permitted to read from this folder', '.php' )) {
484
+	public static function add_index_file($folder) {
485
+		$folder = EEH_File::standardise_and_end_with_directory_separator($folder);
486
+		if ( ! EEH_File::exists($folder.'index.php')) {
487
+			if ( ! EEH_File::write_to_file($folder.'index.php', 'You are not permitted to read from this folder', '.php')) {
488 488
 				return false;
489 489
 			}
490 490
 		}
@@ -499,11 +499,11 @@  discard block
 block discarded – undo
499 499
 	 * @param string $file_path
500 500
 	 * @return string
501 501
 	 */
502
-	public static function get_classname_from_filepath_with_standard_filename( $file_path ){
502
+	public static function get_classname_from_filepath_with_standard_filename($file_path) {
503 503
 		//extract file from path
504
-		$filename = basename( $file_path );
504
+		$filename = basename($file_path);
505 505
 		//now remove the first period and everything after
506
-		$pos_of_first_period = strpos( $filename,'.' );
506
+		$pos_of_first_period = strpos($filename, '.');
507 507
 		return substr($filename, 0, $pos_of_first_period);
508 508
 	}
509 509
 
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
 	 * @param string $file_path
516 516
 	 * @return string
517 517
 	 */
518
-	public static function standardise_directory_separators( $file_path ){
519
-		return str_replace( array( '\\', '/' ), DS, $file_path );
518
+	public static function standardise_directory_separators($file_path) {
519
+		return str_replace(array('\\', '/'), DS, $file_path);
520 520
 	}
521 521
 
522 522
 
@@ -527,8 +527,8 @@  discard block
 block discarded – undo
527 527
 	 * @param string $file_path
528 528
 	 * @return string
529 529
 	 */
530
-	public static function end_with_directory_separator( $file_path ){
531
-		return rtrim( $file_path, '/\\' ) . DS;
530
+	public static function end_with_directory_separator($file_path) {
531
+		return rtrim($file_path, '/\\').DS;
532 532
 	}
533 533
 
534 534
 
@@ -538,8 +538,8 @@  discard block
 block discarded – undo
538 538
 	 * @param $file_path
539 539
 	 * @return string
540 540
 	 */
541
-	public static function standardise_and_end_with_directory_separator( $file_path ){
542
-		return self::end_with_directory_separator( self::standardise_directory_separators( $file_path ));
541
+	public static function standardise_and_end_with_directory_separator($file_path) {
542
+		return self::end_with_directory_separator(self::standardise_directory_separators($file_path));
543 543
 	}
544 544
 
545 545
 
@@ -556,21 +556,21 @@  discard block
 block discarded – undo
556 556
 	 *		if $index_numerically == FALSE (Default) keys are what the class names SHOULD be;
557 557
 	 *		 and values are their filepaths
558 558
 	 */
559
-	public static function get_contents_of_folders( $folder_paths = array(), $index_numerically = FALSE ){
559
+	public static function get_contents_of_folders($folder_paths = array(), $index_numerically = FALSE) {
560 560
 		$class_to_folder_path = array();
561
-		foreach( $folder_paths as $folder_path ){
562
-			$folder_path = self::standardise_and_end_with_directory_separator( $folder_path );
561
+		foreach ($folder_paths as $folder_path) {
562
+			$folder_path = self::standardise_and_end_with_directory_separator($folder_path);
563 563
 			// load WP_Filesystem and set file permissions
564
-			$files_in_folder = glob( $folder_path . '*' );
564
+			$files_in_folder = glob($folder_path.'*');
565 565
 			$class_to_folder_path = array();
566
-			if ( $files_in_folder ) {
567
-				foreach( $files_in_folder as $file_path ){
566
+			if ($files_in_folder) {
567
+				foreach ($files_in_folder as $file_path) {
568 568
 					//only add files, not folders
569
-					if ( ! is_dir( $file_path )) {
570
-						if ( $index_numerically ) {
569
+					if ( ! is_dir($file_path)) {
570
+						if ($index_numerically) {
571 571
 							$class_to_folder_path[] = $file_path;
572 572
 						} else {
573
-							$classname = self::get_classname_from_filepath_with_standard_filename( $file_path );
573
+							$classname = self::get_classname_from_filepath_with_standard_filename($file_path);
574 574
 							$class_to_folder_path[$classname] = $file_path;
575 575
 						}
576 576
 					}
@@ -590,39 +590,39 @@  discard block
 block discarded – undo
590 590
 	 * @throws EE_Error if filesystem credentials are required
591 591
 	 * @return boolean success
592 592
 	 */
593
-	public static function copy( $source_file, $destination_file, $overwrite = FALSE ){
594
-		$full_source_path = EEH_File::standardise_directory_separators( $source_file );
595
-		if( ! EEH_File::exists( $full_source_path ) ){
596
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
597
-				$msg = sprintf( __( 'The file located at "%2$s" is not readable or doesn\'t exist.', 'event_espresso' ), $full_source_path );
598
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_source_path );
599
-				throw new EE_Error( $msg );
593
+	public static function copy($source_file, $destination_file, $overwrite = FALSE) {
594
+		$full_source_path = EEH_File::standardise_directory_separators($source_file);
595
+		if ( ! EEH_File::exists($full_source_path)) {
596
+			if (defined('WP_DEBUG') && WP_DEBUG) {
597
+				$msg = sprintf(__('The file located at "%2$s" is not readable or doesn\'t exist.', 'event_espresso'), $full_source_path);
598
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path);
599
+				throw new EE_Error($msg);
600 600
 			}
601 601
 			return FALSE;
602 602
 		}
603 603
 
604
-		$full_dest_path = EEH_File::standardise_directory_separators( $destination_file );
605
-		$folder = EEH_File::remove_filename_from_filepath( $full_dest_path );
606
-		if ( ! EEH_File::verify_is_writable( $folder, 'folder' )) {
607
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
608
-				$msg = sprintf( __( 'The file located at "%2$s" is not writable.', 'event_espresso' ), $full_dest_path );
609
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_dest_path );
610
-				throw new EE_Error( $msg );
604
+		$full_dest_path = EEH_File::standardise_directory_separators($destination_file);
605
+		$folder = EEH_File::remove_filename_from_filepath($full_dest_path);
606
+		if ( ! EEH_File::verify_is_writable($folder, 'folder')) {
607
+			if (defined('WP_DEBUG') && WP_DEBUG) {
608
+				$msg = sprintf(__('The file located at "%2$s" is not writable.', 'event_espresso'), $full_dest_path);
609
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_dest_path);
610
+				throw new EE_Error($msg);
611 611
 			}
612 612
 			return FALSE;
613 613
 		}
614 614
 
615 615
 		// load WP_Filesystem and set file permissions
616
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $destination_file );
616
+		$wp_filesystem = EEH_File::_get_wp_filesystem($destination_file);
617 617
 		// write the file
618 618
 		if ( ! $wp_filesystem->copy(
619
-						EEH_File::convert_local_filepath_to_remote_filepath( $full_source_path ),
620
-						EEH_File::convert_local_filepath_to_remote_filepath( $full_dest_path ),
619
+						EEH_File::convert_local_filepath_to_remote_filepath($full_source_path),
620
+						EEH_File::convert_local_filepath_to_remote_filepath($full_dest_path),
621 621
 						$overwrite )) {
622
-			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
623
-				$msg = sprintf( __( 'Attempted writing to file %1$s, but could not, probably because of permissions issues', 'event_espresso' ), $full_source_path );
624
-				$msg .= EEH_File::_permissions_error_for_unreadable_filepath( $full_source_path, 'f' );
625
-				throw new EE_Error( $msg );
622
+			if (defined('WP_DEBUG') && WP_DEBUG) {
623
+				$msg = sprintf(__('Attempted writing to file %1$s, but could not, probably because of permissions issues', 'event_espresso'), $full_source_path);
624
+				$msg .= EEH_File::_permissions_error_for_unreadable_filepath($full_source_path, 'f');
625
+				throw new EE_Error($msg);
626 626
 			}
627 627
 			return FALSE;
628 628
 		}
@@ -634,9 +634,9 @@  discard block
 block discarded – undo
634 634
 	 * @param string $filepath
635 635
 	 * @return boolean
636 636
 	 */
637
-	public static function is_in_uploads_folder( $filepath ) {
637
+	public static function is_in_uploads_folder($filepath) {
638 638
 		$uploads = wp_upload_dir();
639
-		return strpos( $filepath, $uploads[ 'basedir' ] ) === 0 ? true : false;
639
+		return strpos($filepath, $uploads['basedir']) === 0 ? true : false;
640 640
 	}
641 641
 
642 642
 	/**
@@ -651,9 +651,9 @@  discard block
 block discarded – undo
651 651
 	 * @return string the remote filepath (eg the filepath the filesystem method, eg
652 652
 	 * ftp or ssh, will use to access the folder
653 653
 	 */
654
-	public static function convert_local_filepath_to_remote_filepath( $local_filepath ) {
655
-		$wp_filesystem = EEH_File::_get_wp_filesystem( $local_filepath );
656
-		return str_replace( WP_CONTENT_DIR . DS, $wp_filesystem->wp_content_dir(), $local_filepath );
654
+	public static function convert_local_filepath_to_remote_filepath($local_filepath) {
655
+		$wp_filesystem = EEH_File::_get_wp_filesystem($local_filepath);
656
+		return str_replace(WP_CONTENT_DIR.DS, $wp_filesystem->wp_content_dir(), $local_filepath);
657 657
 	}
658 658
 }
659 659
 // End of file EEH_File.helper.php
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,4 +1,6 @@
 block discarded – undo
1
-<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3
+}
2 4
 
3 5
 /**
4 6
  *
Please login to merge, or discard this patch.