Completed
Branch EDTR/master (cc21f1)
by
unknown
25:43 queued 17:38
created

Extend_Events_Admin_Page::handleActionRequest()   B

Complexity

Conditions 10
Paths 11

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 11
nop 0
dl 0
loc 33
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
use EventEspresso\core\domain\services\admin\events\default_settings\AdvancedEditorAdminFormSection;
4
use EventEspresso\core\domain\services\admin\events\editor\AdvancedEditorEntityData;
5
use EventEspresso\core\exceptions\ExceptionStackTraceDisplay;
6
use EventEspresso\core\exceptions\InvalidDataTypeException;
7
use EventEspresso\core\exceptions\InvalidInterfaceException;
8
use EventEspresso\core\services\loaders\LoaderFactory;
9
10
/**
11
 * Extend_Events_Admin_Page
12
 * This is the Events Caffeinated admin page.
13
 *
14
 * @package         Extend_Events_Admin_Page
15
 * @subpackage      includes/core/admin/Extend_Events_Admin_Page.core.php
16
 * @author          Darren Ethier
17
 */
18
class Extend_Events_Admin_Page extends Events_Admin_Page
19
{
20
21
    /**
22
     * @var AdvancedEditorAdminFormSection
23
     */
24
    protected $advanced_editor_admin_form;
25
26
    /**
27
     * @var AdvancedEditorEntityData
28
     */
29
    protected $advanced_editor_data;
30
31
32
    /**
33
     * Extend_Events_Admin_Page constructor.
34
     *
35
     * @param bool $routing
36
     * @throws EE_Error
37
     * @throws InvalidArgumentException
38
     * @throws InvalidDataTypeException
39
     * @throws InvalidInterfaceException
40
     * @throws ReflectionException
41
     */
42 View Code Duplication
    public function __construct($routing = true)
43
    {
44
        if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
45
            define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
46
            define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
47
            define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
48
        }
49
        parent::__construct($routing);
50
    }
51
52
53
    /**
54
     * Sets routes.
55
     *
56
     * @throws EE_Error
57
     * @throws InvalidArgumentException
58
     * @throws InvalidDataTypeException
59
     * @throws InvalidInterfaceException
60
     * @throws Exception
61
     */
62
    protected function _extend_page_config()
63
    {
64
        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
65
        // is there a evt_id in the request?
66
        $evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
67
            ? $this->_req_data['EVT_ID']
68
            : 0;
69
        $evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
70
        // tkt_id?
71
        $tkt_id = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
72
            ? $this->_req_data['TKT_ID']
73
            : 0;
74
        $new_page_routes = array(
75
            'duplicate_event'          => array(
76
                'func'       => '_duplicate_event',
77
                'capability' => 'ee_edit_event',
78
                'obj_id'     => $evt_id,
79
                'noheader'   => true,
80
            ),
81
            'ticket_list_table'        => array(
82
                'func'       => '_tickets_overview_list_table',
83
                'capability' => 'ee_read_default_tickets',
84
            ),
85
            'trash_ticket'             => array(
86
                'func'       => '_trash_or_restore_ticket',
87
                'capability' => 'ee_delete_default_ticket',
88
                'obj_id'     => $tkt_id,
89
                'noheader'   => true,
90
                'args'       => array('trash' => true),
91
            ),
92
            'trash_tickets'            => array(
93
                'func'       => '_trash_or_restore_ticket',
94
                'capability' => 'ee_delete_default_tickets',
95
                'noheader'   => true,
96
                'args'       => array('trash' => true),
97
            ),
98
            'restore_ticket'           => array(
99
                'func'       => '_trash_or_restore_ticket',
100
                'capability' => 'ee_delete_default_ticket',
101
                'obj_id'     => $tkt_id,
102
                'noheader'   => true,
103
            ),
104
            'restore_tickets'          => array(
105
                'func'       => '_trash_or_restore_ticket',
106
                'capability' => 'ee_delete_default_tickets',
107
                'noheader'   => true,
108
            ),
109
            'delete_ticket'            => array(
110
                'func'       => '_delete_ticket',
111
                'capability' => 'ee_delete_default_ticket',
112
                'obj_id'     => $tkt_id,
113
                'noheader'   => true,
114
            ),
115
            'delete_tickets'           => array(
116
                'func'       => '_delete_ticket',
117
                'capability' => 'ee_delete_default_tickets',
118
                'noheader'   => true,
119
            ),
120
            'import_page'              => array(
121
                'func'       => '_import_page',
122
                'capability' => 'import',
123
            ),
124
            'import'                   => array(
125
                'func'       => '_import_events',
126
                'capability' => 'import',
127
                'noheader'   => true,
128
            ),
129
            'import_events'            => array(
130
                'func'       => '_import_events',
131
                'capability' => 'import',
132
                'noheader'   => true,
133
            ),
134
            'export_events'            => array(
135
                'func'       => '_events_export',
136
                'capability' => 'export',
137
                'noheader'   => true,
138
            ),
139
            'export_categories'        => array(
140
                'func'       => '_categories_export',
141
                'capability' => 'export',
142
                'noheader'   => true,
143
            ),
144
            'sample_export_file'       => array(
145
                'func'       => '_sample_export_file',
146
                'capability' => 'export',
147
                'noheader'   => true,
148
            ),
149
            'update_template_settings' => array(
150
                'func'       => '_update_template_settings',
151
                'capability' => 'manage_options',
152
                'noheader'   => true,
153
            ),
154
        );
155
        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
156
        // partial route/config override
157
        $this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
158
        $this->_page_config['create_new']['metaboxes'][] = '_premium_event_editor_meta_boxes';
159
        $this->_page_config['create_new']['qtips'][] = 'EE_Event_Editor_Tips';
160
        $this->_page_config['edit']['qtips'][] = 'EE_Event_Editor_Tips';
161
        $this->_page_config['edit']['metaboxes'][] = '_premium_event_editor_meta_boxes';
162
        $this->_page_config['default']['list_table'] = 'Extend_Events_Admin_List_Table';
163
        // add tickets tab but only if there are more than one default ticket!
164
        $tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
165
            array(array('TKT_is_default' => 1)),
166
            'TKT_ID',
167
            true
168
        );
169
        if ($tkt_count > 1) {
170
            $new_page_config = array(
171
                'ticket_list_table' => array(
172
                    'nav'           => array(
173
                        'label' => esc_html__('Default Tickets', 'event_espresso'),
174
                        'order' => 60,
175
                    ),
176
                    'list_table'    => 'Tickets_List_Table',
177
                    'require_nonce' => false,
178
                ),
179
            );
180
        }
181
        // template settings
182
        $new_page_config['template_settings'] = array(
183
            'nav'           => array(
184
                'label' => esc_html__('Templates', 'event_espresso'),
185
                'order' => 30,
186
            ),
187
            'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
188
            'help_tabs'     => array(
189
                'general_settings_templates_help_tab' => array(
190
                    'title'    => esc_html__('Templates', 'event_espresso'),
191
                    'filename' => 'general_settings_templates',
192
                ),
193
            ),
194
            'help_tour'     => array('Templates_Help_Tour'),
195
            'require_nonce' => false,
196
        );
197
        $this->_page_config = array_merge($this->_page_config, $new_page_config);
198
        // add filters and actions
199
        // modifying _views
200
        add_filter(
201
            'FHEE_event_datetime_metabox_add_additional_date_time_template',
202
            array($this, 'add_additional_datetime_button'),
203
            10,
204
            2
205
        );
206
        add_filter(
207
            'FHEE_event_datetime_metabox_clone_button_template',
208
            array($this, 'add_datetime_clone_button'),
209
            10,
210
            2
211
        );
212
        add_filter(
213
            'FHEE_event_datetime_metabox_timezones_template',
214
            array($this, 'datetime_timezones_template'),
215
            10,
216
            2
217
        );
218
        // filters for event list table
219
        add_filter('FHEE__Extend_Events_Admin_List_Table__filters', array($this, 'list_table_filters'), 10, 2);
220
        add_filter(
221
            'FHEE__Events_Admin_List_Table__column_actions__action_links',
222
            array($this, 'extra_list_table_actions'),
223
            10,
224
            2
225
        );
226
        // legend item
227
        add_filter('FHEE__Events_Admin_Page___event_legend_items__items', array($this, 'additional_legend_items'));
228
        add_action('admin_init', array($this, 'admin_init'));
229
       // load additional handlers
230
        $this->handleActionRequest();
231
    }
232
233
234
    private function getRequestAction()
235
    {
236
        return isset($this->_req_data['action']) ? sanitize_key($this->_req_data['action']) : null;
237
    }
238
239
240
    /**
241
     * @throws EE_Error
242
     * @throws InvalidArgumentException
243
     * @throws InvalidDataTypeException
244
     * @throws InvalidInterfaceException
245
     * @throws Exception
246
     */
247
    private function handleActionRequest()
248
    {
249
        $action = $this->getRequestAction();
250
        if ($action) {
251
            // setup Advanced Editor ???
252
            if ($action === 'default_event_settings' || $action === 'update_default_event_settings') {
253
                $this->advanced_editor_admin_form = $this->loader->getShared(
254
                    'EventEspresso\core\domain\services\admin\events\default_settings\AdvancedEditorAdminFormSection'
255
                );
256
            }
257
            $admin_config = $this->loader->getShared('EE_Admin_Config');
258
            // load handler for GraphQL requests and AdvancedEditorEntityData
259
            if (($action === 'edit' || $action === 'create_new')
260
                && $admin_config instanceof EE_Admin_Config
261
                && class_exists('WPGraphQL')
262
                && $admin_config->useAdvancedEditor()
263
            ) {
264
                try {
265
                    /** @var EventEspresso\core\services\graphql\GraphQLManager $graphQL_manager */
266
                    $graphQL_manager = $this->loader->getShared(
267
                        'EventEspresso\core\services\graphql\GraphQLManager'
268
                    );
269
                    $graphQL_manager->init();
270
                    $this->advanced_editor_data = $this->loader->getShared(
271
                        'EventEspresso\core\domain\services\admin\events\editor\AdvancedEditorEntityData',
272
                        [$this->_cpt_model_obj]
273
                    );
274
                } catch (Exception $exception) {
275
                    new ExceptionStackTraceDisplay($exception);
276
                }
277
            }
278
        }
279
    }
280
281
282
    /**
283
     * admin_init
284
     */
285
    public function admin_init()
286
    {
287
        EE_Registry::$i18n_js_strings = array_merge(
288
            EE_Registry::$i18n_js_strings,
289
            array(
290
                'image_confirm'          => esc_html__(
291
                    'Do you really want to delete this image? Please remember to update your event to complete the removal.',
292
                    'event_espresso'
293
                ),
294
                'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
295
                'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
296
                'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
297
                'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
298
                'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
299
            )
300
        );
301
    }
302
303
304
    /**
305
     * Add per page screen options to the default ticket list table view.
306
     *
307
     * @throws InvalidArgumentException
308
     * @throws InvalidDataTypeException
309
     * @throws InvalidInterfaceException
310
     */
311
    protected function _add_screen_options_ticket_list_table()
312
    {
313
        $this->_per_page_screen_option();
314
    }
315
316
317
    /**
318
     * @param string $return
319
     * @param int    $id
320
     * @param string $new_title
321
     * @param string $new_slug
322
     * @return string
323
     */
324
    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
325
    {
326
        $return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
327
        // make sure this is only when editing
328
        if (! empty($id)) {
329
            $href = EE_Admin_Page::add_query_args_and_nonce(
330
                array('action' => 'duplicate_event', 'EVT_ID' => $id),
331
                $this->_admin_base_url
332
            );
333
            $title = esc_attr__('Duplicate Event', 'event_espresso');
334
            $return .= '<a href="'
335
                       . $href
336
                       . '" title="'
337
                       . $title
338
                       . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
339
                       . $title
340
                       . '</a>';
341
        }
342
        return $return;
343
    }
344
345
346
    /**
347
     * Set the list table views for the default ticket list table view.
348
     */
349 View Code Duplication
    public function _set_list_table_views_ticket_list_table()
350
    {
351
        $this->_views = array(
352
            'all'     => array(
353
                'slug'        => 'all',
354
                'label'       => esc_html__('All', 'event_espresso'),
355
                'count'       => 0,
356
                'bulk_action' => array(
357
                    'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
358
                ),
359
            ),
360
            'trashed' => array(
361
                'slug'        => 'trashed',
362
                'label'       => esc_html__('Trash', 'event_espresso'),
363
                'count'       => 0,
364
                'bulk_action' => array(
365
                    'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
366
                    'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
367
                ),
368
            ),
369
        );
370
    }
371
372
373
    /**
374
     * Enqueue scripts and styles for the event editor.
375
     */
376 View Code Duplication
    public function load_scripts_styles_edit()
377
    {
378
        wp_register_script(
379
            'ee-event-editor-heartbeat',
380
            EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
381
            array('ee_admin_js', 'heartbeat'),
382
            EVENT_ESPRESSO_VERSION,
383
            true
384
        );
385
        wp_enqueue_script('ee-accounting');
386
        // styles
387
        wp_enqueue_style('espresso-ui-theme');
388
        wp_enqueue_script('event_editor_js');
389
        wp_enqueue_script('ee-event-editor-heartbeat');
390
    }
391
392
393
    /**
394
     * Returns template for the additional datetime.
395
     *
396
     * @param $template
397
     * @param $template_args
398
     * @return mixed
399
     * @throws DomainException
400
     */
401
    public function add_additional_datetime_button($template, $template_args)
402
    {
403
        return EEH_Template::display_template(
404
            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
405
            $template_args,
406
            true
407
        );
408
    }
409
410
411
    /**
412
     * Returns the template for cloning a datetime.
413
     *
414
     * @param $template
415
     * @param $template_args
416
     * @return mixed
417
     * @throws DomainException
418
     */
419
    public function add_datetime_clone_button($template, $template_args)
420
    {
421
        return EEH_Template::display_template(
422
            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
423
            $template_args,
424
            true
425
        );
426
    }
427
428
429
    /**
430
     * Returns the template for datetime timezones.
431
     *
432
     * @param $template
433
     * @param $template_args
434
     * @return mixed
435
     * @throws DomainException
436
     */
437
    public function datetime_timezones_template($template, $template_args)
438
    {
439
        return EEH_Template::display_template(
440
            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
441
            $template_args,
442
            true
443
        );
444
    }
445
446
447
    /**
448
     * Sets the views for the default list table view.
449
     */
450
    protected function _set_list_table_views_default()
451
    {
452
        parent::_set_list_table_views_default();
453
        $new_views = array(
454
            'today' => array(
455
                'slug'        => 'today',
456
                'label'       => esc_html__('Today', 'event_espresso'),
457
                'count'       => $this->total_events_today(),
458
                'bulk_action' => array(
459
                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
460
                ),
461
            ),
462
            'month' => array(
463
                'slug'        => 'month',
464
                'label'       => esc_html__('This Month', 'event_espresso'),
465
                'count'       => $this->total_events_this_month(),
466
                'bulk_action' => array(
467
                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
468
                ),
469
            ),
470
        );
471
        $this->_views = array_merge($this->_views, $new_views);
472
    }
473
474
475
    /**
476
     * Returns the extra action links for the default list table view.
477
     *
478
     * @param array    $action_links
479
     * @param EE_Event $event
480
     * @return array
481
     * @throws EE_Error
482
     * @throws InvalidArgumentException
483
     * @throws InvalidDataTypeException
484
     * @throws InvalidInterfaceException
485
     * @throws ReflectionException
486
     */
487
    public function extra_list_table_actions(array $action_links, EE_Event $event)
488
    {
489
        if (EE_Registry::instance()->CAP->current_user_can(
490
            'ee_read_registrations',
491
            'espresso_registrations_reports',
492
            $event->ID()
493
        )
494
        ) {
495
            $reports_query_args = array(
496
                'action' => 'reports',
497
                'EVT_ID' => $event->ID(),
498
            );
499
            $reports_link = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
500
            $action_links[] = '<a href="'
501
                              . $reports_link
502
                              . '" title="'
503
                              . esc_attr__('View Report', 'event_espresso')
504
                              . '"><div class="dashicons dashicons-chart-bar"></div></a>'
505
                              . "\n\t";
506
        }
507
        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
508
            EE_Registry::instance()->load_helper('MSG_Template');
509
            $action_links[] = EEH_MSG_Template::get_message_action_link(
510
                'see_notifications_for',
511
                null,
512
                array('EVT_ID' => $event->ID())
513
            );
514
        }
515
        return $action_links;
516
    }
517
518
519
    /**
520
     * @param $items
521
     * @return mixed
522
     */
523
    public function additional_legend_items($items)
524
    {
525
        if (EE_Registry::instance()->CAP->current_user_can(
526
            'ee_read_registrations',
527
            'espresso_registrations_reports'
528
        )
529
        ) {
530
            $items['reports'] = array(
531
                'class' => 'dashicons dashicons-chart-bar',
532
                'desc'  => esc_html__('Event Reports', 'event_espresso'),
533
            );
534
        }
535 View Code Duplication
        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
536
            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
537
            // $related_for_icon can sometimes be a string so 'css_class' would be an illegal offset
538
            // (can only use numeric offsets when treating strings as arrays)
539
            if (is_array($related_for_icon) && isset($related_for_icon['css_class'], $related_for_icon['label'])) {
540
                $items['view_related_messages'] = array(
541
                    'class' => $related_for_icon['css_class'],
542
                    'desc'  => $related_for_icon['label'],
543
                );
544
            }
545
        }
546
        return $items;
547
    }
548
549
550
    /**
551
     * This is the callback method for the duplicate event route
552
     * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
553
     * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
554
     * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
555
     * After duplication the redirect is to the new event edit page.
556
     *
557
     * @return void
558
     * @throws EE_Error If EE_Event is not available with given ID
559
     * @throws InvalidArgumentException
560
     * @throws InvalidDataTypeException
561
     * @throws InvalidInterfaceException
562
     * @throws ReflectionException
563
     * @access protected
564
     */
565
    protected function _duplicate_event()
566
    {
567
        // first make sure the ID for the event is in the request.
568
        //  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
569 View Code Duplication
        if (! isset($this->_req_data['EVT_ID'])) {
570
            EE_Error::add_error(
571
                esc_html__(
572
                    'In order to duplicate an event an Event ID is required.  None was given.',
573
                    'event_espresso'
574
                ),
575
                __FILE__,
576
                __FUNCTION__,
577
                __LINE__
578
            );
579
            $this->_redirect_after_action(false, '', '', array(), true);
580
            return;
581
        }
582
        // k we've got EVT_ID so let's use that to get the event we'll duplicate
583
        $orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
584
        if (! $orig_event instanceof EE_Event) {
585
            throw new EE_Error(
586
                sprintf(
587
                    esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
588
                    $this->_req_data['EVT_ID']
589
                )
590
            );
591
        }
592
        // k now let's clone the $orig_event before getting relations
593
        $new_event = clone $orig_event;
594
        // original datetimes
595
        $orig_datetimes = $orig_event->get_many_related('Datetime');
596
        // other original relations
597
        $orig_ven = $orig_event->get_many_related('Venue');
598
        // reset the ID and modify other details to make it clear this is a dupe
599
        $new_event->set('EVT_ID', 0);
600
        $new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
601
        $new_event->set('EVT_name', $new_name);
602
        $new_event->set(
603
            'EVT_slug',
604
            wp_unique_post_slug(
605
                sanitize_title($orig_event->name()),
606
                0,
607
                'publish',
608
                'espresso_events',
609
                0
610
            )
611
        );
612
        $new_event->set('status', 'draft');
613
        // duplicate discussion settings
614
        $new_event->set('comment_status', $orig_event->get('comment_status'));
615
        $new_event->set('ping_status', $orig_event->get('ping_status'));
616
        // save the new event
617
        $new_event->save();
618
        // venues
619
        foreach ($orig_ven as $ven) {
620
            $new_event->_add_relation_to($ven, 'Venue');
621
        }
622
        $new_event->save();
623
        // now we need to get the question group relations and handle that
624
        // first primary question groups
625
        $orig_primary_qgs = $orig_event->get_many_related(
626
            'Question_Group',
627
            [['Event_Question_Group.EQG_primary' => true]]
628
        );
629 View Code Duplication
        if (! empty($orig_primary_qgs)) {
630
            foreach ($orig_primary_qgs as $id => $obj) {
631
                if ($obj instanceof EE_Question_Group) {
632
                    $new_event->_add_relation_to($obj, 'Question_Group', ['EQG_primary' => true]);
633
                }
634
            }
635
        }
636
        // next additional attendee question groups
637
        $orig_additional_qgs = $orig_event->get_many_related(
638
            'Question_Group',
639
            [['Event_Question_Group.EQG_additional' => true]]
640
        );
641 View Code Duplication
        if (! empty($orig_additional_qgs)) {
642
            foreach ($orig_additional_qgs as $id => $obj) {
643
                if ($obj instanceof EE_Question_Group) {
644
                    $new_event->_add_relation_to($obj, 'Question_Group', ['EQG_additional' => true]);
645
                }
646
            }
647
        }
648
649
        $new_event->save();
650
651
        // k now that we have the new event saved we can loop through the datetimes and start adding relations.
652
        $cloned_tickets = array();
653
        foreach ($orig_datetimes as $orig_dtt) {
654
            if (! $orig_dtt instanceof EE_Datetime) {
655
                continue;
656
            }
657
            $new_dtt = clone $orig_dtt;
658
            $orig_tkts = $orig_dtt->tickets();
659
            // save new dtt then add to event
660
            $new_dtt->set('DTT_ID', 0);
661
            $new_dtt->set('DTT_sold', 0);
662
            $new_dtt->set_reserved(0);
663
            $new_dtt->save();
664
            $new_event->_add_relation_to($new_dtt, 'Datetime');
665
            $new_event->save();
666
            // now let's get the ticket relations setup.
667
            foreach ((array) $orig_tkts as $orig_tkt) {
668
                // it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
669
                if (! $orig_tkt instanceof EE_Ticket) {
670
                    continue;
671
                }
672
                // is this ticket archived?  If it is then let's skip
673
                if ($orig_tkt->get('TKT_deleted')) {
674
                    continue;
675
                }
676
                // does this original ticket already exist in the clone_tickets cache?
677
                //  If so we'll just use the new ticket from it.
678
                if (isset($cloned_tickets[ $orig_tkt->ID() ])) {
679
                    $new_tkt = $cloned_tickets[ $orig_tkt->ID() ];
680
                } else {
681
                    $new_tkt = clone $orig_tkt;
682
                    // get relations on the $orig_tkt that we need to setup.
683
                    $orig_prices = $orig_tkt->prices();
684
                    $new_tkt->set('TKT_ID', 0);
685
                    $new_tkt->set('TKT_sold', 0);
686
                    $new_tkt->set('TKT_reserved', 0);
687
                    $new_tkt->save(); // make sure new ticket has ID.
688
                    // price relations on new ticket need to be setup.
689
                    foreach ($orig_prices as $orig_price) {
690
                        $new_price = clone $orig_price;
691
                        $new_price->set('PRC_ID', 0);
692
                        $new_price->save();
693
                        $new_tkt->_add_relation_to($new_price, 'Price');
694
                        $new_tkt->save();
695
                    }
696
697
                    do_action(
698
                        'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
699
                        $orig_tkt,
700
                        $new_tkt,
701
                        $orig_prices,
702
                        $orig_event,
703
                        $orig_dtt,
704
                        $new_dtt
705
                    );
706
                }
707
                // k now we can add the new ticket as a relation to the new datetime
708
                // and make sure its added to our cached $cloned_tickets array
709
                // for use with later datetimes that have the same ticket.
710
                $new_dtt->_add_relation_to($new_tkt, 'Ticket');
711
                $new_dtt->save();
712
                $cloned_tickets[ $orig_tkt->ID() ] = $new_tkt;
713
            }
714
        }
715
        // clone taxonomy information
716
        $taxonomies_to_clone_with = apply_filters(
717
            'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
718
            array('espresso_event_categories', 'espresso_event_type', 'post_tag')
719
        );
720
        // get terms for original event (notice)
721
        $orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
722
        // loop through terms and add them to new event.
723
        foreach ($orig_terms as $term) {
724
            wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
725
        }
726
727
        // duplicate other core WP_Post items for this event.
728
        // post thumbnail (feature image).
729
        $feature_image_id = get_post_thumbnail_id($orig_event->ID());
730
        if ($feature_image_id) {
731
            update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
732
        }
733
734
        // duplicate page_template setting
735
        $page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
736
        if ($page_template) {
737
            update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
738
        }
739
740
        do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
741
        // now let's redirect to the edit page for this duplicated event if we have a new event id.
742
        if ($new_event->ID()) {
743
            $redirect_args = array(
744
                'post'   => $new_event->ID(),
745
                'action' => 'edit',
746
            );
747
            EE_Error::add_success(
748
                esc_html__(
749
                    'Event successfully duplicated.  Please review the details below and make any necessary edits',
750
                    'event_espresso'
751
                )
752
            );
753
        } else {
754
            $redirect_args = array(
755
                'action' => 'default',
756
            );
757
            EE_Error::add_error(
758
                esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
759
                __FILE__,
760
                __FUNCTION__,
761
                __LINE__
762
            );
763
        }
764
        $this->_redirect_after_action(false, '', '', $redirect_args, true);
765
    }
766
767
768
    /**
769
     * Generates output for the import page.
770
     *
771
     * @throws DomainException
772
     * @throws EE_Error
773
     * @throws InvalidArgumentException
774
     * @throws InvalidDataTypeException
775
     * @throws InvalidInterfaceException
776
     */
777
    protected function _import_page()
778
    {
779
        $title = esc_html__('Import', 'event_espresso');
780
        $intro = esc_html__(
781
            'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
782
            'event_espresso'
783
        );
784
        $form_url = EVENTS_ADMIN_URL;
785
        $action = 'import_events';
786
        $type = 'csv';
787
        $this->_template_args['form'] = EE_Import::instance()->upload_form(
788
            $title,
789
            $intro,
790
            $form_url,
791
            $action,
792
            $type
793
        );
794
        $this->_template_args['sample_file_link'] = EE_Admin_Page::add_query_args_and_nonce(
795
            array('action' => 'sample_export_file'),
796
            $this->_admin_base_url
797
        );
798
        $content = EEH_Template::display_template(
799
            EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
800
            $this->_template_args,
801
            true
802
        );
803
        $this->_template_args['admin_page_content'] = $content;
804
        $this->display_admin_page_with_sidebar();
805
    }
806
807
808
    /**
809
     * _import_events
810
     * This handles displaying the screen and running imports for importing events.
811
     *
812
     * @return void
813
     * @throws EE_Error
814
     * @throws InvalidArgumentException
815
     * @throws InvalidDataTypeException
816
     * @throws InvalidInterfaceException
817
     */
818
    protected function _import_events()
819
    {
820
        require_once(EE_CLASSES . 'EE_Import.class.php');
821
        $success = EE_Import::instance()->import();
822
        $this->_redirect_after_action($success, 'Import File', 'ran', array('action' => 'import_page'), true);
823
    }
824
825
826
    /**
827
     * _events_export
828
     * Will export all (or just the given event) to a Excel compatible file.
829
     *
830
     * @access protected
831
     * @return void
832
     */
833
    protected function _events_export()
834
    {
835
        if (isset($this->_req_data['EVT_ID'])) {
836
            $event_ids = $this->_req_data['EVT_ID'];
837
        } elseif (isset($this->_req_data['EVT_IDs'])) {
838
            $event_ids = $this->_req_data['EVT_IDs'];
839
        } else {
840
            $event_ids = null;
841
        }
842
        // todo: I don't like doing this but it'll do until we modify EE_Export Class.
843
        $new_request_args = array(
844
            'export' => 'report',
845
            'action' => 'all_event_data',
846
            'EVT_ID' => $event_ids,
847
        );
848
        $this->_req_data = array_merge($this->_req_data, $new_request_args);
849
        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
850
            require_once(EE_CLASSES . 'EE_Export.class.php');
851
            $EE_Export = EE_Export::instance($this->_req_data);
852
            $EE_Export->export();
853
        }
854
    }
855
856
857
    /**
858
     * handle category exports()
859
     *
860
     * @return void
861
     */
862 View Code Duplication
    protected function _categories_export()
863
    {
864
        // todo: I don't like doing this but it'll do until we modify EE_Export Class.
865
        $new_request_args = array(
866
            'export'       => 'report',
867
            'action'       => 'categories',
868
            'category_ids' => $this->_req_data['EVT_CAT_ID'],
869
        );
870
        $this->_req_data = array_merge($this->_req_data, $new_request_args);
871
        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
872
            require_once(EE_CLASSES . 'EE_Export.class.php');
873
            $EE_Export = EE_Export::instance($this->_req_data);
874
            $EE_Export->export();
875
        }
876
    }
877
878
879
    /**
880
     * Creates a sample CSV file for importing
881
     */
882
    protected function _sample_export_file()
883
    {
884
        // require_once(EE_CLASSES . 'EE_Export.class.php');
885
        EE_Export::instance()->export_sample();
886
    }
887
888
889
    /*************        Template Settings        *************/
890
    /**
891
     * Generates template settings page output
892
     *
893
     * @throws DomainException
894
     * @throws EE_Error
895
     * @throws InvalidArgumentException
896
     * @throws InvalidDataTypeException
897
     * @throws InvalidInterfaceException
898
     */
899
    protected function _template_settings()
900
    {
901
        $this->_template_args['values'] = $this->_yes_no_values;
902
        /**
903
         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
904
         * from General_Settings_Admin_Page to here.
905
         */
906
        $this->_template_args = apply_filters(
907
            'FHEE__General_Settings_Admin_Page__template_settings__template_args',
908
            $this->_template_args
909
        );
910
        $this->_set_add_edit_form_tags('update_template_settings');
911
        $this->_set_publish_post_box_vars(null, false, false, null, false);
912
        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
913
            EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
914
            $this->_template_args,
915
            true
916
        );
917
        $this->display_admin_page_with_sidebar();
918
    }
919
920
921
    /**
922
     * Handler for updating template settings.
923
     *
924
     * @throws EE_Error
925
     * @throws InvalidArgumentException
926
     * @throws InvalidDataTypeException
927
     * @throws InvalidInterfaceException
928
     */
929
    protected function _update_template_settings()
930
    {
931
        /**
932
         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
933
         * from General_Settings_Admin_Page to here.
934
         */
935
        EE_Registry::instance()->CFG->template_settings = apply_filters(
936
            'FHEE__General_Settings_Admin_Page__update_template_settings__data',
937
            EE_Registry::instance()->CFG->template_settings,
938
            $this->_req_data
939
        );
940
        // update custom post type slugs and detect if we need to flush rewrite rules
941
        $old_slug = EE_Registry::instance()->CFG->core->event_cpt_slug;
942
        EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
943
            ? EE_Registry::instance()->CFG->core->event_cpt_slug
944
            : EEH_URL::slugify($this->_req_data['event_cpt_slug'], 'events');
945
        $what = 'Template Settings';
946
        $success = $this->_update_espresso_configuration(
947
            $what,
948
            EE_Registry::instance()->CFG->template_settings,
949
            __FILE__,
950
            __FUNCTION__,
951
            __LINE__
952
        );
953
        if (EE_Registry::instance()->CFG->core->event_cpt_slug !== $old_slug) {
954
            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
955
            $rewrite_rules = LoaderFactory::getLoader()->getShared(
956
                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
957
            );
958
            $rewrite_rules->flush();
959
        }
960
        $this->_redirect_after_action($success, $what, 'updated', array('action' => 'template_settings'));
961
    }
962
963
964
    /**
965
     * _premium_event_editor_meta_boxes
966
     * add all metaboxes related to the event_editor
967
     *
968
     * @access protected
969
     * @return void
970
     * @throws EE_Error
971
     * @throws InvalidArgumentException
972
     * @throws InvalidDataTypeException
973
     * @throws InvalidInterfaceException
974
     * @throws ReflectionException
975
     */
976 View Code Duplication
    protected function _premium_event_editor_meta_boxes()
977
    {
978
        $this->verify_cpt_object();
979
        add_meta_box(
980
            'espresso_event_editor_event_options',
981
            esc_html__('Event Registration Options', 'event_espresso'),
982
            array($this, 'registration_options_meta_box'),
983
            $this->page_slug,
984
            'side',
985
            'core'
986
        );
987
    }
988
989
990
    /**
991
     * override caf metabox
992
     *
993
     * @return void
994
     * @throws DomainException
995
     * @throws EE_Error
996
     */
997
    public function registration_options_meta_box()
998
    {
999
        $yes_no_values = array(
1000
            array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
1001
            array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
1002
        );
1003
        $default_reg_status_values = EEM_Registration::reg_status_array(
1004
            array(
1005
                EEM_Registration::status_id_cancelled,
1006
                EEM_Registration::status_id_declined,
1007
                EEM_Registration::status_id_incomplete,
1008
                EEM_Registration::status_id_wait_list,
1009
            ),
1010
            true
1011
        );
1012
        $template_args['active_status'] = $this->_cpt_model_obj->pretty_active_status(false);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$template_args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $template_args = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
1013
        $template_args['_event'] = $this->_cpt_model_obj;
1014
        $template_args['additional_limit'] = $this->_cpt_model_obj->additional_limit();
1015
        $template_args['default_registration_status'] = EEH_Form_Fields::select_input(
1016
            'default_reg_status',
1017
            $default_reg_status_values,
1018
            $this->_cpt_model_obj->default_registration_status()
0 ignored issues
show
Bug introduced by
It seems like $this->_cpt_model_obj->d...t_registration_status() targeting EE_Event::default_registration_status() can also be of type boolean; however, EEH_Form_Fields::select_input() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
1019
        );
1020
        $template_args['display_description'] = EEH_Form_Fields::select_input(
1021
            'display_desc',
1022
            $yes_no_values,
1023
            $this->_cpt_model_obj->display_description()
1024
        );
1025
        $template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
1026
            'display_ticket_selector',
1027
            $yes_no_values,
1028
            $this->_cpt_model_obj->display_ticket_selector(),
1029
            '',
1030
            '',
1031
            false
1032
        );
1033
        $template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
1034
            'EVT_default_registration_status',
1035
            $default_reg_status_values,
1036
            $this->_cpt_model_obj->default_registration_status()
0 ignored issues
show
Bug introduced by
It seems like $this->_cpt_model_obj->d...t_registration_status() targeting EE_Event::default_registration_status() can also be of type boolean; however, EEH_Form_Fields::select_input() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

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

An additional type check may prevent trouble.

Loading history...
1037
        );
1038
        $template_args['additional_registration_options'] = apply_filters(
1039
            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
1040
            '',
1041
            $template_args,
1042
            $yes_no_values,
1043
            $default_reg_status_values
1044
        );
1045
        EEH_Template::display_template(
1046
            EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
1047
            $template_args
1048
        );
1049
    }
1050
1051
1052
1053
    /**
1054
     * wp_list_table_mods for caf
1055
     * ============================
1056
     */
1057
    /**
1058
     * hook into list table filters and provide filters for caffeinated list table
1059
     *
1060
     * @param array $old_filters    any existing filters present
1061
     * @param array $list_table_obj the list table object
1062
     * @return array                  new filters
1063
     * @throws EE_Error
1064
     * @throws InvalidArgumentException
1065
     * @throws InvalidDataTypeException
1066
     * @throws InvalidInterfaceException
1067
     * @throws ReflectionException
1068
     */
1069
    public function list_table_filters($old_filters, $list_table_obj)
1070
    {
1071
        $filters = array();
1072
        // first month/year filters
1073
        $filters[] = $this->espresso_event_months_dropdown();
1074
        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1075
        // active status dropdown
1076
        if ($status !== 'draft') {
1077
            $filters[] = $this->active_status_dropdown(
1078
                isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
1079
            );
1080
            $filters[] = $this->venuesDropdown(
1081
                isset($this->_req_data['venue']) ? $this->_req_data['venue'] : ''
1082
            );
1083
        }
1084
        // category filter
1085
        $filters[] = $this->category_dropdown();
1086
        return array_merge($old_filters, $filters);
1087
    }
1088
1089
1090
    /**
1091
     * espresso_event_months_dropdown
1092
     *
1093
     * @access public
1094
     * @return string                dropdown listing month/year selections for events.
1095
     */
1096
    public function espresso_event_months_dropdown()
1097
    {
1098
        // what we need to do is get all PRIMARY datetimes for all events to filter on.
1099
        // Note we need to include any other filters that are set!
1100
        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1101
        // categories?
1102
        $category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1103
            ? $this->_req_data['EVT_CAT']
1104
            : null;
1105
        // active status?
1106
        $active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
1107
        $cur_date = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1108
        return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1109
    }
1110
1111
1112
    /**
1113
     * returns a list of "active" statuses on the event
1114
     *
1115
     * @param  string $current_value whatever the current active status is
1116
     * @return string
1117
     */
1118
    public function active_status_dropdown($current_value = '')
1119
    {
1120
        $select_name = 'active_status';
1121
        $values = array(
1122
            'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1123
            'active'   => esc_html__('Active', 'event_espresso'),
1124
            'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1125
            'expired'  => esc_html__('Expired', 'event_espresso'),
1126
            'inactive' => esc_html__('Inactive', 'event_espresso'),
1127
        );
1128
1129
        return EEH_Form_Fields::select_input($select_name, $values, $current_value, '', 'wide');
1130
    }
1131
1132
1133
    /**
1134
     * returns a list of "venues"
1135
     *
1136
     * @param string $current_value whatever the current active status is
1137
     * @return string
1138
     * @throws EE_Error
1139
     * @throws InvalidArgumentException
1140
     * @throws InvalidDataTypeException
1141
     * @throws InvalidInterfaceException
1142
     * @throws ReflectionException
1143
     */
1144
    protected function venuesDropdown($current_value = '')
1145
    {
1146
        $select_name = 'venue';
1147
        $values = array(
1148
            '' => esc_html__('All Venues', 'event_espresso'),
1149
        );
1150
        // populate the list of venues.
1151
        $venue_model = EE_Registry::instance()->load_model('Venue');
1152
        $venues = $venue_model->get_all(array('order_by' => array('VNU_name' => 'ASC')));
1153
1154
        foreach ($venues as $venue) {
1155
            $values[ $venue->ID() ] = $venue->name();
1156
        }
1157
1158
        return EEH_Form_Fields::select_input($select_name, $values, $current_value, '', 'wide');
1159
    }
1160
1161
1162
    /**
1163
     * output a dropdown of the categories for the category filter on the event admin list table
1164
     *
1165
     * @access  public
1166
     * @return string html
1167
     */
1168
    public function category_dropdown()
1169
    {
1170
        $cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1171
        return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1172
    }
1173
1174
1175
    /**
1176
     * get total number of events today
1177
     *
1178
     * @access public
1179
     * @return int
1180
     * @throws EE_Error
1181
     * @throws InvalidArgumentException
1182
     * @throws InvalidDataTypeException
1183
     * @throws InvalidInterfaceException
1184
     */
1185
    public function total_events_today()
1186
    {
1187
        $start = EEM_Datetime::instance()->convert_datetime_for_query(
1188
            'DTT_EVT_start',
1189
            date('Y-m-d') . ' 00:00:00',
1190
            'Y-m-d H:i:s',
1191
            'UTC'
1192
        );
1193
        $end = EEM_Datetime::instance()->convert_datetime_for_query(
1194
            'DTT_EVT_start',
1195
            date('Y-m-d') . ' 23:59:59',
1196
            'Y-m-d H:i:s',
1197
            'UTC'
1198
        );
1199
        $where = array(
1200
            'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1201
        );
1202
        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1203
        return $count;
1204
    }
1205
1206
1207
    /**
1208
     * get total number of events this month
1209
     *
1210
     * @access public
1211
     * @return int
1212
     * @throws EE_Error
1213
     * @throws InvalidArgumentException
1214
     * @throws InvalidDataTypeException
1215
     * @throws InvalidInterfaceException
1216
     */
1217
    public function total_events_this_month()
1218
    {
1219
        // Dates
1220
        $this_year_r = date('Y');
1221
        $this_month_r = date('m');
1222
        $days_this_month = date('t');
1223
        $start = EEM_Datetime::instance()->convert_datetime_for_query(
1224
            'DTT_EVT_start',
1225
            $this_year_r . '-' . $this_month_r . '-01 00:00:00',
1226
            'Y-m-d H:i:s',
1227
            'UTC'
1228
        );
1229
        $end = EEM_Datetime::instance()->convert_datetime_for_query(
1230
            'DTT_EVT_start',
1231
            $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1232
            'Y-m-d H:i:s',
1233
            'UTC'
1234
        );
1235
        $where = array(
1236
            'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1237
        );
1238
        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1239
        return $count;
1240
    }
1241
1242
1243
    /** DEFAULT TICKETS STUFF **/
1244
1245
    /**
1246
     * Output default tickets list table view.
1247
     *
1248
     * @throws DomainException
1249
     * @throws EE_Error
1250
     * @throws InvalidArgumentException
1251
     * @throws InvalidDataTypeException
1252
     * @throws InvalidInterfaceException
1253
     */
1254
    public function _tickets_overview_list_table()
1255
    {
1256
        $this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1257
        $this->display_admin_list_table_page_with_no_sidebar();
1258
    }
1259
1260
1261
    /**
1262
     * @param int  $per_page
1263
     * @param bool $count
1264
     * @param bool $trashed
1265
     * @return EE_Soft_Delete_Base_Class[]|int
1266
     * @throws EE_Error
1267
     * @throws InvalidArgumentException
1268
     * @throws InvalidDataTypeException
1269
     * @throws InvalidInterfaceException
1270
     */
1271 View Code Duplication
    public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1272
    {
1273
        $orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1274
        $order = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1275
        switch ($orderby) {
1276
            case 'TKT_name':
1277
                $orderby = array('TKT_name' => $order);
1278
                break;
1279
            case 'TKT_price':
1280
                $orderby = array('TKT_price' => $order);
1281
                break;
1282
            case 'TKT_uses':
1283
                $orderby = array('TKT_uses' => $order);
1284
                break;
1285
            case 'TKT_min':
1286
                $orderby = array('TKT_min' => $order);
1287
                break;
1288
            case 'TKT_max':
1289
                $orderby = array('TKT_max' => $order);
1290
                break;
1291
            case 'TKT_qty':
1292
                $orderby = array('TKT_qty' => $order);
1293
                break;
1294
        }
1295
        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1296
            ? $this->_req_data['paged']
1297
            : 1;
1298
        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1299
            ? $this->_req_data['perpage']
1300
            : $per_page;
1301
        $_where = array(
1302
            'TKT_is_default' => 1,
1303
            'TKT_deleted'    => $trashed,
1304
        );
1305
        $offset = ($current_page - 1) * $per_page;
1306
        $limit = array($offset, $per_page);
1307
        if (isset($this->_req_data['s'])) {
1308
            $sstr = '%' . $this->_req_data['s'] . '%';
1309
            $_where['OR'] = array(
1310
                'TKT_name'        => array('LIKE', $sstr),
1311
                'TKT_description' => array('LIKE', $sstr),
1312
            );
1313
        }
1314
        $query_params = array(
1315
            $_where,
1316
            'order_by' => $orderby,
1317
            'limit'    => $limit,
1318
            'group_by' => 'TKT_ID',
1319
        );
1320
        if ($count) {
1321
            return EEM_Ticket::instance()->count_deleted_and_undeleted(array($_where));
1322
        } else {
1323
            return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1324
        }
1325
    }
1326
1327
1328
    /**
1329
     * @param bool $trash
1330
     * @throws EE_Error
1331
     * @throws InvalidArgumentException
1332
     * @throws InvalidDataTypeException
1333
     * @throws InvalidInterfaceException
1334
     */
1335
    protected function _trash_or_restore_ticket($trash = false)
1336
    {
1337
        $success = 1;
1338
        $TKT = EEM_Ticket::instance();
1339
        // checkboxes?
1340
        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1341
            // if array has more than one element then success message should be plural
1342
            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1343
            // cycle thru the boxes
1344
            foreach ($this->_req_data['checkbox'] as $TKT_ID) {
1345
                if ($trash) {
1346
                    if (! $TKT->delete_by_ID($TKT_ID)) {
1347
                        $success = 0;
1348
                    }
1349
                } elseif (! $TKT->restore_by_ID($TKT_ID)) {
1350
                    $success = 0;
1351
                }
1352
            }
1353 View Code Duplication
        } else {
1354
            // grab single id and trash
1355
            $TKT_ID = absint($this->_req_data['TKT_ID']);
1356
            if ($trash) {
1357
                if (! $TKT->delete_by_ID($TKT_ID)) {
1358
                    $success = 0;
1359
                }
1360
            } elseif (! $TKT->restore_by_ID($TKT_ID)) {
1361
                $success = 0;
1362
            }
1363
        }
1364
        $action_desc = $trash ? 'moved to the trash' : 'restored';
1365
        $query_args = array(
1366
            'action' => 'ticket_list_table',
1367
            'status' => $trash ? '' : 'trashed',
1368
        );
1369
        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1370
    }
1371
1372
1373
    /**
1374
     * Handles trashing default ticket.
1375
     *
1376
     * @throws EE_Error
1377
     * @throws InvalidArgumentException
1378
     * @throws InvalidDataTypeException
1379
     * @throws InvalidInterfaceException
1380
     * @throws ReflectionException
1381
     */
1382
    protected function _delete_ticket()
1383
    {
1384
        $success = 1;
1385
        // checkboxes?
1386 View Code Duplication
        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1387
            // if array has more than one element then success message should be plural
1388
            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1389
            // cycle thru the boxes
1390
            foreach ($this->_req_data['checkbox'] as $TKT_ID) {
1391
                // delete
1392
                if (! $this->_delete_the_ticket($TKT_ID)) {
1393
                    $success = 0;
1394
                }
1395
            }
1396
        } else {
1397
            // grab single id and trash
1398
            $TKT_ID = absint($this->_req_data['TKT_ID']);
1399
            if (! $this->_delete_the_ticket($TKT_ID)) {
1400
                $success = 0;
1401
            }
1402
        }
1403
        $action_desc = 'deleted';
1404
        $query_args = array(
1405
            'action' => 'ticket_list_table',
1406
            'status' => 'trashed',
1407
        );
1408
        // fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1409
        if (EEM_Ticket::instance()->count_deleted_and_undeleted(
1410
            array(array('TKT_is_default' => 1)),
1411
            'TKT_ID',
1412
            true
1413
        )
1414
        ) {
1415
            $query_args = array();
1416
        }
1417
        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1418
    }
1419
1420
1421
    /**
1422
     * @param int $TKT_ID
1423
     * @return bool|int
1424
     * @throws EE_Error
1425
     * @throws InvalidArgumentException
1426
     * @throws InvalidDataTypeException
1427
     * @throws InvalidInterfaceException
1428
     * @throws ReflectionException
1429
     */
1430
    protected function _delete_the_ticket($TKT_ID)
1431
    {
1432
        $tkt = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1433
        $tkt->_remove_relations('Datetime');
1434
        // delete all related prices first
1435
        $tkt->delete_related_permanently('Price');
1436
        return $tkt->delete_permanently();
1437
    }
1438
}
1439