Completed
Branch EDTR/refactor-master (e18acd)
by
unknown
11:03 queued 02:08
created

EE_Admin_Page::initializePage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
1
<?php
2
3
use EventEspresso\core\exceptions\InvalidDataTypeException;
4
use EventEspresso\core\exceptions\InvalidInterfaceException;
5
use EventEspresso\core\interfaces\InterminableInterface;
6
use EventEspresso\core\services\loaders\LoaderFactory;
7
use EventEspresso\core\services\loaders\LoaderInterface;
8
9
/**
10
 * EE_Admin_Page class
11
 *
12
 * @package           Event Espresso
13
 * @subpackage        includes/core/admin/EE_Admin_Page.core.php
14
 * @abstract
15
 * @author            Brent Christensen, Darren Ethier
16
 */
17
abstract class EE_Admin_Page extends EE_Base implements InterminableInterface
18
{
19
20
    /**
21
     * @var LoaderInterface $loader
22
     */
23
    protected $loader;
24
25
    // set in _init_page_props()
26
    public $page_slug;
27
28
    public $page_label;
29
30
    public $page_folder;
31
32
    // set in define_page_props()
33
    protected $_admin_base_url;
34
35
    protected $_admin_base_path;
36
37
    protected $_admin_page_title;
38
39
    protected $_labels;
40
41
42
    // set early within EE_Admin_Init
43
    protected $_wp_page_slug;
44
45
    // nav tabs
46
    protected $_nav_tabs;
47
48
    protected $_default_nav_tab_name;
49
50
    /**
51
     * @var array $_help_tour
52
     */
53
    protected $_help_tour = array();
54
55
56
    // template variables (used by templates)
57
    protected $_template_path;
58
59
    protected $_column_template_path;
60
61
    /**
62
     * @var array $_template_args
63
     */
64
    protected $_template_args = array();
65
66
    /**
67
     * this will hold the list table object for a given view.
68
     *
69
     * @var EE_Admin_List_Table $_list_table_object
70
     */
71
    protected $_list_table_object;
72
73
    // boolean
74
    protected $_is_UI_request; // this starts at null so we can have no header routes progress through two states.
75
76
    protected $_routing;
77
78
    // list table args
79
    protected $_view;
80
81
    protected $_views;
82
83
84
    // action => method pairs used for routing incoming requests
85
    protected $_page_routes;
86
87
    /**
88
     * @var array $_page_config
89
     */
90
    protected $_page_config;
91
92
    /**
93
     * the current page route and route config
94
     *
95
     * @var string $_route
96
     */
97
    protected $_route;
98
99
    /**
100
     * @var string $_cpt_route
101
     */
102
    protected $_cpt_route;
103
104
    /**
105
     * @var array $_route_config
106
     */
107
    protected $_route_config;
108
109
    /**
110
     * Used to hold default query args for list table routes to help preserve stickiness of filters for carried out
111
     * actions.
112
     *
113
     * @since 4.6.x
114
     * @var array.
115
     */
116
    protected $_default_route_query_args;
117
118
    // set via request page and action args.
119
    protected $_current_page;
120
121
    protected $_current_view;
122
123
    protected $_current_page_view_url;
124
125
    // sanitized request action (and nonce)
126
127
    /**
128
     * @var string $_req_action
129
     */
130
    protected $_req_action;
131
132
    /**
133
     * @var string $_req_nonce
134
     */
135
    protected $_req_nonce;
136
137
    // search related
138
    protected $_search_btn_label;
139
140
    protected $_search_box_callback;
141
142
    /**
143
     * WP Current Screen object
144
     *
145
     * @var WP_Screen
146
     */
147
    protected $_current_screen;
148
149
    // for holding EE_Admin_Hooks object when needed (set via set_hook_object())
150
    protected $_hook_obj;
151
152
    // for holding incoming request data
153
    protected $_req_data;
154
155
    // yes / no array for admin form fields
156
    protected $_yes_no_values = array();
157
158
    // some default things shared by all child classes
159
    protected $_default_espresso_metaboxes;
160
161
    /**
162
     *    EE_Registry Object
163
     *
164
     * @var    EE_Registry
165
     */
166
    protected $EE;
167
168
169
    /**
170
     * This is just a property that flags whether the given route is a caffeinated route or not.
171
     *
172
     * @var boolean
173
     */
174
    protected $_is_caf = false;
175
176
177
    /**
178
     * @Constructor
179
     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
180
     * @throws EE_Error
181
     * @throws InvalidArgumentException
182
     * @throws ReflectionException
183
     * @throws InvalidDataTypeException
184
     * @throws InvalidInterfaceException
185
     */
186
    public function __construct($routing = true)
187
    {
188
        $this->loader = LoaderFactory::getLoader();
189
        if (strpos($this->_get_dir(), 'caffeinated') !== false) {
190
            $this->_is_caf = true;
191
        }
192
        $this->_yes_no_values = array(
193
            array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
194
            array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
195
        );
196
        // set the _req_data property.
197
        $this->_req_data = array_merge($_GET, $_POST);
198
        // routing enabled?
199
        $this->_routing = $routing;
200
    }
201
202
203
    /**
204
     * This logic used to be in the constructor, but that caused a chicken <--> egg scenario
205
     * for child classes that needed to set properties prior to these methods getting called,
206
     * but also needed the parent class to have its construction completed as well.
207
     * Bottom line is that constructors should ONLY be used for setting initial properties
208
     * and any complex initialization logic should only run after instantiation is complete.
209
     *
210
     * This method gets called immediately after construction from within
211
     *      EE_Admin_Page_Init::_initialize_admin_page()
212
     *
213
     * @throws EE_Error
214
     * @throws InvalidArgumentException
215
     * @throws InvalidDataTypeException
216
     * @throws InvalidInterfaceException
217
     * @throws ReflectionException
218
     * @since $VID:$
219
     */
220
    public function initializePage()
221
    {
222
        // set initial page props (child method)
223
        $this->_init_page_props();
224
        // set global defaults
225
        $this->_set_defaults();
226
        // set early because incoming requests could be ajax related and we need to register those hooks.
227
        $this->_global_ajax_hooks();
228
        $this->_ajax_hooks();
229
        // other_page_hooks have to be early too.
230
        $this->_do_other_page_hooks();
231
        // This just allows us to have extending classes do something specific
232
        // before the parent constructor runs _page_setup().
233
        if (method_exists($this, '_before_page_setup')) {
234
            $this->_before_page_setup();
235
        }
236
        // set up page dependencies
237
        $this->_page_setup();
238
    }
239
240
241
    /**
242
     * _init_page_props
243
     * Child classes use to set at least the following properties:
244
     * $page_slug.
245
     * $page_label.
246
     *
247
     * @abstract
248
     * @return void
249
     */
250
    abstract protected function _init_page_props();
251
252
253
    /**
254
     * _ajax_hooks
255
     * child classes put all their add_action('wp_ajax_{name_of_hook}') hooks in here.
256
     * Note: within the ajax callback methods.
257
     *
258
     * @abstract
259
     * @return void
260
     */
261
    abstract protected function _ajax_hooks();
262
263
264
    /**
265
     * _define_page_props
266
     * child classes define page properties in here.  Must include at least:
267
     * $_admin_base_url = base_url for all admin pages
268
     * $_admin_page_title = default admin_page_title for admin pages
269
     * $_labels = array of default labels for various automatically generated elements:
270
     *    array(
271
     *        'buttons' => array(
272
     *            'add' => esc_html__('label for add new button'),
273
     *            'edit' => esc_html__('label for edit button'),
274
     *            'delete' => esc_html__('label for delete button')
275
     *            )
276
     *        )
277
     *
278
     * @abstract
279
     * @return void
280
     */
281
    abstract protected function _define_page_props();
282
283
284
    /**
285
     * _set_page_routes
286
     * child classes use this to define the page routes for all subpages handled by the class.  Page routes are
287
     * assigned to a action => method pairs in an array and to the $_page_routes property.  Each page route must also
288
     * have a 'default' route. Here's the format
289
     * $this->_page_routes = array(
290
     *        'default' => array(
291
     *            'func' => '_default_method_handling_route',
292
     *            'args' => array('array','of','args'),
293
     *            'noheader' => true, //add this in if this page route is processed before any headers are loaded (i.e.
294
     *            ajax request, backend processing)
295
     *            'headers_sent_route'=>'headers_route_reference', //add this if noheader=>true, and you want to load a
296
     *            headers route after.  The string you enter here should match the defined route reference for a
297
     *            headers sent route.
298
     *            'capability' => 'route_capability', //indicate a string for minimum capability required to access
299
     *            this route.
300
     *            'obj_id' => 10 // if this route has an object id, then this can include it (used for capability
301
     *            checks).
302
     *        ),
303
     *        'insert_item' => '_method_for_handling_insert_item' //this can be used if all we need to have is a
304
     *        handling method.
305
     *        )
306
     * )
307
     *
308
     * @abstract
309
     * @return void
310
     */
311
    abstract protected function _set_page_routes();
312
313
314
    /**
315
     * _set_page_config
316
     * child classes use this to define the _page_config array for all subpages handled by the class. Each key in the
317
     * array corresponds to the page_route for the loaded page. Format:
318
     * $this->_page_config = array(
319
     *        'default' => array(
320
     *            'labels' => array(
321
     *                'buttons' => array(
322
     *                    'add' => esc_html__('label for adding item'),
323
     *                    'edit' => esc_html__('label for editing item'),
324
     *                    'delete' => esc_html__('label for deleting item')
325
     *                ),
326
     *                'publishbox' => esc_html__('Localized Title for Publish metabox', 'event_espresso')
327
     *            ), //optional an array of custom labels for various automatically generated elements to use on the
328
     *            page. If this isn't present then the defaults will be used as set for the $this->_labels in
329
     *            _define_page_props() method
330
     *            'nav' => array(
331
     *                'label' => esc_html__('Label for Tab', 'event_espresso').
332
     *                'url' => 'http://someurl', //automatically generated UNLESS you define
333
     *                'css_class' => 'css-class', //automatically generated UNLESS you define
334
     *                'order' => 10, //required to indicate tab position.
335
     *                'persistent' => false //if you want the nav tab to ONLY display when the specific route is
336
     *                displayed then add this parameter.
337
     *            'list_table' => 'name_of_list_table' //string for list table class to be loaded for this admin_page.
338
     *            'metaboxes' => array('metabox1', 'metabox2'), //if present this key indicates we want to load
339
     *            metaboxes set for eventespresso admin pages.
340
     *            'has_metaboxes' => true, //this boolean flag can simply be used to indicate if the route will have
341
     *            metaboxes.  Typically this is used if the 'metaboxes' index is not used because metaboxes are added
342
     *            later.  We just use this flag to make sure the necessary js gets enqueued on page load.
343
     *            'has_help_popups' => false //defaults(true) //this boolean flag can simply be used to indicate if the
344
     *            given route has help popups setup and if it does then we need to make sure thickbox is enqueued.
345
     *            'columns' => array(4, 2), //this key triggers the setup of a page that uses columns (metaboxes).  The
346
     *            array indicates the max number of columns (4) and the default number of columns on page load (2).
347
     *            There is an option in the "screen_options" dropdown that is setup so users can pick what columns they
348
     *            want to display.
349
     *            'help_tabs' => array( //this is used for adding help tabs to a page
350
     *                'tab_id' => array(
351
     *                    'title' => 'tab_title',
352
     *                    'filename' => 'name_of_file_containing_content', //this is the primary method for setting
353
     *                    help tab content.  The fallback if it isn't present is to try a the callback.  Filename
354
     *                    should match a file in the admin folder's "help_tabs" dir (ie..
355
     *                    events/help_tabs/name_of_file_containing_content.help_tab.php)
356
     *                    'callback' => 'callback_method_for_content', //if 'filename' isn't present then system will
357
     *                    attempt to use the callback which should match the name of a method in the class
358
     *                    ),
359
     *                'tab2_id' => array(
360
     *                    'title' => 'tab2 title',
361
     *                    'filename' => 'file_name_2'
362
     *                    'callback' => 'callback_method_for_content',
363
     *                 ),
364
     *            'help_sidebar' => 'callback_for_sidebar_content', //this is used for setting up the sidebar in the
365
     *            help tab area on an admin page. @link
366
     *            http://make.wordpress.org/core/2011/12/06/help-and-screen-api-changes-in-3-3/
367
     *            'help_tour' => array(
368
     *                'name_of_help_tour_class', //all help tours shoudl be a child class of EE_Help_Tour and located
369
     *                in a folder for this admin page named "help_tours", a file name matching the key given here
370
     *                (name_of_help_tour_class.class.php), and class matching key given here (name_of_help_tour_class)
371
     *            ),
372
     *            'require_nonce' => TRUE //this is used if you want to set a route to NOT require a nonce (default is
373
     *            true if it isn't present).  To remove the requirement for a nonce check when this route is visited
374
     *            just set
375
     *            'require_nonce' to FALSE
376
     *            )
377
     * )
378
     *
379
     * @abstract
380
     * @return void
381
     */
382
    abstract protected function _set_page_config();
383
384
385
386
387
388
    /** end sample help_tour methods **/
389
    /**
390
     * _add_screen_options
391
     * Child classes can add any extra wp_screen_options within this method using built-in WP functions/methods for
392
     * doing so. Note child classes can also define _add_screen_options_($this->_current_view) to limit screen options
393
     * to a particular view.
394
     *
395
     * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
396
     *         see also WP_Screen object documents...
397
     * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
398
     * @abstract
399
     * @return void
400
     */
401
    abstract protected function _add_screen_options();
402
403
404
    /**
405
     * _add_feature_pointers
406
     * Child classes should use this method for implementing any "feature pointers" (using built-in WP styling js).
407
     * Note child classes can also define _add_feature_pointers_($this->_current_view) to limit screen options to a
408
     * particular view. Note: this is just a placeholder for now.  Implementation will come down the road See:
409
     * WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
410
     * extended) also see:
411
     *
412
     * @link   http://eamann.com/tech/wordpress-portland/
413
     * @abstract
414
     * @return void
415
     */
416
    abstract protected function _add_feature_pointers();
417
418
419
    /**
420
     * load_scripts_styles
421
     * child classes put their wp_enqueue_script and wp_enqueue_style hooks in here for anything they need loaded for
422
     * their pages/subpages.  Note this is for all pages/subpages of the system.  You can also load only specific
423
     * scripts/styles per view by putting them in a dynamic function in this format
424
     * (load_scripts_styles_{$this->_current_view}) which matches your page route (action request arg)
425
     *
426
     * @abstract
427
     * @return void
428
     */
429
    abstract public function load_scripts_styles();
430
431
432
    /**
433
     * admin_init
434
     * Anything that should be set/executed at 'admin_init' WP hook runtime should be put in here.  This will apply to
435
     * all pages/views loaded by child class.
436
     *
437
     * @abstract
438
     * @return void
439
     */
440
    abstract public function admin_init();
441
442
443
    /**
444
     * admin_notices
445
     * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply to
446
     * all pages/views loaded by child class.
447
     *
448
     * @abstract
449
     * @return void
450
     */
451
    abstract public function admin_notices();
452
453
454
    /**
455
     * admin_footer_scripts
456
     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
457
     * will apply to all pages/views loaded by child class.
458
     *
459
     * @return void
460
     */
461
    abstract public function admin_footer_scripts();
462
463
464
    /**
465
     * admin_footer
466
     * anything triggered by the 'admin_footer' WP action hook should be added to here. This particular method will
467
     * apply to all pages/views loaded by child class.
468
     *
469
     * @return void
470
     */
471
    public function admin_footer()
472
    {
473
    }
474
475
476
    /**
477
     * _global_ajax_hooks
478
     * all global add_action('wp_ajax_{name_of_hook}') hooks in here.
479
     * Note: within the ajax callback methods.
480
     *
481
     * @abstract
482
     * @return void
483
     */
484
    protected function _global_ajax_hooks()
485
    {
486
        // for lazy loading of metabox content
487
        add_action('wp_ajax_espresso-ajax-content', array($this, 'ajax_metabox_content'), 10);
488
    }
489
490
491
    public function ajax_metabox_content()
492
    {
493
        $contentid = isset($this->_req_data['contentid']) ? $this->_req_data['contentid'] : '';
494
        $url = isset($this->_req_data['contenturl']) ? $this->_req_data['contenturl'] : '';
495
        self::cached_rss_display($contentid, $url);
496
        wp_die();
497
    }
498
499
500
    /**
501
     * _page_setup
502
     * Makes sure any things that need to be loaded early get handled.  We also escape early here if the page requested
503
     * doesn't match the object.
504
     *
505
     * @final
506
     * @return void
507
     * @throws EE_Error
508
     * @throws InvalidArgumentException
509
     * @throws ReflectionException
510
     * @throws InvalidDataTypeException
511
     * @throws InvalidInterfaceException
512
     */
513
    final protected function _page_setup()
514
    {
515
        // requires?
516
        // admin_init stuff - global - we're setting this REALLY early
517
        // so if EE_Admin pages have to hook into other WP pages they can.
518
        // But keep in mind, not everything is available from the EE_Admin Page object at this point.
519
        add_action('admin_init', array($this, 'admin_init_global'), 5);
520
        // next verify if we need to load anything...
521
        $this->_current_page = ! empty($_GET['page']) ? sanitize_key($_GET['page']) : '';
522
        $this->page_folder = strtolower(
523
            str_replace(array('_Admin_Page', 'Extend_'), '', get_class($this))
524
        );
525
        global $ee_menu_slugs;
526
        $ee_menu_slugs = (array) $ee_menu_slugs;
527
        if (! defined('DOING_AJAX') && (! $this->_current_page || ! isset($ee_menu_slugs[ $this->_current_page ]))) {
528
            return;
529
        }
530
        // becuz WP List tables have two duplicate select inputs for choosing bulk actions, we need to copy the action from the second to the first
531
        if (isset($this->_req_data['action2']) && $this->_req_data['action'] === '-1') {
532
            $this->_req_data['action'] = ! empty($this->_req_data['action2']) && $this->_req_data['action2'] !== '-1'
533
                ? $this->_req_data['action2']
534
                : $this->_req_data['action'];
535
        }
536
        // then set blank or -1 action values to 'default'
537
        $this->_req_action = isset($this->_req_data['action'])
538
                             && ! empty($this->_req_data['action'])
539
                             && $this->_req_data['action'] !== '-1'
540
            ? sanitize_key($this->_req_data['action'])
541
            : 'default';
542
        // if action is 'default' after the above BUT we have  'route' var set, then let's use the route as the action.
543
        //  This covers cases where we're coming in from a list table that isn't on the default route.
544
        $this->_req_action = $this->_req_action === 'default' && isset($this->_req_data['route'])
545
            ? $this->_req_data['route'] : $this->_req_action;
546
        // however if we are doing_ajax and we've got a 'route' set then that's what the req_action will be
547
        $this->_req_action = defined('DOING_AJAX') && isset($this->_req_data['route'])
548
            ? $this->_req_data['route']
549
            : $this->_req_action;
550
        $this->_current_view = $this->_req_action;
551
        $this->_req_nonce = $this->_req_action . '_nonce';
552
        $this->_define_page_props();
553
        $this->_current_page_view_url = add_query_arg(
554
            array('page' => $this->_current_page, 'action' => $this->_current_view),
555
            $this->_admin_base_url
556
        );
557
        // default things
558
        $this->_default_espresso_metaboxes = array(
559
            '_espresso_news_post_box',
560
            '_espresso_links_post_box',
561
            '_espresso_ratings_request',
562
            '_espresso_sponsors_post_box',
563
        );
564
        // set page configs
565
        $this->_set_page_routes();
566
        $this->_set_page_config();
567
        // let's include any referrer data in our default_query_args for this route for "stickiness".
568
        if (isset($this->_req_data['wp_referer'])) {
569
            $this->_default_route_query_args['wp_referer'] = $this->_req_data['wp_referer'];
570
        }
571
        // for caffeinated and other extended functionality.
572
        //  If there is a _extend_page_config method
573
        // then let's run that to modify the all the various page configuration arrays
574
        if (method_exists($this, '_extend_page_config')) {
575
            $this->_extend_page_config();
576
        }
577
        // for CPT and other extended functionality.
578
        // If there is an _extend_page_config_for_cpt
579
        // then let's run that to modify all the various page configuration arrays.
580
        if (method_exists($this, '_extend_page_config_for_cpt')) {
581
            $this->_extend_page_config_for_cpt();
582
        }
583
        // filter routes and page_config so addons can add their stuff. Filtering done per class
584
        $this->_page_routes = apply_filters(
585
            'FHEE__' . get_class($this) . '__page_setup__page_routes',
586
            $this->_page_routes,
587
            $this
588
        );
589
        $this->_page_config = apply_filters(
590
            'FHEE__' . get_class($this) . '__page_setup__page_config',
591
            $this->_page_config,
592
            $this
593
        );
594
        // if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present
595
        // then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
596
        if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)) {
597
            add_action(
598
                'AHEE__EE_Admin_Page__route_admin_request',
599
                array($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view),
600
                10,
601
                2
602
            );
603
        }
604
        // next route only if routing enabled
605
        if ($this->_routing && ! defined('DOING_AJAX')) {
606
            $this->_verify_routes();
607
            // next let's just check user_access and kill if no access
608
            $this->check_user_access();
609
            if ($this->_is_UI_request) {
610
                // admin_init stuff - global, all views for this page class, specific view
611
                add_action('admin_init', array($this, 'admin_init'), 10);
612
                if (method_exists($this, 'admin_init_' . $this->_current_view)) {
613
                    add_action('admin_init', array($this, 'admin_init_' . $this->_current_view), 15);
614
                }
615
            } else {
616
                // hijack regular WP loading and route admin request immediately
617
                @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
618
                $this->route_admin_request();
619
            }
620
        }
621
    }
622
623
624
    /**
625
     * Provides a way for related child admin pages to load stuff on the loaded admin page.
626
     *
627
     * @return void
628
     * @throws ReflectionException
629
     * @throws EE_Error
630
     */
631
    private function _do_other_page_hooks()
632
    {
633
        $registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, array());
634
        foreach ($registered_pages as $page) {
635
            // now let's setup the file name and class that should be present
636
            $classname = str_replace('.class.php', '', $page);
637
            // autoloaders should take care of loading file
638
            if (! class_exists($classname)) {
639
                $error_msg[] = sprintf(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$error_msg was never initialized. Although not strictly required by PHP, it is generally a good practice to add $error_msg = 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...
640
                    esc_html__(
641
                        'Something went wrong with loading the %s admin hooks page.',
642
                        'event_espresso'
643
                    ),
644
                    $page
645
                );
646
                $error_msg[] = $error_msg[0]
647
                               . "\r\n"
648
                               . sprintf(
649
                                   esc_html__(
650
                                       'There is no class in place for the %1$s admin hooks page.%2$sMake sure you have %3$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
651
                                       'event_espresso'
652
                                   ),
653
                                   $page,
654
                                   '<br />',
655
                                   '<strong>' . $classname . '</strong>'
656
                               );
657
                throw new EE_Error(implode('||', $error_msg));
658
            }
659
            // // notice we are passing the instance of this class to the hook object.
660
            $this->loader->getShared($classname, [$this]);
661
        }
662
    }
663
664
665
    /**
666
     * @throws DomainException
667
     * @throws EE_Error
668
     * @throws InvalidArgumentException
669
     * @throws InvalidDataTypeException
670
     * @throws InvalidInterfaceException
671
     * @throws ReflectionException
672
     * @since $VID:$
673
     */
674
    public function load_page_dependencies()
675
    {
676
        try {
677
            $this->_load_page_dependencies();
678
        } catch (EE_Error $e) {
679
            $e->get_error();
680
        }
681
    }
682
683
684
    /**
685
     * load_page_dependencies
686
     * loads things specific to this page class when its loaded.  Really helps with efficiency.
687
     *
688
     * @return void
689
     * @throws DomainException
690
     * @throws EE_Error
691
     * @throws InvalidArgumentException
692
     * @throws InvalidDataTypeException
693
     * @throws InvalidInterfaceException
694
     * @throws ReflectionException
695
     */
696
    protected function _load_page_dependencies()
697
    {
698
        // let's set the current_screen and screen options to override what WP set
699
        $this->_current_screen = get_current_screen();
700
        // load admin_notices - global, page class, and view specific
701
        add_action('admin_notices', array($this, 'admin_notices_global'), 5);
702
        add_action('admin_notices', array($this, 'admin_notices'), 10);
703
        if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
704
            add_action('admin_notices', array($this, 'admin_notices_' . $this->_current_view), 15);
705
        }
706
        // load network admin_notices - global, page class, and view specific
707
        add_action('network_admin_notices', array($this, 'network_admin_notices_global'), 5);
708
        if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
709
            add_action('network_admin_notices', array($this, 'network_admin_notices_' . $this->_current_view));
710
        }
711
        // this will save any per_page screen options if they are present
712
        $this->_set_per_page_screen_options();
713
        // setup list table properties
714
        $this->_set_list_table();
715
        // child classes can "register" a metabox to be automatically handled via the _page_config array property.
716
        // However in some cases the metaboxes will need to be added within a route handling callback.
717
        $this->_add_registered_meta_boxes();
718
        $this->_add_screen_columns();
719
        // add screen options - global, page child class, and view specific
720
        $this->_add_global_screen_options();
721
        $this->_add_screen_options();
722
        $add_screen_options = "_add_screen_options_{$this->_current_view}";
723
        if (method_exists($this, $add_screen_options)) {
724
            $this->{$add_screen_options}();
725
        }
726
        // add help tab(s) and tours- set via page_config and qtips.
727
        $this->_add_help_tour();
728
        $this->_add_help_tabs();
729
        $this->_add_qtips();
730
        // add feature_pointers - global, page child class, and view specific
731
        $this->_add_feature_pointers();
732
        $this->_add_global_feature_pointers();
733
        $add_feature_pointer = "_add_feature_pointer_{$this->_current_view}";
734
        if (method_exists($this, $add_feature_pointer)) {
735
            $this->{$add_feature_pointer}();
736
        }
737
        // enqueue scripts/styles - global, page class, and view specific
738
        add_action('admin_enqueue_scripts', array($this, 'load_global_scripts_styles'), 5);
739
        add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles'), 10);
740
        if (method_exists($this, "load_scripts_styles_{$this->_current_view}")) {
741
            add_action('admin_enqueue_scripts', array($this, "load_scripts_styles_{$this->_current_view}"), 15);
742
        }
743
        add_action('admin_enqueue_scripts', array($this, 'admin_footer_scripts_eei18n_js_strings'), 100);
744
        // admin_print_footer_scripts - global, page child class, and view specific.
745
        // NOTE, despite the name, whenever possible, scripts should NOT be loaded using this.
746
        // In most cases that's doing_it_wrong().  But adding hidden container elements etc.
747
        // is a good use case. Notice the late priority we're giving these
748
        add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_global'), 99);
749
        add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts'), 100);
750
        if (method_exists($this, "admin_footer_scripts_{$this->_current_view}")) {
751
            add_action('admin_print_footer_scripts', array($this, "admin_footer_scripts_{$this->_current_view}"), 101);
752
        }
753
        // admin footer scripts
754
        add_action('admin_footer', array($this, 'admin_footer_global'), 99);
755
        add_action('admin_footer', array($this, 'admin_footer'), 100);
756
        if (method_exists($this, "admin_footer_{$this->_current_view}")) {
757
            add_action('admin_footer', array($this, "admin_footer_{$this->_current_view}"), 101);
758
        }
759
        do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', $this->page_slug);
760
        // targeted hook
761
        do_action(
762
            "FHEE__EE_Admin_Page___load_page_dependencies__after_load__{$this->page_slug}__{$this->_req_action}"
763
        );
764
    }
765
766
767
    /**
768
     * _set_defaults
769
     * This sets some global defaults for class properties.
770
     */
771
    private function _set_defaults()
772
    {
773
        $this->_current_screen = $this->_admin_page_title = $this->_req_action = $this->_req_nonce = null;
774
        $this->_event = $this->_template_path = $this->_column_template_path = null;
775
        $this->_nav_tabs = $this->_views = $this->_page_routes = array();
776
        $this->_page_config = $this->_default_route_query_args = array();
777
        $this->_default_nav_tab_name = 'overview';
778
        // init template args
779
        $this->_template_args = array(
780
            'admin_page_header'  => '',
781
            'admin_page_content' => '',
782
            'post_body_content'  => '',
783
            'before_list_table'  => '',
784
            'after_list_table'   => '',
785
        );
786
    }
787
788
789
    /**
790
     * route_admin_request
791
     *
792
     * @see    _route_admin_request()
793
     * @return exception|void error
794
     * @throws InvalidArgumentException
795
     * @throws InvalidInterfaceException
796
     * @throws InvalidDataTypeException
797
     * @throws EE_Error
798
     * @throws ReflectionException
799
     */
800
    public function route_admin_request()
801
    {
802
        try {
803
            $this->_route_admin_request();
804
        } catch (EE_Error $e) {
805
            $e->get_error();
806
        }
807
    }
808
809
810
    public function set_wp_page_slug($wp_page_slug)
811
    {
812
        $this->_wp_page_slug = $wp_page_slug;
813
        // if in network admin then we need to append "-network" to the page slug. Why? Because that's how WP rolls...
814
        if (is_network_admin()) {
815
            $this->_wp_page_slug .= '-network';
816
        }
817
    }
818
819
820
    /**
821
     * _verify_routes
822
     * All this method does is verify the incoming request and make sure that routes exist for it.  We do this early so
823
     * we know if we need to drop out.
824
     *
825
     * @return bool
826
     * @throws EE_Error
827
     */
828
    protected function _verify_routes()
829
    {
830
        if (! $this->_current_page && ! defined('DOING_AJAX')) {
831
            return false;
832
        }
833
        $this->_route = false;
834
        // check that the page_routes array is not empty
835 View Code Duplication
        if (empty($this->_page_routes)) {
836
            // user error msg
837
            $error_msg = sprintf(
838
                esc_html__('No page routes have been set for the %s admin page.', 'event_espresso'),
839
                $this->_admin_page_title
840
            );
841
            // developer error msg
842
            $error_msg .= '||' . $error_msg
843
                          . esc_html__(
844
                              ' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.',
845
                              'event_espresso'
846
                          );
847
            throw new EE_Error($error_msg);
848
        }
849
        // and that the requested page route exists
850
        if (array_key_exists($this->_req_action, $this->_page_routes)) {
851
            $this->_route = $this->_page_routes[ $this->_req_action ];
852
            $this->_route_config = isset($this->_page_config[ $this->_req_action ])
853
                ? $this->_page_config[ $this->_req_action ] : array();
854 View Code Duplication
        } else {
855
            // user error msg
856
            $error_msg = sprintf(
857
                esc_html__(
858
                    'The requested page route does not exist for the %s admin page.',
859
                    'event_espresso'
860
                ),
861
                $this->_admin_page_title
862
            );
863
            // developer error msg
864
            $error_msg .= '||' . $error_msg
865
                          . sprintf(
866
                              esc_html__(
867
                                  ' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.',
868
                                  'event_espresso'
869
                              ),
870
                              $this->_req_action
871
                          );
872
            throw new EE_Error($error_msg);
873
        }
874
        // and that a default route exists
875 View Code Duplication
        if (! array_key_exists('default', $this->_page_routes)) {
876
            // user error msg
877
            $error_msg = sprintf(
878
                esc_html__(
879
                    'A default page route has not been set for the % admin page.',
880
                    'event_espresso'
881
                ),
882
                $this->_admin_page_title
883
            );
884
            // developer error msg
885
            $error_msg .= '||' . $error_msg
886
                          . esc_html__(
887
                              ' Create a key in the "_page_routes" array named "default" and set its value to your default page method.',
888
                              'event_espresso'
889
                          );
890
            throw new EE_Error($error_msg);
891
        }
892
893
        // first lets' catch if the UI request has EVER been set.
894
        if ($this->_is_UI_request === null) {
895
            // lets set if this is a UI request or not.
896
            $this->_is_UI_request = ! isset($this->_req_data['noheader']) || $this->_req_data['noheader'] !== true;
897
            // wait a minute... we might have a noheader in the route array
898
            $this->_is_UI_request = is_array($this->_route)
899
                                    && isset($this->_route['noheader'])
900
                                    && $this->_route['noheader'] ? false : $this->_is_UI_request;
901
        }
902
        $this->_set_current_labels();
903
        return true;
904
    }
905
906
907
    /**
908
     * this method simply verifies a given route and makes sure its an actual route available for the loaded page
909
     *
910
     * @param  string $route the route name we're verifying
911
     * @return mixed (bool|Exception)      we'll throw an exception if this isn't a valid route.
912
     * @throws EE_Error
913
     */
914
    protected function _verify_route($route)
915
    {
916
        if (array_key_exists($this->_req_action, $this->_page_routes)) {
917
            return true;
918
        }
919
        // user error msg
920
        $error_msg = sprintf(
921
            esc_html__('The given page route does not exist for the %s admin page.', 'event_espresso'),
922
            $this->_admin_page_title
923
        );
924
        // developer error msg
925
        $error_msg .= '||' . $error_msg
926
                      . sprintf(
927
                          esc_html__(
928
                              ' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property',
929
                              'event_espresso'
930
                          ),
931
                          $route
932
                      );
933
        throw new EE_Error($error_msg);
934
    }
935
936
937
    /**
938
     * perform nonce verification
939
     * This method has be encapsulated here so that any ajax requests that bypass normal routes can verify their nonces
940
     * using this method (and save retyping!)
941
     *
942
     * @param string $nonce     The nonce sent
943
     * @param string $nonce_ref The nonce reference string (name0)
944
     * @return void
945
     * @throws EE_Error
946
     * @throws InvalidArgumentException
947
     * @throws InvalidDataTypeException
948
     * @throws InvalidInterfaceException
949
     */
950
    protected function _verify_nonce($nonce, $nonce_ref)
951
    {
952
        // verify nonce against expected value
953
        if (! wp_verify_nonce($nonce, $nonce_ref)) {
954
            // these are not the droids you are looking for !!!
955
            $msg = sprintf(
956
                esc_html__('%sNonce Fail.%s', 'event_espresso'),
957
                '<a href="http://www.youtube.com/watch?v=56_S0WeTkzs">',
958
                '</a>'
959
            );
960
            if (WP_DEBUG) {
961
                $msg .= "\n  "
962
                        . sprintf(
963
                            esc_html__(
964
                                'In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!',
965
                                'event_espresso'
966
                            ),
967
                            __CLASS__
968
                        );
969
            }
970
            if (! defined('DOING_AJAX')) {
971
                wp_die($msg);
972
            } else {
973
                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
974
                $this->_return_json();
975
            }
976
        }
977
    }
978
979
980
    /**
981
     * _route_admin_request()
982
     * Meat and potatoes of the class.  Basically, this dude checks out what's being requested and sees if there are
983
     * some doodads to work the magic and handle the flingjangy. Translation:  Checks if the requested action is listed
984
     * in the page routes and then will try to load the corresponding method.
985
     *
986
     * @return void
987
     * @throws EE_Error
988
     * @throws InvalidArgumentException
989
     * @throws InvalidDataTypeException
990
     * @throws InvalidInterfaceException
991
     * @throws ReflectionException
992
     */
993
    protected function _route_admin_request()
994
    {
995
        if (! $this->_is_UI_request) {
996
            $this->_verify_routes();
997
        }
998
        $nonce_check = isset($this->_route_config['require_nonce'])
999
            ? $this->_route_config['require_nonce']
1000
            : true;
1001 View Code Duplication
        if ($this->_req_action !== 'default' && $nonce_check) {
1002
            // set nonce from post data
1003
            $nonce = isset($this->_req_data[ $this->_req_nonce ])
1004
                ? sanitize_text_field($this->_req_data[ $this->_req_nonce ])
1005
                : '';
1006
            $this->_verify_nonce($nonce, $this->_req_nonce);
1007
        }
1008
        // set the nav_tabs array but ONLY if this is  UI_request
1009
        if ($this->_is_UI_request) {
1010
            $this->_set_nav_tabs();
1011
        }
1012
        // grab callback function
1013
        $func = is_array($this->_route) ? $this->_route['func'] : $this->_route;
1014
        // check if callback has args
1015
        $args = is_array($this->_route) && isset($this->_route['args']) ? $this->_route['args'] : array();
1016
        $error_msg = '';
1017
        // action right before calling route
1018
        // (hook is something like 'AHEE__Registrations_Admin_Page__route_admin_request')
1019
        if (! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
1020
            do_action('AHEE__EE_Admin_Page__route_admin_request', $this->_current_view, $this);
1021
        }
1022
        // right before calling the route, let's remove _wp_http_referer from the
1023
        // $_SERVER[REQUEST_URI] global (its now in _req_data for route processing).
1024
        $_SERVER['REQUEST_URI'] = remove_query_arg(
1025
            '_wp_http_referer',
1026
            wp_unslash($_SERVER['REQUEST_URI'])
1027
        );
1028
        if (! empty($func)) {
1029
            if (is_array($func)) {
1030
                list($class, $method) = $func;
1031
            } elseif (strpos($func, '::') !== false) {
1032
                list($class, $method) = explode('::', $func);
1033
            } else {
1034
                $class = $this;
1035
                $method = $func;
1036
            }
1037
            if (! (is_object($class) && $class === $this)) {
1038
                // send along this admin page object for access by addons.
1039
                $args['admin_page_object'] = $this;
1040
            }
1041
            // is it a method on a class that doesn't work?
1042
            if (((method_exists($class, $method)
1043
                  && call_user_func_array(array($class, $method), $args) === false)
1044
                 && (// is it a standalone function that doesn't work?
1045
                     function_exists($method)
1046
                     && call_user_func_array(
1047
                         $func,
1048
                         array_merge(array('admin_page_object' => $this), $args)
1049
                     ) === false
1050
                 )) || (// is it neither a class method NOR a standalone function?
1051
                    ! function_exists($method)
1052
                    && ! method_exists($class, $method)
1053
                )
1054
            ) {
1055
                // user error msg
1056
                $error_msg = esc_html__(
1057
                    'An error occurred. The  requested page route could not be found.',
1058
                    'event_espresso'
1059
                );
1060
                // developer error msg
1061
                $error_msg .= '||';
1062
                $error_msg .= sprintf(
1063
                    esc_html__(
1064
                        'Page route "%s" could not be called. Check that the spelling for method names and actions in the "_page_routes" array are all correct.',
1065
                        'event_espresso'
1066
                    ),
1067
                    $method
1068
                );
1069
            }
1070
            if (! empty($error_msg)) {
1071
                throw new EE_Error($error_msg);
1072
            }
1073
        }
1074
        // if we've routed and this route has a no headers route AND a sent_headers_route,
1075
        // then we need to reset the routing properties to the new route.
1076
        // now if UI request is FALSE and noheader is true AND we have a headers_sent_route in the route array then let's set UI_request to true because the no header route has a second func after headers have been sent.
1077
        if ($this->_is_UI_request === false
1078
            && is_array($this->_route)
1079
            && ! empty($this->_route['headers_sent_route'])
1080
        ) {
1081
            $this->_reset_routing_properties($this->_route['headers_sent_route']);
1082
        }
1083
    }
1084
1085
1086
    /**
1087
     * This method just allows the resetting of page properties in the case where a no headers
1088
     * route redirects to a headers route in its route config.
1089
     *
1090
     * @since   4.3.0
1091
     * @param  string $new_route New (non header) route to redirect to.
1092
     * @return   void
1093
     * @throws ReflectionException
1094
     * @throws InvalidArgumentException
1095
     * @throws InvalidInterfaceException
1096
     * @throws InvalidDataTypeException
1097
     * @throws EE_Error
1098
     */
1099
    protected function _reset_routing_properties($new_route)
1100
    {
1101
        $this->_is_UI_request = true;
1102
        // now we set the current route to whatever the headers_sent_route is set at
1103
        $this->_req_data['action'] = $new_route;
1104
        // rerun page setup
1105
        $this->_page_setup();
1106
    }
1107
1108
1109
    /**
1110
     * _add_query_arg
1111
     * adds nonce to array of arguments then calls WP add_query_arg function
1112
     *(internally just uses EEH_URL's function with the same name)
1113
     *
1114
     * @param array  $args
1115
     * @param string $url
1116
     * @param bool   $sticky                  if true, then the existing Request params will be appended to the
1117
     *                                        generated url in an associative array indexed by the key 'wp_referer';
1118
     *                                        Example usage: If the current page is:
1119
     *                                        http://mydomain.com/wp-admin/admin.php?page=espresso_registrations
1120
     *                                        &action=default&event_id=20&month_range=March%202015
1121
     *                                        &_wpnonce=5467821
1122
     *                                        and you call:
1123
     *                                        EE_Admin_Page::add_query_args_and_nonce(
1124
     *                                        array(
1125
     *                                        'action' => 'resend_something',
1126
     *                                        'page=>espresso_registrations'
1127
     *                                        ),
1128
     *                                        $some_url,
1129
     *                                        true
1130
     *                                        );
1131
     *                                        It will produce a url in this structure:
1132
     *                                        http://{$some_url}/?page=espresso_registrations&action=resend_something
1133
     *                                        &wp_referer[action]=default&wp_referer[event_id]=20&wpreferer[
1134
     *                                        month_range]=March%202015
1135
     * @param   bool $exclude_nonce           If true, the the nonce will be excluded from the generated nonce.
1136
     * @return string
1137
     */
1138
    public static function add_query_args_and_nonce(
1139
        $args = array(),
1140
        $url = '',
1141
        $sticky = false,
1142
        $exclude_nonce = false
1143
    ) {
1144
        // if there is a _wp_http_referer include the values from the request but only if sticky = true
1145
        if ($sticky) {
1146
            $request = $_REQUEST;
1147
            unset($request['_wp_http_referer'], $request['wp_referer']);
1148
            foreach ($request as $key => $value) {
1149
                // do not add nonces
1150
                if (strpos($key, 'nonce') !== false) {
1151
                    continue;
1152
                }
1153
                $args[ 'wp_referer[' . $key . ']' ] = $value;
1154
            }
1155
        }
1156
        return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
1157
    }
1158
1159
1160
    /**
1161
     * This returns a generated link that will load the related help tab.
1162
     *
1163
     * @param  string $help_tab_id the id for the connected help tab
1164
     * @param  string $icon_style  (optional) include css class for the style you want to use for the help icon.
1165
     * @param  string $help_text   (optional) send help text you want to use for the link if default not to be used
1166
     * @uses EEH_Template::get_help_tab_link()
1167
     * @return string              generated link
1168
     */
1169
    protected function _get_help_tab_link($help_tab_id, $icon_style = '', $help_text = '')
1170
    {
1171
        return EEH_Template::get_help_tab_link(
1172
            $help_tab_id,
1173
            $this->page_slug,
1174
            $this->_req_action,
1175
            $icon_style,
1176
            $help_text
1177
        );
1178
    }
1179
1180
1181
    /**
1182
     * _add_help_tabs
1183
     * Note child classes define their help tabs within the page_config array.
1184
     *
1185
     * @link   http://codex.wordpress.org/Function_Reference/add_help_tab
1186
     * @return void
1187
     * @throws DomainException
1188
     * @throws EE_Error
1189
     */
1190
    protected function _add_help_tabs()
1191
    {
1192
        $tour_buttons = '';
1193
        if (isset($this->_page_config[ $this->_req_action ])) {
1194
            $config = $this->_page_config[ $this->_req_action ];
1195
            // is there a help tour for the current route?  if there is let's setup the tour buttons
1196
            if (isset($this->_help_tour[ $this->_req_action ])) {
1197
                $tb = array();
1198
                $tour_buttons = '<div class="ee-abs-container"><div class="ee-help-tour-restart-buttons">';
1199
                foreach ($this->_help_tour['tours'] as $tour) {
1200
                    // if this is the end tour then we don't need to setup a button
1201
                    if ($tour instanceof EE_Help_Tour_final_stop || ! $tour instanceof EE_Help_Tour) {
1202
                        continue;
1203
                    }
1204
                    $tb[] = '<button id="trigger-tour-'
1205
                            . $tour->get_slug()
1206
                            . '" class="button-primary trigger-ee-help-tour">'
1207
                            . $tour->get_label()
1208
                            . '</button>';
1209
                }
1210
                $tour_buttons .= implode('<br />', $tb);
1211
                $tour_buttons .= '</div></div>';
1212
            }
1213
            // let's see if there is a help_sidebar set for the current route and we'll set that up for usage as well.
1214
            if (is_array($config) && isset($config['help_sidebar'])) {
1215
                // check that the callback given is valid
1216
                if (! method_exists($this, $config['help_sidebar'])) {
1217
                    throw new EE_Error(
1218
                        sprintf(
1219
                            esc_html__(
1220
                                'The _page_config array has a callback set for the "help_sidebar" option.  However the callback given (%s) is not a valid callback.  Doublecheck the spelling and make sure this method exists for the class %s',
1221
                                'event_espresso'
1222
                            ),
1223
                            $config['help_sidebar'],
1224
                            get_class($this)
1225
                        )
1226
                    );
1227
                }
1228
                $content = apply_filters(
1229
                    'FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar',
1230
                    $this->{$config['help_sidebar']}()
1231
                );
1232
                $content .= $tour_buttons; // add help tour buttons.
1233
                // do we have any help tours setup?  Cause if we do we want to add the buttons
1234
                $this->_current_screen->set_help_sidebar($content);
1235
            }
1236
            // if there ARE tour buttons...
1237
            if (! empty($tour_buttons)) {
1238
                // if we DON'T have config help sidebar then we'll just add the tour buttons to the sidebar.
1239
                if (! isset($config['help_sidebar'])) {
1240
                    $this->_current_screen->set_help_sidebar($tour_buttons);
1241
                }
1242
                // handle if no help_tabs are set so the sidebar will still show for the help tour buttons
1243
                if (! isset($config['help_tabs'])) {
1244
                    $_ht['id'] = $this->page_slug;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$_ht was never initialized. Although not strictly required by PHP, it is generally a good practice to add $_ht = 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...
1245
                    $_ht['title'] = esc_html__('Help Tours', 'event_espresso');
1246
                    $_ht['content'] = '<p>'
1247
                                      . esc_html__(
1248
                                          'The buttons to the right allow you to start/restart any help tours available for this page',
1249
                                          'event_espresso'
1250
                                      ) . '</p>';
1251
                    $this->_current_screen->add_help_tab($_ht);
1252
                }
1253
            }
1254
            if (! isset($config['help_tabs'])) {
1255
                return;
1256
            } //no help tabs for this route
1257
            foreach ((array) $config['help_tabs'] as $tab_id => $cfg) {
1258
                // we're here so there ARE help tabs!
1259
                // make sure we've got what we need
1260
                if (! isset($cfg['title'])) {
1261
                    throw new EE_Error(
1262
                        esc_html__(
1263
                            'The _page_config array is not set up properly for help tabs.  It is missing a title',
1264
                            'event_espresso'
1265
                        )
1266
                    );
1267
                }
1268
                if (! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1269
                    throw new EE_Error(
1270
                        esc_html__(
1271
                            'The _page_config array is not setup properly for help tabs. It is missing a either a filename reference, or a callback reference or a content reference so there is no way to know the content for the help tab',
1272
                            'event_espresso'
1273
                        )
1274
                    );
1275
                }
1276
                // first priority goes to content.
1277
                if (! empty($cfg['content'])) {
1278
                    $content = ! empty($cfg['content']) ? $cfg['content'] : null;
1279
                    // second priority goes to filename
1280
                } elseif (! empty($cfg['filename'])) {
1281
                    $file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1282
                    // it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1283
                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1284
                                                             . basename($this->_get_dir())
1285
                                                             . '/help_tabs/'
1286
                                                             . $cfg['filename']
1287
                                                             . '.help_tab.php' : $file_path;
1288
                    // if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1289
                    if (! isset($cfg['callback']) && ! is_readable($file_path)) {
1290
                        EE_Error::add_error(
1291
                            sprintf(
1292
                                esc_html__(
1293
                                    'The filename given for the help tab %s is not a valid file and there is no other configuration for the tab content.  Please check that the string you set for the help tab on this route (%s) is the correct spelling.  The file should be in %s',
1294
                                    'event_espresso'
1295
                                ),
1296
                                $tab_id,
1297
                                key($config),
1298
                                $file_path
1299
                            ),
1300
                            __FILE__,
1301
                            __FUNCTION__,
1302
                            __LINE__
1303
                        );
1304
                        return;
1305
                    }
1306
                    $template_args['admin_page_obj'] = $this;
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...
1307
                    $content = EEH_Template::display_template(
1308
                        $file_path,
1309
                        $template_args,
1310
                        true
1311
                    );
1312
                } else {
1313
                    $content = '';
1314
                }
1315
                // check if callback is valid
1316
                if (empty($content) && (
1317
                        ! isset($cfg['callback']) || ! method_exists($this, $cfg['callback'])
1318
                    )
1319
                ) {
1320
                    EE_Error::add_error(
1321
                        sprintf(
1322
                            esc_html__(
1323
                                'The callback given for a %s help tab on this page does not content OR a corresponding method for generating the content.  Check the spelling or make sure the method is present.',
1324
                                'event_espresso'
1325
                            ),
1326
                            $cfg['title']
1327
                        ),
1328
                        __FILE__,
1329
                        __FUNCTION__,
1330
                        __LINE__
1331
                    );
1332
                    return;
1333
                }
1334
                // setup config array for help tab method
1335
                $id = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1336
                $_ht = array(
1337
                    'id'       => $id,
1338
                    'title'    => $cfg['title'],
1339
                    'callback' => isset($cfg['callback']) && empty($content) ? array($this, $cfg['callback']) : null,
1340
                    'content'  => $content,
1341
                );
1342
                $this->_current_screen->add_help_tab($_ht);
1343
            }
1344
        }
1345
    }
1346
1347
1348
    /**
1349
     * This basically checks loaded $_page_config property to see if there are any help_tours defined.  "help_tours" is
1350
     * an array with properties for setting up usage of the joyride plugin
1351
     *
1352
     * @link   http://zurb.com/playground/jquery-joyride-feature-tour-plugin
1353
     * @see    instructions regarding the format and construction of the "help_tour" array element is found in the
1354
     *         _set_page_config() comments
1355
     * @return void
1356
     * @throws EE_Error
1357
     * @throws InvalidArgumentException
1358
     * @throws InvalidDataTypeException
1359
     * @throws InvalidInterfaceException
1360
     */
1361
    protected function _add_help_tour()
1362
    {
1363
        $tours = array();
1364
        $this->_help_tour = array();
1365
        // exit early if help tours are turned off globally
1366
        if ((defined('EE_DISABLE_HELP_TOURS') && EE_DISABLE_HELP_TOURS)
1367
            || ! EE_Registry::instance()->CFG->admin->help_tour_activation
1368
        ) {
1369
            return;
1370
        }
1371
        // loop through _page_config to find any help_tour defined
1372
        foreach ($this->_page_config as $route => $config) {
1373
            // we're only going to set things up for this route
1374
            if ($route !== $this->_req_action) {
1375
                continue;
1376
            }
1377
            if (isset($config['help_tour'])) {
1378
                foreach ($config['help_tour'] as $tour) {
1379
                    $file_path = $this->_get_dir() . '/help_tours/' . $tour . '.class.php';
1380
                    // let's see if we can get that file...
1381
                    // if not its possible this is a decaf route not set in caffeinated
1382
                    // so lets try and get the caffeinated equivalent
1383
                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1384
                                                             . basename($this->_get_dir())
1385
                                                             . '/help_tours/'
1386
                                                             . $tour
1387
                                                             . '.class.php' : $file_path;
1388
                    // if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1389 View Code Duplication
                    if (! is_readable($file_path)) {
1390
                        EE_Error::add_error(
1391
                            sprintf(
1392
                                esc_html__(
1393
                                    'The file path given for the help tour (%s) is not a valid path.  Please check that the string you set for the help tour on this route (%s) is the correct spelling',
1394
                                    'event_espresso'
1395
                                ),
1396
                                $file_path,
1397
                                $tour
1398
                            ),
1399
                            __FILE__,
1400
                            __FUNCTION__,
1401
                            __LINE__
1402
                        );
1403
                        return;
1404
                    }
1405
                    require_once $file_path;
1406
                    if (! class_exists($tour)) {
1407
                        $error_msg[] = sprintf(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$error_msg was never initialized. Although not strictly required by PHP, it is generally a good practice to add $error_msg = 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...
1408
                            esc_html__('Something went wrong with loading the %s Help Tour Class.', 'event_espresso'),
1409
                            $tour
1410
                        );
1411
                        $error_msg[] = $error_msg[0] . "\r\n"
1412
                                       . sprintf(
1413
                                           esc_html__(
1414
                                               'There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1415
                                               'event_espresso'
1416
                                           ),
1417
                                           $tour,
1418
                                           '<br />',
1419
                                           $tour,
1420
                                           $this->_req_action,
1421
                                           get_class($this)
1422
                                       );
1423
                        throw new EE_Error(implode('||', $error_msg));
1424
                    }
1425
                    $tour_obj = new $tour($this->_is_caf);
1426
                    $tours[] = $tour_obj;
1427
                    $this->_help_tour[ $route ][] = EEH_Template::help_tour_stops_generator($tour_obj);
1428
                }
1429
                // let's inject the end tour stop element common to all pages... this will only get seen once per machine.
1430
                $end_stop_tour = new EE_Help_Tour_final_stop($this->_is_caf);
1431
                $tours[] = $end_stop_tour;
1432
                $this->_help_tour[ $route ][] = EEH_Template::help_tour_stops_generator($end_stop_tour);
1433
            }
1434
        }
1435
1436
        if (! empty($tours)) {
1437
            $this->_help_tour['tours'] = $tours;
1438
        }
1439
        // that's it!  Now that the $_help_tours property is set (or not)
1440
        // the scripts and html should be taken care of automatically.
1441
1442
        /**
1443
         * Allow extending the help tours variable.
1444
         *
1445
         * @param Array $_help_tour The array containing all help tour information to be displayed.
1446
         */
1447
        $this->_help_tour = apply_filters('FHEE__EE_Admin_Page___add_help_tour___help_tour', $this->_help_tour);
1448
    }
1449
1450
1451
    /**
1452
     * This simply sets up any qtips that have been defined in the page config
1453
     *
1454
     * @return void
1455
     */
1456
    protected function _add_qtips()
1457
    {
1458
        if (isset($this->_route_config['qtips'])) {
1459
            $qtips = (array) $this->_route_config['qtips'];
1460
            // load qtip loader
1461
            $path = array(
1462
                $this->_get_dir() . '/qtips/',
1463
                EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1464
            );
1465
            EEH_Qtip_Loader::instance()->register($qtips, $path);
1466
        }
1467
    }
1468
1469
1470
    /**
1471
     * _set_nav_tabs
1472
     * This sets up the nav tabs from the page_routes array.  This method can be overwritten by child classes if you
1473
     * wish to add additional tabs or modify accordingly.
1474
     *
1475
     * @return void
1476
     * @throws InvalidArgumentException
1477
     * @throws InvalidInterfaceException
1478
     * @throws InvalidDataTypeException
1479
     */
1480
    protected function _set_nav_tabs()
1481
    {
1482
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1483
        $i = 0;
1484
        foreach ($this->_page_config as $slug => $config) {
1485
            if (! is_array($config)
1486
                || (
1487
                    is_array($config)
1488
                    && (
1489
                        (isset($config['nav']) && ! $config['nav'])
1490
                        || ! isset($config['nav'])
1491
                    )
1492
                )
1493
            ) {
1494
                continue;
1495
            }
1496
            // no nav tab for this config
1497
            // check for persistent flag
1498
            if ($slug !== $this->_req_action && isset($config['nav']['persistent']) && ! $config['nav']['persistent']) {
1499
                // nav tab is only to appear when route requested.
1500
                continue;
1501
            }
1502
            if (! $this->check_user_access($slug, true)) {
1503
                // no nav tab because current user does not have access.
1504
                continue;
1505
            }
1506
            $css_class = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1507
            $this->_nav_tabs[ $slug ] = array(
1508
                'url'       => isset($config['nav']['url'])
1509
                    ? $config['nav']['url']
1510
                    : self::add_query_args_and_nonce(
1511
                        array('action' => $slug),
1512
                        $this->_admin_base_url
1513
                    ),
1514
                'link_text' => isset($config['nav']['label'])
1515
                    ? $config['nav']['label']
1516
                    : ucwords(
1517
                        str_replace('_', ' ', $slug)
1518
                    ),
1519
                'css_class' => $this->_req_action === $slug ? $css_class . 'nav-tab-active' : $css_class,
1520
                'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1521
            );
1522
            $i++;
1523
        }
1524
        // if $this->_nav_tabs is empty then lets set the default
1525
        if (empty($this->_nav_tabs)) {
1526
            $this->_nav_tabs[ $this->_default_nav_tab_name ] = array(
1527
                'url'       => $this->_admin_base_url,
1528
                'link_text' => ucwords(str_replace('_', ' ', $this->_default_nav_tab_name)),
1529
                'css_class' => 'nav-tab-active',
1530
                'order'     => 10,
1531
            );
1532
        }
1533
        // now let's sort the tabs according to order
1534
        usort($this->_nav_tabs, array($this, '_sort_nav_tabs'));
1535
    }
1536
1537
1538
    /**
1539
     * _set_current_labels
1540
     * This method modifies the _labels property with any optional specific labels indicated in the _page_routes
1541
     * property array
1542
     *
1543
     * @return void
1544
     */
1545
    private function _set_current_labels()
1546
    {
1547
        if (is_array($this->_route_config) && isset($this->_route_config['labels'])) {
1548
            foreach ($this->_route_config['labels'] as $label => $text) {
1549
                if (is_array($text)) {
1550
                    foreach ($text as $sublabel => $subtext) {
1551
                        $this->_labels[ $label ][ $sublabel ] = $subtext;
1552
                    }
1553
                } else {
1554
                    $this->_labels[ $label ] = $text;
1555
                }
1556
            }
1557
        }
1558
    }
1559
1560
1561
    /**
1562
     *        verifies user access for this admin page
1563
     *
1564
     * @param string $route_to_check if present then the capability for the route matching this string is checked.
1565
     * @param bool   $verify_only    Default is FALSE which means if user check fails then wp_die().  Otherwise just
1566
     *                               return false if verify fail.
1567
     * @return bool
1568
     * @throws InvalidArgumentException
1569
     * @throws InvalidDataTypeException
1570
     * @throws InvalidInterfaceException
1571
     */
1572
    public function check_user_access($route_to_check = '', $verify_only = false)
1573
    {
1574
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1575
        $route_to_check = empty($route_to_check) ? $this->_req_action : $route_to_check;
1576
        $capability = ! empty($route_to_check) && isset($this->_page_routes[ $route_to_check ])
1577
                      && is_array(
1578
                          $this->_page_routes[ $route_to_check ]
1579
                      )
1580
                      && ! empty($this->_page_routes[ $route_to_check ]['capability'])
1581
            ? $this->_page_routes[ $route_to_check ]['capability'] : null;
1582
        if (empty($capability) && empty($route_to_check)) {
1583
            $capability = is_array($this->_route) && empty($this->_route['capability']) ? 'manage_options'
1584
                : $this->_route['capability'];
1585
        } else {
1586
            $capability = empty($capability) ? 'manage_options' : $capability;
1587
        }
1588
        $id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1589
        if (! defined('DOING_AJAX')
1590
            && (
1591
                ! function_exists('is_admin')
1592
                || ! EE_Registry::instance()->CAP->current_user_can(
1593
                    $capability,
1594
                    $this->page_slug
1595
                    . '_'
1596
                    . $route_to_check,
1597
                    $id
1598
                )
1599
            )
1600
        ) {
1601
            if ($verify_only) {
1602
                return false;
1603
            }
1604
            if (is_user_logged_in()) {
1605
                wp_die(__('You do not have access to this route.', 'event_espresso'));
1606
            } else {
1607
                return false;
1608
            }
1609
        }
1610
        return true;
1611
    }
1612
1613
1614
    /**
1615
     * admin_init_global
1616
     * This runs all the code that we want executed within the WP admin_init hook.
1617
     * This method executes for ALL EE Admin pages.
1618
     *
1619
     * @return void
1620
     */
1621
    public function admin_init_global()
1622
    {
1623
    }
1624
1625
1626
    /**
1627
     * wp_loaded_global
1628
     * This runs all the code that we want executed within the WP wp_loaded hook.  This method is optional for an
1629
     * EE_Admin page and will execute on every EE Admin Page load
1630
     *
1631
     * @return void
1632
     */
1633
    public function wp_loaded()
1634
    {
1635
    }
1636
1637
1638
    /**
1639
     * admin_notices
1640
     * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply on
1641
     * ALL EE_Admin pages.
1642
     *
1643
     * @return void
1644
     */
1645
    public function admin_notices_global()
1646
    {
1647
        $this->_display_no_javascript_warning();
1648
        $this->_display_espresso_notices();
1649
    }
1650
1651
1652
    public function network_admin_notices_global()
1653
    {
1654
        $this->_display_no_javascript_warning();
1655
        $this->_display_espresso_notices();
1656
    }
1657
1658
1659
    /**
1660
     * admin_footer_scripts_global
1661
     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
1662
     * will apply on ALL EE_Admin pages.
1663
     *
1664
     * @return void
1665
     */
1666
    public function admin_footer_scripts_global()
1667
    {
1668
        $this->_add_admin_page_ajax_loading_img();
1669
        $this->_add_admin_page_overlay();
1670
        // if metaboxes are present we need to add the nonce field
1671
        if (isset($this->_route_config['metaboxes'])
1672
            || isset($this->_route_config['list_table'])
1673
            || (isset($this->_route_config['has_metaboxes']) && $this->_route_config['has_metaboxes'])
1674
        ) {
1675
            wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
1676
            wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
1677
        }
1678
    }
1679
1680
1681
    /**
1682
     * admin_footer_global
1683
     * Anything triggered by the wp 'admin_footer' wp hook should be put in here.
1684
     * This particular method will apply on ALL EE_Admin Pages.
1685
     *
1686
     * @return void
1687
     * @throws InvalidArgumentException
1688
     * @throws InvalidDataTypeException
1689
     * @throws InvalidInterfaceException
1690
     */
1691
    public function admin_footer_global()
1692
    {
1693
        // dialog container for dialog helper
1694
        $d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1695
        $d_cont .= '<div class="ee-notices"></div>';
1696
        $d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1697
        $d_cont .= '</div>';
1698
        echo $d_cont;
1699
        // help tour stuff?
1700
        if (isset($this->_help_tour[ $this->_req_action ])) {
1701
            echo implode('<br />', $this->_help_tour[ $this->_req_action ]);
1702
        }
1703
        // current set timezone for timezone js
1704
        echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1705
    }
1706
1707
1708
    /**
1709
     * This function sees if there is a method for help popup content existing for the given route.  If there is then
1710
     * we'll use the retrieved array to output the content using the template. For child classes: If you want to have
1711
     * help popups then in your templates or your content you set "triggers" for the content using the
1712
     * "_set_help_trigger('help_trigger_id')" where "help_trigger_id" is what you will use later in your custom method
1713
     * for the help popup content on that page. Then in your Child_Admin_Page class you need to define a help popup
1714
     * method for the content in the format "_help_popup_content_{route_name}()"  So if you are setting help content
1715
     * for the
1716
     * 'edit_event' route you should have a method named "_help_popup_content_edit_route". In your defined
1717
     * "help_popup_content_..." method.  You must prepare and return an array in the following format array(
1718
     *    'help_trigger_id' => array(
1719
     *        'title' => esc_html__('localized title for popup', 'event_espresso'),
1720
     *        'content' => esc_html__('localized content for popup', 'event_espresso')
1721
     *    )
1722
     * );
1723
     * Then the EE_Admin_Parent will take care of making sure that is setup properly on the correct route.
1724
     *
1725
     * @param array $help_array
1726
     * @param bool  $display
1727
     * @return string content
1728
     * @throws DomainException
1729
     * @throws EE_Error
1730
     */
1731
    protected function _set_help_popup_content($help_array = array(), $display = false)
1732
    {
1733
        $content = '';
1734
        $help_array = empty($help_array) ? $this->_get_help_content() : $help_array;
1735
        // loop through the array and setup content
1736
        foreach ($help_array as $trigger => $help) {
1737
            // make sure the array is setup properly
1738
            if (! isset($help['title'], $help['content'])) {
1739
                throw new EE_Error(
1740
                    esc_html__(
1741
                        'Does not look like the popup content array has been setup correctly.  Might want to double check that.  Read the comments for the _get_help_popup_content method found in "EE_Admin_Page" class',
1742
                        'event_espresso'
1743
                    )
1744
                );
1745
            }
1746
            // we're good so let'd setup the template vars and then assign parsed template content to our content.
1747
            $template_args = array(
1748
                'help_popup_id'      => $trigger,
1749
                'help_popup_title'   => $help['title'],
1750
                'help_popup_content' => $help['content'],
1751
            );
1752
            $content .= EEH_Template::display_template(
1753
                EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php',
1754
                $template_args,
1755
                true
1756
            );
1757
        }
1758
        if ($display) {
1759
            echo $content;
1760
            return '';
1761
        }
1762
        return $content;
1763
    }
1764
1765
1766
    /**
1767
     * All this does is retrieve the help content array if set by the EE_Admin_Page child
1768
     *
1769
     * @return array properly formatted array for help popup content
1770
     * @throws EE_Error
1771
     */
1772
    private function _get_help_content()
1773
    {
1774
        // what is the method we're looking for?
1775
        $method_name = '_help_popup_content_' . $this->_req_action;
1776
        // if method doesn't exist let's get out.
1777
        if (! method_exists($this, $method_name)) {
1778
            return array();
1779
        }
1780
        // k we're good to go let's retrieve the help array
1781
        $help_array = $this->{$method_name}();
1782
        // make sure we've got an array!
1783
        if (! is_array($help_array)) {
1784
            throw new EE_Error(
1785
                esc_html__(
1786
                    'Something went wrong with help popup content generation. Expecting an array and well, this ain\'t no array bub.',
1787
                    'event_espresso'
1788
                )
1789
            );
1790
        }
1791
        return $help_array;
1792
    }
1793
1794
1795
    /**
1796
     * EE Admin Pages can use this to set a properly formatted trigger for a help popup.
1797
     * By default the trigger html is printed.  Otherwise it can be returned if the $display flag is set "false"
1798
     * See comments made on the _set_help_content method for understanding other parts to the help popup tool.
1799
     *
1800
     * @param string  $trigger_id reference for retrieving the trigger content for the popup
1801
     * @param boolean $display    if false then we return the trigger string
1802
     * @param array   $dimensions an array of dimensions for the box (array(h,w))
1803
     * @return string
1804
     * @throws DomainException
1805
     * @throws EE_Error
1806
     */
1807
    protected function _set_help_trigger($trigger_id, $display = true, $dimensions = array('400', '640'))
1808
    {
1809
        if (defined('DOING_AJAX')) {
1810
            return '';
1811
        }
1812
        // let's check and see if there is any content set for this popup.  If there isn't then we'll include a default title and content so that developers know something needs to be corrected
1813
        $help_array = $this->_get_help_content();
1814
        $help_content = '';
1815
        if (empty($help_array) || ! isset($help_array[ $trigger_id ])) {
1816
            $help_array[ $trigger_id ] = array(
1817
                'title'   => esc_html__('Missing Content', 'event_espresso'),
1818
                'content' => esc_html__(
1819
                    'A trigger has been set that doesn\'t have any corresponding content. Make sure you have set the help content. (see the "_set_help_popup_content" method in the EE_Admin_Page for instructions.)',
1820
                    'event_espresso'
1821
                ),
1822
            );
1823
            $help_content = $this->_set_help_popup_content($help_array);
1824
        }
1825
        // let's setup the trigger
1826
        $content = '<a class="ee-dialog" href="?height='
1827
                   . $dimensions[0]
1828
                   . '&width='
1829
                   . $dimensions[1]
1830
                   . '&inlineId='
1831
                   . $trigger_id
1832
                   . '" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1833
        $content .= $help_content;
1834
        if ($display) {
1835
            echo $content;
1836
            return '';
1837
        }
1838
        return $content;
1839
    }
1840
1841
1842
    /**
1843
     * _add_global_screen_options
1844
     * Add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
1845
     * This particular method will add_screen_options on ALL EE_Admin Pages
1846
     *
1847
     * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
1848
     *         see also WP_Screen object documents...
1849
     * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
1850
     * @abstract
1851
     * @return void
1852
     */
1853
    private function _add_global_screen_options()
1854
    {
1855
    }
1856
1857
1858
    /**
1859
     * _add_global_feature_pointers
1860
     * This method is used for implementing any "feature pointers" (using built-in WP styling js).
1861
     * This particular method will implement feature pointers for ALL EE_Admin pages.
1862
     * Note: this is just a placeholder for now.  Implementation will come down the road
1863
     *
1864
     * @see    WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
1865
     *         extended) also see:
1866
     * @link   http://eamann.com/tech/wordpress-portland/
1867
     * @abstract
1868
     * @return void
1869
     */
1870
    private function _add_global_feature_pointers()
1871
    {
1872
    }
1873
1874
1875
    /**
1876
     * load_global_scripts_styles
1877
     * The scripts and styles enqueued in here will be loaded on every EE Admin page
1878
     *
1879
     * @return void
1880
     * @throws EE_Error
1881
     */
1882
    public function load_global_scripts_styles()
1883
    {
1884
        /** STYLES **/
1885
        // add debugging styles
1886
        if (WP_DEBUG) {
1887
            add_action('admin_head', array($this, 'add_xdebug_style'));
1888
        }
1889
        // register all styles
1890
        wp_register_style(
1891
            'espresso-ui-theme',
1892
            EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1893
            array(),
1894
            EVENT_ESPRESSO_VERSION
1895
        );
1896
        wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', array(), EVENT_ESPRESSO_VERSION);
1897
        // helpers styles
1898
        wp_register_style(
1899
            'ee-text-links',
1900
            EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css',
1901
            array(),
1902
            EVENT_ESPRESSO_VERSION
1903
        );
1904
        /** SCRIPTS **/
1905
        // register all scripts
1906
        wp_register_script(
1907
            'ee-dialog',
1908
            EE_ADMIN_URL . 'assets/ee-dialog-helper.js',
1909
            array('jquery', 'jquery-ui-draggable'),
1910
            EVENT_ESPRESSO_VERSION,
1911
            true
1912
        );
1913
        wp_register_script(
1914
            'ee_admin_js',
1915
            EE_ADMIN_URL . 'assets/ee-admin-page.js',
1916
            array('espresso_core', 'ee-parse-uri', 'ee-dialog'),
1917
            EVENT_ESPRESSO_VERSION,
1918
            true
1919
        );
1920
        wp_register_script(
1921
            'jquery-ui-timepicker-addon',
1922
            EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js',
1923
            array('jquery-ui-datepicker', 'jquery-ui-slider'),
1924
            EVENT_ESPRESSO_VERSION,
1925
            true
1926
        );
1927
        if (EE_Registry::instance()->CFG->admin->help_tour_activation) {
1928
            add_filter('FHEE_load_joyride', '__return_true');
1929
        }
1930
        // script for sorting tables
1931
        wp_register_script(
1932
            'espresso_ajax_table_sorting',
1933
            EE_ADMIN_URL . 'assets/espresso_ajax_table_sorting.js',
1934
            array('ee_admin_js', 'jquery-ui-sortable'),
1935
            EVENT_ESPRESSO_VERSION,
1936
            true
1937
        );
1938
        // script for parsing uri's
1939
        wp_register_script(
1940
            'ee-parse-uri',
1941
            EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js',
1942
            array(),
1943
            EVENT_ESPRESSO_VERSION,
1944
            true
1945
        );
1946
        // and parsing associative serialized form elements
1947
        wp_register_script(
1948
            'ee-serialize-full-array',
1949
            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js',
1950
            array('jquery'),
1951
            EVENT_ESPRESSO_VERSION,
1952
            true
1953
        );
1954
        // helpers scripts
1955
        wp_register_script(
1956
            'ee-text-links',
1957
            EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js',
1958
            array('jquery'),
1959
            EVENT_ESPRESSO_VERSION,
1960
            true
1961
        );
1962
        wp_register_script(
1963
            'ee-moment-core',
1964
            EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js',
1965
            array(),
1966
            EVENT_ESPRESSO_VERSION,
1967
            true
1968
        );
1969
        wp_register_script(
1970
            'ee-moment',
1971
            EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js',
1972
            array('ee-moment-core'),
1973
            EVENT_ESPRESSO_VERSION,
1974
            true
1975
        );
1976
        wp_register_script(
1977
            'ee-datepicker',
1978
            EE_ADMIN_URL . 'assets/ee-datepicker.js',
1979
            array('jquery-ui-timepicker-addon', 'ee-moment'),
1980
            EVENT_ESPRESSO_VERSION,
1981
            true
1982
        );
1983
        // google charts
1984
        wp_register_script(
1985
            'google-charts',
1986
            'https://www.gstatic.com/charts/loader.js',
1987
            array(),
1988
            EVENT_ESPRESSO_VERSION
1989
        );
1990
        // ENQUEUE ALL BASICS BY DEFAULT
1991
        wp_enqueue_style('ee-admin-css');
1992
        wp_enqueue_script('ee_admin_js');
1993
        wp_enqueue_script('ee-accounting');
1994
        wp_enqueue_script('jquery-validate');
1995
        // taking care of metaboxes
1996
        if (empty($this->_cpt_route)
1997
            && (isset($this->_route_config['metaboxes']) || isset($this->_route_config['has_metaboxes']))
1998
        ) {
1999
            wp_enqueue_script('dashboard');
2000
        }
2001
        // LOCALIZED DATA
2002
        // localize script for ajax lazy loading
2003
        $lazy_loader_container_ids = apply_filters(
2004
            'FHEE__EE_Admin_Page_Core__load_global_scripts_styles__loader_containers',
2005
            array('espresso_news_post_box_content')
2006
        );
2007
        wp_localize_script('ee_admin_js', 'eeLazyLoadingContainers', $lazy_loader_container_ids);
2008
        /**
2009
         * help tour stuff
2010
         */
2011
        if (! empty($this->_help_tour)) {
2012
            // register the js for kicking things off
2013
            wp_enqueue_script(
2014
                'ee-help-tour',
2015
                EE_ADMIN_URL . 'assets/ee-help-tour.js',
2016
                array('jquery-joyride'),
2017
                EVENT_ESPRESSO_VERSION,
2018
                true
2019
            );
2020
            $tours = array();
2021
            // setup tours for the js tour object
2022
            foreach ($this->_help_tour['tours'] as $tour) {
2023
                if ($tour instanceof EE_Help_Tour) {
2024
                    $tours[] = array(
2025
                        'id'      => $tour->get_slug(),
2026
                        'options' => $tour->get_options(),
2027
                    );
2028
                }
2029
            }
2030
            wp_localize_script('ee-help-tour', 'EE_HELP_TOUR', array('tours' => $tours));
2031
            // admin_footer_global will take care of making sure our help_tour skeleton gets printed via the info stored in $this->_help_tour
2032
        }
2033
    }
2034
2035
2036
    /**
2037
     *        admin_footer_scripts_eei18n_js_strings
2038
     *
2039
     * @return        void
2040
     */
2041
    public function admin_footer_scripts_eei18n_js_strings()
2042
    {
2043
        EE_Registry::$i18n_js_strings['ajax_url'] = WP_AJAX_URL;
2044
        EE_Registry::$i18n_js_strings['confirm_delete'] = esc_html__(
2045
            'Are you absolutely sure you want to delete this item?\nThis action will delete ALL DATA associated with this item!!!\nThis can NOT be undone!!!',
2046
            'event_espresso'
2047
        );
2048
        EE_Registry::$i18n_js_strings['January'] = esc_html__('January', 'event_espresso');
2049
        EE_Registry::$i18n_js_strings['February'] = esc_html__('February', 'event_espresso');
2050
        EE_Registry::$i18n_js_strings['March'] = esc_html__('March', 'event_espresso');
2051
        EE_Registry::$i18n_js_strings['April'] = esc_html__('April', 'event_espresso');
2052
        EE_Registry::$i18n_js_strings['May'] = esc_html__('May', 'event_espresso');
2053
        EE_Registry::$i18n_js_strings['June'] = esc_html__('June', 'event_espresso');
2054
        EE_Registry::$i18n_js_strings['July'] = esc_html__('July', 'event_espresso');
2055
        EE_Registry::$i18n_js_strings['August'] = esc_html__('August', 'event_espresso');
2056
        EE_Registry::$i18n_js_strings['September'] = esc_html__('September', 'event_espresso');
2057
        EE_Registry::$i18n_js_strings['October'] = esc_html__('October', 'event_espresso');
2058
        EE_Registry::$i18n_js_strings['November'] = esc_html__('November', 'event_espresso');
2059
        EE_Registry::$i18n_js_strings['December'] = esc_html__('December', 'event_espresso');
2060
        EE_Registry::$i18n_js_strings['Jan'] = esc_html__('Jan', 'event_espresso');
2061
        EE_Registry::$i18n_js_strings['Feb'] = esc_html__('Feb', 'event_espresso');
2062
        EE_Registry::$i18n_js_strings['Mar'] = esc_html__('Mar', 'event_espresso');
2063
        EE_Registry::$i18n_js_strings['Apr'] = esc_html__('Apr', 'event_espresso');
2064
        EE_Registry::$i18n_js_strings['May'] = esc_html__('May', 'event_espresso');
2065
        EE_Registry::$i18n_js_strings['Jun'] = esc_html__('Jun', 'event_espresso');
2066
        EE_Registry::$i18n_js_strings['Jul'] = esc_html__('Jul', 'event_espresso');
2067
        EE_Registry::$i18n_js_strings['Aug'] = esc_html__('Aug', 'event_espresso');
2068
        EE_Registry::$i18n_js_strings['Sep'] = esc_html__('Sep', 'event_espresso');
2069
        EE_Registry::$i18n_js_strings['Oct'] = esc_html__('Oct', 'event_espresso');
2070
        EE_Registry::$i18n_js_strings['Nov'] = esc_html__('Nov', 'event_espresso');
2071
        EE_Registry::$i18n_js_strings['Dec'] = esc_html__('Dec', 'event_espresso');
2072
        EE_Registry::$i18n_js_strings['Sunday'] = esc_html__('Sunday', 'event_espresso');
2073
        EE_Registry::$i18n_js_strings['Monday'] = esc_html__('Monday', 'event_espresso');
2074
        EE_Registry::$i18n_js_strings['Tuesday'] = esc_html__('Tuesday', 'event_espresso');
2075
        EE_Registry::$i18n_js_strings['Wednesday'] = esc_html__('Wednesday', 'event_espresso');
2076
        EE_Registry::$i18n_js_strings['Thursday'] = esc_html__('Thursday', 'event_espresso');
2077
        EE_Registry::$i18n_js_strings['Friday'] = esc_html__('Friday', 'event_espresso');
2078
        EE_Registry::$i18n_js_strings['Saturday'] = esc_html__('Saturday', 'event_espresso');
2079
        EE_Registry::$i18n_js_strings['Sun'] = esc_html__('Sun', 'event_espresso');
2080
        EE_Registry::$i18n_js_strings['Mon'] = esc_html__('Mon', 'event_espresso');
2081
        EE_Registry::$i18n_js_strings['Tue'] = esc_html__('Tue', 'event_espresso');
2082
        EE_Registry::$i18n_js_strings['Wed'] = esc_html__('Wed', 'event_espresso');
2083
        EE_Registry::$i18n_js_strings['Thu'] = esc_html__('Thu', 'event_espresso');
2084
        EE_Registry::$i18n_js_strings['Fri'] = esc_html__('Fri', 'event_espresso');
2085
        EE_Registry::$i18n_js_strings['Sat'] = esc_html__('Sat', 'event_espresso');
2086
    }
2087
2088
2089
    /**
2090
     *        load enhanced xdebug styles for ppl with failing eyesight
2091
     *
2092
     * @return        void
2093
     */
2094
    public function add_xdebug_style()
2095
    {
2096
        echo '<style>.xdebug-error { font-size:1.5em; }</style>';
2097
    }
2098
2099
2100
    /************************/
2101
    /** LIST TABLE METHODS **/
2102
    /************************/
2103
    /**
2104
     * this sets up the list table if the current view requires it.
2105
     *
2106
     * @return void
2107
     * @throws EE_Error
2108
     * @throws InvalidArgumentException
2109
     * @throws InvalidDataTypeException
2110
     * @throws InvalidInterfaceException
2111
     */
2112
    protected function _set_list_table()
2113
    {
2114
        // first is this a list_table view?
2115
        if (! isset($this->_route_config['list_table'])) {
2116
            return;
2117
        } //not a list_table view so get out.
2118
        // list table functions are per view specific (because some admin pages might have more than one list table!)
2119
        $list_table_view = '_set_list_table_views_' . $this->_req_action;
2120
        if (! method_exists($this, $list_table_view) || $this->{$list_table_view}() === false) {
2121
            // user error msg
2122
            $error_msg = esc_html__(
2123
                'An error occurred. The requested list table views could not be found.',
2124
                'event_espresso'
2125
            );
2126
            // developer error msg
2127
            $error_msg .= '||'
2128
                          . sprintf(
2129
                              esc_html__(
2130
                                  'List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.',
2131
                                  'event_espresso'
2132
                              ),
2133
                              $this->_req_action,
2134
                              $list_table_view
2135
                          );
2136
            throw new EE_Error($error_msg);
2137
        }
2138
        // let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
2139
        $this->_views = apply_filters(
2140
            'FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action,
2141
            $this->_views
2142
        );
2143
        $this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
2144
        $this->_views = apply_filters('FHEE_list_table_views', $this->_views);
2145
        $this->_set_list_table_view();
2146
        $this->_set_list_table_object();
2147
    }
2148
2149
2150
    /**
2151
     * set current view for List Table
2152
     *
2153
     * @return void
2154
     */
2155
    protected function _set_list_table_view()
2156
    {
2157
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2158
        // looking at active items or dumpster diving ?
2159
        if (! isset($this->_req_data['status']) || ! array_key_exists($this->_req_data['status'], $this->_views)) {
2160
            $this->_view = isset($this->_views['in_use']) ? 'in_use' : 'all';
2161
        } else {
2162
            $this->_view = sanitize_key($this->_req_data['status']);
2163
        }
2164
    }
2165
2166
2167
    /**
2168
     * _set_list_table_object
2169
     * WP_List_Table objects need to be loaded fairly early so automatic stuff WP does is taken care of.
2170
     *
2171
     * @throws InvalidInterfaceException
2172
     * @throws InvalidArgumentException
2173
     * @throws InvalidDataTypeException
2174
     * @throws EE_Error
2175
     * @throws InvalidInterfaceException
2176
     */
2177
    protected function _set_list_table_object()
2178
    {
2179
        if (isset($this->_route_config['list_table'])) {
2180
            if (! class_exists($this->_route_config['list_table'])) {
2181
                throw new EE_Error(
2182
                    sprintf(
2183
                        esc_html__(
2184
                            'The %s class defined for the list table does not exist.  Please check the spelling of the class ref in the $_page_config property on %s.',
2185
                            'event_espresso'
2186
                        ),
2187
                        $this->_route_config['list_table'],
2188
                        get_class($this)
2189
                    )
2190
                );
2191
            }
2192
            $this->_list_table_object = $this->loader->getShared(
2193
                $this->_route_config['list_table'],
2194
                array($this)
2195
            );
2196
        }
2197
    }
2198
2199
2200
    /**
2201
     * get_list_table_view_RLs - get it? View RL ?? VU-RL???  URL ??
2202
     *
2203
     * @param array $extra_query_args                     Optional. An array of extra query args to add to the generated
2204
     *                                                    urls.  The array should be indexed by the view it is being
2205
     *                                                    added to.
2206
     * @return array
2207
     */
2208
    public function get_list_table_view_RLs($extra_query_args = array())
2209
    {
2210
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2211
        if (empty($this->_views)) {
2212
            $this->_views = array();
2213
        }
2214
        // cycle thru views
2215
        foreach ($this->_views as $key => $view) {
2216
            $query_args = array();
2217
            // check for current view
2218
            $this->_views[ $key ]['class'] = $this->_view === $view['slug'] ? 'current' : '';
2219
            $query_args['action'] = $this->_req_action;
2220
            $query_args[ $this->_req_action . '_nonce' ] = wp_create_nonce($query_args['action'] . '_nonce');
2221
            $query_args['status'] = $view['slug'];
2222
            // merge any other arguments sent in.
2223
            if (isset($extra_query_args[ $view['slug'] ])) {
2224
                foreach ($extra_query_args[ $view['slug'] ] as $extra_query_arg) {
2225
                    $query_args[] = $extra_query_arg;
2226
                }
2227
            }
2228
            $this->_views[ $key ]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2229
        }
2230
        return $this->_views;
2231
    }
2232
2233
2234
    /**
2235
     * _entries_per_page_dropdown
2236
     * generates a drop down box for selecting the number of visible rows in an admin page list table
2237
     *
2238
     * @todo   : Note: ideally this should be added to the screen options dropdown as that would be consistent with how
2239
     *         WP does it.
2240
     * @param int $max_entries total number of rows in the table
2241
     * @return string
2242
     */
2243
    protected function _entries_per_page_dropdown($max_entries = 0)
2244
    {
2245
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2246
        $values = array(10, 25, 50, 100);
2247
        $per_page = (! empty($this->_req_data['per_page'])) ? absint($this->_req_data['per_page']) : 10;
2248
        if ($max_entries) {
2249
            $values[] = $max_entries;
2250
            sort($values);
2251
        }
2252
        $entries_per_page_dropdown = '
2253
			<div id="entries-per-page-dv" class="alignleft actions">
2254
				<label class="hide-if-no-js">
2255
					Show
2256
					<select id="entries-per-page-slct" name="entries-per-page-slct">';
2257
        foreach ($values as $value) {
2258
            if ($value < $max_entries) {
2259
                $selected = $value === $per_page ? ' selected="' . $per_page . '"' : '';
2260
                $entries_per_page_dropdown .= '
2261
						<option value="' . $value . '"' . $selected . '>' . $value . '&nbsp;&nbsp;</option>';
2262
            }
2263
        }
2264
        $selected = $max_entries === $per_page ? ' selected="' . $per_page . '"' : '';
2265
        $entries_per_page_dropdown .= '
2266
						<option value="' . $max_entries . '"' . $selected . '>All&nbsp;&nbsp;</option>';
2267
        $entries_per_page_dropdown .= '
2268
					</select>
2269
					entries
2270
				</label>
2271
				<input id="entries-per-page-btn" class="button-secondary" type="submit" value="Go" >
2272
			</div>
2273
		';
2274
        return $entries_per_page_dropdown;
2275
    }
2276
2277
2278
    /**
2279
     *        _set_search_attributes
2280
     *
2281
     * @return        void
2282
     */
2283
    public function _set_search_attributes()
2284
    {
2285
        $this->_template_args['search']['btn_label'] = sprintf(
2286
            esc_html__('Search %s', 'event_espresso'),
2287
            empty($this->_search_btn_label) ? $this->page_label
2288
                : $this->_search_btn_label
2289
        );
2290
        $this->_template_args['search']['callback'] = 'search_' . $this->page_slug;
2291
    }
2292
2293
2294
2295
    /*** END LIST TABLE METHODS **/
2296
2297
2298
    /**
2299
     * _add_registered_metaboxes
2300
     *  this loads any registered metaboxes via the 'metaboxes' index in the _page_config property array.
2301
     *
2302
     * @link   http://codex.wordpress.org/Function_Reference/add_meta_box
2303
     * @return void
2304
     * @throws EE_Error
2305
     */
2306
    private function _add_registered_meta_boxes()
2307
    {
2308
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2309
        // we only add meta boxes if the page_route calls for it
2310
        if (is_array($this->_route_config) && isset($this->_route_config['metaboxes'])
2311
            && is_array(
2312
                $this->_route_config['metaboxes']
2313
            )
2314
        ) {
2315
            // this simply loops through the callbacks provided
2316
            // and checks if there is a corresponding callback registered by the child
2317
            // if there is then we go ahead and process the metabox loader.
2318
            foreach ($this->_route_config['metaboxes'] as $metabox_callback) {
2319
                // first check for Closures
2320
                if ($metabox_callback instanceof Closure) {
2321
                    $result = $metabox_callback();
2322
                } elseif (is_array($metabox_callback) && isset($metabox_callback[0], $metabox_callback[1])) {
2323
                    $result = call_user_func(array($metabox_callback[0], $metabox_callback[1]));
2324
                } else {
2325
                    $result = $this->{$metabox_callback}();
2326
                }
2327
                if ($result === false) {
2328
                    // user error msg
2329
                    $error_msg = esc_html__(
2330
                        'An error occurred. The  requested metabox could not be found.',
2331
                        'event_espresso'
2332
                    );
2333
                    // developer error msg
2334
                    $error_msg .= '||'
2335
                                  . sprintf(
2336
                                      esc_html__(
2337
                                          'The metabox with the string "%s" could not be called. Check that the spelling for method names and actions in the "_page_config[\'metaboxes\']" array are all correct.',
2338
                                          'event_espresso'
2339
                                      ),
2340
                                      $metabox_callback
2341
                                  );
2342
                    throw new EE_Error($error_msg);
2343
                }
2344
            }
2345
        }
2346
    }
2347
2348
2349
    /**
2350
     * _add_screen_columns
2351
     * This will check the _page_config array and if there is "columns" key index indicated, we'll set the template as
2352
     * the dynamic column template and we'll setup the column options for the page.
2353
     *
2354
     * @return void
2355
     */
2356
    private function _add_screen_columns()
2357
    {
2358
        if (is_array($this->_route_config)
2359
            && isset($this->_route_config['columns'])
2360
            && is_array($this->_route_config['columns'])
2361
            && count($this->_route_config['columns']) === 2
2362
        ) {
2363
            add_screen_option(
2364
                'layout_columns',
2365
                array(
2366
                    'max'     => (int) $this->_route_config['columns'][0],
2367
                    'default' => (int) $this->_route_config['columns'][1],
2368
                )
2369
            );
2370
            $this->_template_args['num_columns'] = $this->_route_config['columns'][0];
2371
            $screen_id = $this->_current_screen->id;
2372
            $screen_columns = (int) get_user_option("screen_layout_{$screen_id}");
2373
            $total_columns = ! empty($screen_columns)
2374
                ? $screen_columns
2375
                : $this->_route_config['columns'][1];
2376
            $this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
2377
            $this->_template_args['current_page'] = $this->_wp_page_slug;
2378
            $this->_template_args['screen'] = $this->_current_screen;
2379
            $this->_column_template_path = EE_ADMIN_TEMPLATE
2380
                                           . 'admin_details_metabox_column_wrapper.template.php';
2381
            // finally if we don't have has_metaboxes set in the route config
2382
            // let's make sure it IS set other wise the necessary hidden fields for this won't be loaded.
2383
            $this->_route_config['has_metaboxes'] = true;
2384
        }
2385
    }
2386
2387
2388
2389
    /** GLOBALLY AVAILABLE METABOXES **/
2390
2391
2392
    /**
2393
     * In this section we put any globally available EE metaboxes for all EE Admin pages.  They are called by simply
2394
     * referencing the callback in the _page_config array property.  This way you can be very specific about what pages
2395
     * these get loaded on.
2396
     */
2397 View Code Duplication
    private function _espresso_news_post_box()
2398
    {
2399
        $news_box_title = apply_filters(
2400
            'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2401
            esc_html__('New @ Event Espresso', 'event_espresso')
2402
        );
2403
        add_meta_box(
2404
            'espresso_news_post_box',
2405
            $news_box_title,
2406
            array(
2407
                $this,
2408
                'espresso_news_post_box',
2409
            ),
2410
            $this->_wp_page_slug,
2411
            'side'
2412
        );
2413
    }
2414
2415
2416
    /**
2417
     * Code for setting up espresso ratings request metabox.
2418
     */
2419
    protected function _espresso_ratings_request()
2420
    {
2421
        if (! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
2422
            return;
2423
        }
2424
        $ratings_box_title = apply_filters(
2425
            'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2426
            esc_html__('Keep Event Espresso Decaf Free', 'event_espresso')
2427
        );
2428
        add_meta_box(
2429
            'espresso_ratings_request',
2430
            $ratings_box_title,
2431
            array(
2432
                $this,
2433
                'espresso_ratings_request',
2434
            ),
2435
            $this->_wp_page_slug,
2436
            'side'
2437
        );
2438
    }
2439
2440
2441
    /**
2442
     * Code for setting up espresso ratings request metabox content.
2443
     *
2444
     * @throws DomainException
2445
     */
2446
    public function espresso_ratings_request()
2447
    {
2448
        EEH_Template::display_template(EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php');
2449
    }
2450
2451
2452
    public static function cached_rss_display($rss_id, $url)
2453
    {
2454
        $loading = '<p class="widget-loading hide-if-no-js">'
2455
                   . __('Loading&#8230;', 'event_espresso')
2456
                   . '</p><p class="hide-if-js">'
2457
                   . esc_html__('This widget requires JavaScript.', 'event_espresso')
2458
                   . '</p>';
2459
        $pre = '<div class="espresso-rss-display">' . "\n\t";
2460
        $pre .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
2461
        $post = '</div>' . "\n";
2462
        $cache_key = 'ee_rss_' . md5($rss_id);
2463
        $output = get_transient($cache_key);
2464
        if ($output !== false) {
2465
            echo $pre . $output . $post;
2466
            return true;
2467
        }
2468
        if (! (defined('DOING_AJAX') && DOING_AJAX)) {
2469
            echo $pre . $loading . $post;
2470
            return false;
2471
        }
2472
        ob_start();
2473
        wp_widget_rss_output($url, array('show_date' => 0, 'items' => 5));
2474
        set_transient($cache_key, ob_get_flush(), 12 * HOUR_IN_SECONDS);
2475
        return true;
2476
    }
2477
2478
2479
    public function espresso_news_post_box()
2480
    {
2481
        ?>
2482
        <div class="padding">
2483
            <div id="espresso_news_post_box_content" class="infolinks">
2484
                <?php
2485
                // Get RSS Feed(s)
2486
                self::cached_rss_display(
2487
                    'espresso_news_post_box_content',
2488
                    urlencode(
2489
                        apply_filters(
2490
                            'FHEE__EE_Admin_Page__espresso_news_post_box__feed_url',
2491
                            'http://eventespresso.com/feed/'
2492
                        )
2493
                    )
2494
                );
2495
                ?>
2496
            </div>
2497
            <?php do_action('AHEE__EE_Admin_Page__espresso_news_post_box__after_content'); ?>
2498
        </div>
2499
        <?php
2500
    }
2501
2502
2503
    private function _espresso_links_post_box()
2504
    {
2505
        // Hiding until we actually have content to put in here...
2506
        // add_meta_box('espresso_links_post_box', esc_html__('Helpful Plugin Links', 'event_espresso'), array( $this, 'espresso_links_post_box'), $this->_wp_page_slug, 'side');
2507
    }
2508
2509
2510
    public function espresso_links_post_box()
2511
    {
2512
        // Hiding until we actually have content to put in here...
2513
        // EEH_Template::display_template(
2514
        //     EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_links.template.php'
2515
        // );
2516
    }
2517
2518
2519 View Code Duplication
    protected function _espresso_sponsors_post_box()
2520
    {
2521
        if (apply_filters('FHEE_show_sponsors_meta_box', true)) {
2522
            add_meta_box(
2523
                'espresso_sponsors_post_box',
2524
                esc_html__('Event Espresso Highlights', 'event_espresso'),
2525
                array($this, 'espresso_sponsors_post_box'),
2526
                $this->_wp_page_slug,
2527
                'side'
2528
            );
2529
        }
2530
    }
2531
2532
2533
    public function espresso_sponsors_post_box()
2534
    {
2535
        EEH_Template::display_template(
2536
            EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php'
2537
        );
2538
    }
2539
2540
2541
    private function _publish_post_box()
2542
    {
2543
        $meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2544
        // if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array
2545
        // then we'll use that for the metabox label.
2546
        // Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2547
        if (! empty($this->_labels['publishbox'])) {
2548
            $box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][ $this->_req_action ]
2549
                : $this->_labels['publishbox'];
2550
        } else {
2551
            $box_label = esc_html__('Publish', 'event_espresso');
2552
        }
2553
        $box_label = apply_filters(
2554
            'FHEE__EE_Admin_Page___publish_post_box__box_label',
2555
            $box_label,
2556
            $this->_req_action,
2557
            $this
2558
        );
2559
        add_meta_box(
2560
            $meta_box_ref,
2561
            $box_label,
2562
            array($this, 'editor_overview'),
2563
            $this->_current_screen->id,
2564
            'side',
2565
            'high'
2566
        );
2567
    }
2568
2569
2570
    public function editor_overview()
2571
    {
2572
        // if we have extra content set let's add it in if not make sure its empty
2573
        $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2574
            ? $this->_template_args['publish_box_extra_content']
2575
            : '';
2576
        echo EEH_Template::display_template(
2577
            EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php',
2578
            $this->_template_args,
2579
            true
2580
        );
2581
    }
2582
2583
2584
    /** end of globally available metaboxes section **/
2585
2586
2587
    /**
2588
     * Public wrapper for the protected method.  Allows plugins/addons to externally call the
2589
     * protected method.
2590
     *
2591
     * @see   $this->_set_publish_post_box_vars for param details
2592
     * @since 4.6.0
2593
     * @param string $name
2594
     * @param int    $id
2595
     * @param bool   $delete
2596
     * @param string $save_close_redirect_URL
2597
     * @param bool   $both_btns
2598
     * @throws EE_Error
2599
     * @throws InvalidArgumentException
2600
     * @throws InvalidDataTypeException
2601
     * @throws InvalidInterfaceException
2602
     */
2603
    public function set_publish_post_box_vars(
2604
        $name = '',
2605
        $id = 0,
2606
        $delete = false,
2607
        $save_close_redirect_URL = '',
2608
        $both_btns = true
2609
    ) {
2610
        $this->_set_publish_post_box_vars(
2611
            $name,
2612
            $id,
2613
            $delete,
2614
            $save_close_redirect_URL,
2615
            $both_btns
2616
        );
2617
    }
2618
2619
2620
    /**
2621
     * Sets the _template_args arguments used by the _publish_post_box shortcut
2622
     * Note: currently there is no validation for this.  However if you want the delete button, the
2623
     * save, and save and close buttons to work properly, then you will want to include a
2624
     * values for the name and id arguments.
2625
     *
2626
     * @todo  Add in validation for name/id arguments.
2627
     * @param    string  $name                    key used for the action ID (i.e. event_id)
2628
     * @param    int     $id                      id attached to the item published
2629
     * @param    string  $delete                  page route callback for the delete action
2630
     * @param    string  $save_close_redirect_URL custom URL to redirect to after Save & Close has been completed
2631
     * @param    boolean $both_btns               whether to display BOTH the "Save & Close" and "Save" buttons or just
2632
     *                                            the Save button
2633
     * @throws EE_Error
2634
     * @throws InvalidArgumentException
2635
     * @throws InvalidDataTypeException
2636
     * @throws InvalidInterfaceException
2637
     */
2638
    protected function _set_publish_post_box_vars(
2639
        $name = '',
2640
        $id = 0,
2641
        $delete = '',
2642
        $save_close_redirect_URL = '',
2643
        $both_btns = true
2644
    ) {
2645
        // if Save & Close, use a custom redirect URL or default to the main page?
2646
        $save_close_redirect_URL = ! empty($save_close_redirect_URL)
2647
            ? $save_close_redirect_URL
2648
            : $this->_admin_base_url;
2649
        // create the Save & Close and Save buttons
2650
        $this->_set_save_buttons($both_btns, array(), array(), $save_close_redirect_URL);
2651
        // if we have extra content set let's add it in if not make sure its empty
2652
        $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2653
            ? $this->_template_args['publish_box_extra_content']
2654
            : '';
2655
        if ($delete && ! empty($id)) {
2656
            // make sure we have a default if just true is sent.
2657
            $delete = ! empty($delete) ? $delete : 'delete';
2658
            $delete_link_args = array($name => $id);
2659
            $delete = $this->get_action_link_or_button(
2660
                $delete,
2661
                $delete,
2662
                $delete_link_args,
2663
                'submitdelete deletion'
2664
            );
2665
        }
2666
        $this->_template_args['publish_delete_link'] = ! empty($id) ? $delete : '';
2667
        if (! empty($name) && ! empty($id)) {
2668
            $hidden_field_arr[ $name ] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$hidden_field_arr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $hidden_field_arr = 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...
2669
                'type'  => 'hidden',
2670
                'value' => $id,
2671
            );
2672
            $hf = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2673
        } else {
2674
            $hf = '';
2675
        }
2676
        // add hidden field
2677
        $this->_template_args['publish_hidden_fields'] = is_array($hf) && ! empty($name)
2678
            ? $hf[ $name ]['field']
2679
            : $hf;
2680
    }
2681
2682
2683
    /**
2684
     * displays an error message to ppl who have javascript disabled
2685
     *
2686
     * @return void
2687
     */
2688
    private function _display_no_javascript_warning()
2689
    {
2690
        ?>
2691
        <noscript>
2692
            <div id="no-js-message" class="error">
2693
                <p style="font-size:1.3em;">
2694
                    <span style="color:red;"><?php esc_html_e('Warning!', 'event_espresso'); ?></span>
2695
                    <?php esc_html_e(
2696
                        'Javascript is currently turned off for your browser. Javascript must be enabled in order for all of the features on this page to function properly. Please turn your javascript back on.',
2697
                        'event_espresso'
2698
                    ); ?>
2699
                </p>
2700
            </div>
2701
        </noscript>
2702
        <?php
2703
    }
2704
2705
2706
    /**
2707
     * displays espresso success and/or error notices
2708
     *
2709
     * @return void
2710
     */
2711
    private function _display_espresso_notices()
2712
    {
2713
        $notices = $this->_get_transient(true);
2714
        echo stripslashes($notices);
2715
    }
2716
2717
2718
    /**
2719
     * spinny things pacify the masses
2720
     *
2721
     * @return void
2722
     */
2723
    protected function _add_admin_page_ajax_loading_img()
2724
    {
2725
        ?>
2726
        <div id="espresso-ajax-loading" class="ajax-loading-grey">
2727
            <span class="ee-spinner ee-spin"></span><span class="hidden"><?php
2728
                esc_html_e('loading...', 'event_espresso'); ?></span>
2729
        </div>
2730
        <?php
2731
    }
2732
2733
2734
    /**
2735
     * add admin page overlay for modal boxes
2736
     *
2737
     * @return void
2738
     */
2739
    protected function _add_admin_page_overlay()
2740
    {
2741
        ?>
2742
        <div id="espresso-admin-page-overlay-dv" class=""></div>
2743
        <?php
2744
    }
2745
2746
2747
    /**
2748
     * facade for add_meta_box
2749
     *
2750
     * @param string  $action        where the metabox get's displayed
2751
     * @param string  $title         Title of Metabox (output in metabox header)
2752
     * @param string  $callback      If not empty and $create_fun is set to false then we'll use a custom callback
2753
     *                               instead of the one created in here.
2754
     * @param array   $callback_args an array of args supplied for the metabox
2755
     * @param string  $column        what metabox column
2756
     * @param string  $priority      give this metabox a priority (using accepted priorities for wp meta boxes)
2757
     * @param boolean $create_func   default is true.  Basically we can say we don't WANT to have the runtime function
2758
     *                               created but just set our own callback for wp's add_meta_box.
2759
     * @throws DomainException
2760
     */
2761
    public function _add_admin_page_meta_box(
2762
        $action,
2763
        $title,
2764
        $callback,
2765
        $callback_args,
2766
        $column = 'normal',
2767
        $priority = 'high',
2768
        $create_func = true
2769
    ) {
2770
        do_action('AHEE_log', __FILE__, __FUNCTION__, $callback);
2771
        // if we have empty callback args and we want to automatically create the metabox callback then we need to make sure the callback args are generated.
2772
        if (empty($callback_args) && $create_func) {
2773
            $callback_args = array(
2774
                'template_path' => $this->_template_path,
2775
                'template_args' => $this->_template_args,
2776
            );
2777
        }
2778
        // if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2779
        $call_back_func = $create_func
2780
            ? static function ($post, $metabox) {
2781
                do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2782
                echo EEH_Template::display_template(
2783
                    $metabox['args']['template_path'],
2784
                    $metabox['args']['template_args'],
2785
                    true
2786
                );
2787
            }
2788
            : $callback;
2789
        add_meta_box(
2790
            str_replace('_', '-', $action) . '-mbox',
2791
            $title,
2792
            $call_back_func,
2793
            $this->_wp_page_slug,
2794
            $column,
2795
            $priority,
2796
            $callback_args
2797
        );
2798
    }
2799
2800
2801
    /**
2802
     * generates HTML wrapper for and admin details page that contains metaboxes in columns
2803
     *
2804
     * @throws DomainException
2805
     * @throws EE_Error
2806
     * @throws InvalidArgumentException
2807
     * @throws InvalidDataTypeException
2808
     * @throws InvalidInterfaceException
2809
     */
2810
    public function display_admin_page_with_metabox_columns()
2811
    {
2812
        $this->_template_args['post_body_content'] = $this->_template_args['admin_page_content'];
2813
        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2814
            $this->_column_template_path,
2815
            $this->_template_args,
2816
            true
2817
        );
2818
        // the final wrapper
2819
        $this->admin_page_wrapper();
2820
    }
2821
2822
2823
    /**
2824
     * generates  HTML wrapper for an admin details page
2825
     *
2826
     * @return void
2827
     * @throws DomainException
2828
     * @throws EE_Error
2829
     * @throws InvalidArgumentException
2830
     * @throws InvalidDataTypeException
2831
     * @throws InvalidInterfaceException
2832
     */
2833
    public function display_admin_page_with_sidebar()
2834
    {
2835
        $this->_display_admin_page(true);
2836
    }
2837
2838
2839
    /**
2840
     * generates  HTML wrapper for an admin details page (except no sidebar)
2841
     *
2842
     * @return void
2843
     * @throws DomainException
2844
     * @throws EE_Error
2845
     * @throws InvalidArgumentException
2846
     * @throws InvalidDataTypeException
2847
     * @throws InvalidInterfaceException
2848
     */
2849
    public function display_admin_page_with_no_sidebar()
2850
    {
2851
        $this->_display_admin_page();
2852
    }
2853
2854
2855
    /**
2856
     * generates HTML wrapper for an EE about admin page (no sidebar)
2857
     *
2858
     * @return void
2859
     * @throws DomainException
2860
     * @throws EE_Error
2861
     * @throws InvalidArgumentException
2862
     * @throws InvalidDataTypeException
2863
     * @throws InvalidInterfaceException
2864
     */
2865
    public function display_about_admin_page()
2866
    {
2867
        $this->_display_admin_page(false, true);
2868
    }
2869
2870
2871
    /**
2872
     * display_admin_page
2873
     * contains the code for actually displaying an admin page
2874
     *
2875
     * @param boolean $sidebar true with sidebar, false without
2876
     * @param boolean $about   use the about admin wrapper instead of the default.
2877
     * @return void
2878
     * @throws DomainException
2879
     * @throws EE_Error
2880
     * @throws InvalidArgumentException
2881
     * @throws InvalidDataTypeException
2882
     * @throws InvalidInterfaceException
2883
     */
2884
    private function _display_admin_page($sidebar = false, $about = false)
2885
    {
2886
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2887
        // custom remove metaboxes hook to add or remove any metaboxes to/from Admin pages.
2888
        do_action('AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes');
2889
        // set current wp page slug - looks like: event-espresso_page_event_categories
2890
        // keep in mind "event-espresso" COULD be something else if the top level menu label has been translated.
2891
        $this->_template_args['current_page'] = $this->_wp_page_slug;
2892
        $this->_template_args['admin_page_wrapper_div_id'] = $this->_cpt_route
2893
            ? 'poststuff'
2894
            : 'espresso-default-admin';
2895
        $template_path = $sidebar
2896
            ? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2897
            : EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2898
        if (defined('DOING_AJAX') && DOING_AJAX) {
2899
            $template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2900
        }
2901
        $template_path = ! empty($this->_column_template_path)
2902
            ? $this->_column_template_path : $template_path;
2903
        $this->_template_args['post_body_content'] = isset($this->_template_args['admin_page_content'])
2904
            ? $this->_template_args['admin_page_content']
2905
            : '';
2906
        $this->_template_args['before_admin_page_content'] = isset($this->_template_args['before_admin_page_content'])
2907
            ? $this->_template_args['before_admin_page_content']
2908
            : '';
2909
        $this->_template_args['after_admin_page_content'] = isset($this->_template_args['after_admin_page_content'])
2910
            ? $this->_template_args['after_admin_page_content']
2911
            : '';
2912
        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2913
            $template_path,
2914
            $this->_template_args,
2915
            true
2916
        );
2917
        // the final template wrapper
2918
        $this->admin_page_wrapper($about);
2919
    }
2920
2921
2922
    /**
2923
     * This is used to display caf preview pages.
2924
     *
2925
     * @since 4.3.2
2926
     * @param string $utm_campaign_source what is the key used for google analytics link
2927
     * @param bool   $display_sidebar     whether to use the sidebar template or the full template for the page.  TRUE
2928
     *                                    = SHOW sidebar, FALSE = no sidebar. Default no sidebar.
2929
     * @return void
2930
     * @throws DomainException
2931
     * @throws EE_Error
2932
     * @throws InvalidArgumentException
2933
     * @throws InvalidDataTypeException
2934
     * @throws InvalidInterfaceException
2935
     */
2936
    public function display_admin_caf_preview_page($utm_campaign_source = '', $display_sidebar = true)
2937
    {
2938
        // let's generate a default preview action button if there isn't one already present.
2939
        $this->_labels['buttons']['buy_now'] = esc_html__(
2940
            'Upgrade to Event Espresso 4 Right Now',
2941
            'event_espresso'
2942
        );
2943
        $buy_now_url = add_query_arg(
2944
            array(
2945
                'ee_ver'       => 'ee4',
2946
                'utm_source'   => 'ee4_plugin_admin',
2947
                'utm_medium'   => 'link',
2948
                'utm_campaign' => $utm_campaign_source,
2949
                'utm_content'  => 'buy_now_button',
2950
            ),
2951
            'http://eventespresso.com/pricing/'
2952
        );
2953
        $this->_template_args['preview_action_button'] = ! isset($this->_template_args['preview_action_button'])
2954
            ? $this->get_action_link_or_button(
2955
                '',
2956
                'buy_now',
2957
                array(),
2958
                'button-primary button-large',
2959
                $buy_now_url,
2960
                true
2961
            )
2962
            : $this->_template_args['preview_action_button'];
2963
        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2964
            EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php',
2965
            $this->_template_args,
2966
            true
2967
        );
2968
        $this->_display_admin_page($display_sidebar);
2969
    }
2970
2971
2972
    /**
2973
     * display_admin_list_table_page_with_sidebar
2974
     * generates HTML wrapper for an admin_page with list_table
2975
     *
2976
     * @return void
2977
     * @throws DomainException
2978
     * @throws EE_Error
2979
     * @throws InvalidArgumentException
2980
     * @throws InvalidDataTypeException
2981
     * @throws InvalidInterfaceException
2982
     */
2983
    public function display_admin_list_table_page_with_sidebar()
2984
    {
2985
        $this->_display_admin_list_table_page(true);
2986
    }
2987
2988
2989
    /**
2990
     * display_admin_list_table_page_with_no_sidebar
2991
     * generates HTML wrapper for an admin_page with list_table (but with no sidebar)
2992
     *
2993
     * @return void
2994
     * @throws DomainException
2995
     * @throws EE_Error
2996
     * @throws InvalidArgumentException
2997
     * @throws InvalidDataTypeException
2998
     * @throws InvalidInterfaceException
2999
     */
3000
    public function display_admin_list_table_page_with_no_sidebar()
3001
    {
3002
        $this->_display_admin_list_table_page();
3003
    }
3004
3005
3006
    /**
3007
     * generates html wrapper for an admin_list_table page
3008
     *
3009
     * @param boolean $sidebar whether to display with sidebar or not.
3010
     * @return void
3011
     * @throws DomainException
3012
     * @throws EE_Error
3013
     * @throws InvalidArgumentException
3014
     * @throws InvalidDataTypeException
3015
     * @throws InvalidInterfaceException
3016
     */
3017
    private function _display_admin_list_table_page($sidebar = false)
3018
    {
3019
        // setup search attributes
3020
        $this->_set_search_attributes();
3021
        $this->_template_args['current_page'] = $this->_wp_page_slug;
3022
        $template_path = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
3023
        $this->_template_args['table_url'] = defined('DOING_AJAX')
3024
            ? add_query_arg(array('noheader' => 'true', 'route' => $this->_req_action), $this->_admin_base_url)
3025
            : add_query_arg(array('route' => $this->_req_action), $this->_admin_base_url);
3026
        $this->_template_args['list_table'] = $this->_list_table_object;
3027
        $this->_template_args['current_route'] = $this->_req_action;
3028
        $this->_template_args['list_table_class'] = get_class($this->_list_table_object);
3029
        $ajax_sorting_callback = $this->_list_table_object->get_ajax_sorting_callback();
3030
        if (! empty($ajax_sorting_callback)) {
3031
            $sortable_list_table_form_fields = wp_nonce_field(
3032
                $ajax_sorting_callback . '_nonce',
3033
                $ajax_sorting_callback . '_nonce',
3034
                false,
3035
                false
3036
            );
3037
            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="'
3038
                                                . $this->page_slug
3039
                                                . '" />';
3040
            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="'
3041
                                                . $ajax_sorting_callback
3042
                                                . '" />';
3043
        } else {
3044
            $sortable_list_table_form_fields = '';
3045
        }
3046
        $this->_template_args['sortable_list_table_form_fields'] = $sortable_list_table_form_fields;
3047
        $hidden_form_fields = isset($this->_template_args['list_table_hidden_fields'])
3048
            ? $this->_template_args['list_table_hidden_fields']
3049
            : '';
3050
        $nonce_ref = $this->_req_action . '_nonce';
3051
        $hidden_form_fields .= '<input type="hidden" name="'
3052
                               . $nonce_ref
3053
                               . '" value="'
3054
                               . wp_create_nonce($nonce_ref)
3055
                               . '">';
3056
        $this->_template_args['list_table_hidden_fields'] = $hidden_form_fields;
3057
        // display message about search results?
3058
        $this->_template_args['before_list_table'] .= ! empty($this->_req_data['s'])
3059
            ? '<p class="ee-search-results">' . sprintf(
3060
                esc_html__('Displaying search results for the search string: %1$s', 'event_espresso'),
3061
                trim($this->_req_data['s'], '%')
3062
            ) . '</p>'
3063
            : '';
3064
        // filter before_list_table template arg
3065
        $this->_template_args['before_list_table'] = apply_filters(
3066
            'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_arg',
3067
            $this->_template_args['before_list_table'],
3068
            $this->page_slug,
3069
            $this->_req_data,
3070
            $this->_req_action
3071
        );
3072
        // convert to array and filter again
3073
        // arrays are easier to inject new items in a specific location,
3074
        // but would not be backwards compatible, so we have to add a new filter
3075
        $this->_template_args['before_list_table'] = implode(
3076
            " \n",
3077
            (array) apply_filters(
3078
                'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_args_array',
3079
                (array) $this->_template_args['before_list_table'],
3080
                $this->page_slug,
3081
                $this->_req_data,
3082
                $this->_req_action
3083
            )
3084
        );
3085
        // filter after_list_table template arg
3086
        $this->_template_args['after_list_table'] = apply_filters(
3087
            'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_arg',
3088
            $this->_template_args['after_list_table'],
3089
            $this->page_slug,
3090
            $this->_req_data,
3091
            $this->_req_action
3092
        );
3093
        // convert to array and filter again
3094
        // arrays are easier to inject new items in a specific location,
3095
        // but would not be backwards compatible, so we have to add a new filter
3096
        $this->_template_args['after_list_table'] = implode(
3097
            " \n",
3098
            (array) apply_filters(
3099
                'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_args_array',
3100
                (array) $this->_template_args['after_list_table'],
3101
                $this->page_slug,
3102
                $this->_req_data,
3103
                $this->_req_action
3104
            )
3105
        );
3106
        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
3107
            $template_path,
3108
            $this->_template_args,
3109
            true
3110
        );
3111
        // the final template wrapper
3112
        if ($sidebar) {
3113
            $this->display_admin_page_with_sidebar();
3114
        } else {
3115
            $this->display_admin_page_with_no_sidebar();
3116
        }
3117
    }
3118
3119
3120
    /**
3121
     * This just prepares a legend using the given items and the admin_details_legend.template.php file and returns the
3122
     * html string for the legend.
3123
     * $items are expected in an array in the following format:
3124
     * $legend_items = array(
3125
     *        'item_id' => array(
3126
     *            'icon' => 'http://url_to_icon_being_described.png',
3127
     *            'desc' => esc_html__('localized description of item');
3128
     *        )
3129
     * );
3130
     *
3131
     * @param  array $items see above for format of array
3132
     * @return string html string of legend
3133
     * @throws DomainException
3134
     */
3135
    protected function _display_legend($items)
3136
    {
3137
        $this->_template_args['items'] = apply_filters(
3138
            'FHEE__EE_Admin_Page___display_legend__items',
3139
            (array) $items,
3140
            $this
3141
        );
3142
        return EEH_Template::display_template(
3143
            EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php',
3144
            $this->_template_args,
3145
            true
3146
        );
3147
    }
3148
3149
3150
    /**
3151
     * This is used whenever we're DOING_AJAX to return a formatted json array that our calling javascript can expect
3152
     * The returned json object is created from an array in the following format:
3153
     * array(
3154
     *  'error' => FALSE, //(default FALSE), contains any errors and/or exceptions (exceptions return json early),
3155
     *  'success' => FALSE, //(default FALSE) - contains any special success message.
3156
     *  'notices' => '', // - contains any EE_Error formatted notices
3157
     *  'content' => 'string can be html', //this is a string of formatted content (can be html)
3158
     *  'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
3159
     *  We're also going to include the template args with every package (so js can pick out any specific template args
3160
     *  that might be included in here)
3161
     * )
3162
     * The json object is populated by whatever is set in the $_template_args property.
3163
     *
3164
     * @param bool  $sticky_notices    Used to indicate whether you want to ensure notices are added to a transient
3165
     *                                 instead of displayed.
3166
     * @param array $notices_arguments Use this to pass any additional args on to the _process_notices.
3167
     * @return void
3168
     * @throws EE_Error
3169
     * @throws InvalidArgumentException
3170
     * @throws InvalidDataTypeException
3171
     * @throws InvalidInterfaceException
3172
     */
3173
    protected function _return_json($sticky_notices = false, $notices_arguments = array())
3174
    {
3175
        // make sure any EE_Error notices have been handled.
3176
        $this->_process_notices($notices_arguments, true, $sticky_notices);
3177
        $data = isset($this->_template_args['data']) ? $this->_template_args['data'] : array();
3178
        unset($this->_template_args['data']);
3179
        $json = array(
3180
            'error'     => isset($this->_template_args['error']) ? $this->_template_args['error'] : false,
3181
            'success'   => isset($this->_template_args['success']) ? $this->_template_args['success'] : false,
3182
            'errors'    => isset($this->_template_args['errors']) ? $this->_template_args['errors'] : false,
3183
            'attention' => isset($this->_template_args['attention']) ? $this->_template_args['attention'] : false,
3184
            'notices'   => EE_Error::get_notices(),
3185
            'content'   => isset($this->_template_args['admin_page_content'])
3186
                ? $this->_template_args['admin_page_content'] : '',
3187
            'data'      => array_merge($data, array('template_args' => $this->_template_args)),
3188
            'isEEajax'  => true
3189
            // special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
3190
        );
3191
        // make sure there are no php errors or headers_sent.  Then we can set correct json header.
3192
        if (null === error_get_last() || ! headers_sent()) {
3193
            header('Content-Type: application/json; charset=UTF-8');
3194
        }
3195
        echo wp_json_encode($json);
3196
        exit();
3197
    }
3198
3199
3200
    /**
3201
     * Simply a wrapper for the protected method so we can call this outside the class (ONLY when doing ajax)
3202
     *
3203
     * @return void
3204
     * @throws EE_Error
3205
     * @throws InvalidArgumentException
3206
     * @throws InvalidDataTypeException
3207
     * @throws InvalidInterfaceException
3208
     */
3209
    public function return_json()
3210
    {
3211
        if (defined('DOING_AJAX') && DOING_AJAX) {
3212
            $this->_return_json();
3213
        } else {
3214
            throw new EE_Error(
3215
                sprintf(
3216
                    esc_html__('The public %s method can only be called when DOING_AJAX = TRUE', 'event_espresso'),
3217
                    __FUNCTION__
3218
                )
3219
            );
3220
        }
3221
    }
3222
3223
3224
    /**
3225
     * This provides a way for child hook classes to send along themselves by reference so methods/properties within
3226
     * them can be accessed by EE_Admin_child pages. This is assigned to the $_hook_obj property.
3227
     *
3228
     * @param EE_Admin_Hooks $hook_obj This will be the object for the EE_Admin_Hooks child
3229
     */
3230
    public function set_hook_object(EE_Admin_Hooks $hook_obj)
3231
    {
3232
        $this->_hook_obj = $hook_obj;
3233
    }
3234
3235
3236
    /**
3237
     *        generates  HTML wrapper with Tabbed nav for an admin page
3238
     *
3239
     * @param boolean $about whether to use the special about page wrapper or default.
3240
     * @return void
3241
     * @throws DomainException
3242
     * @throws EE_Error
3243
     * @throws InvalidArgumentException
3244
     * @throws InvalidDataTypeException
3245
     * @throws InvalidInterfaceException
3246
     */
3247
    public function admin_page_wrapper($about = false)
3248
    {
3249
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3250
        $this->_nav_tabs = $this->_get_main_nav_tabs();
3251
        $this->_template_args['nav_tabs'] = $this->_nav_tabs;
3252
        $this->_template_args['admin_page_title'] = $this->_admin_page_title;
3253
        $this->_template_args['before_admin_page_content'] = apply_filters(
3254
            "FHEE_before_admin_page_content{$this->_current_page}{$this->_current_view}",
3255
            isset($this->_template_args['before_admin_page_content'])
3256
                ? $this->_template_args['before_admin_page_content']
3257
                : ''
3258
        );
3259
        $this->_template_args['after_admin_page_content'] = apply_filters(
3260
            "FHEE_after_admin_page_content{$this->_current_page}{$this->_current_view}",
3261
            isset($this->_template_args['after_admin_page_content'])
3262
                ? $this->_template_args['after_admin_page_content']
3263
                : ''
3264
        );
3265
        $this->_template_args['after_admin_page_content'] .= $this->_set_help_popup_content();
3266
        // load settings page wrapper template
3267
        $template_path = ! defined('DOING_AJAX')
3268
            ? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php'
3269
            : EE_ADMIN_TEMPLATE
3270
              . 'admin_wrapper_ajax.template.php';
3271
        // about page?
3272
        $template_path = $about
3273
            ? EE_ADMIN_TEMPLATE . 'about_admin_wrapper.template.php'
3274
            : $template_path;
3275
        if (defined('DOING_AJAX')) {
3276
            $this->_template_args['admin_page_content'] = EEH_Template::display_template(
3277
                $template_path,
3278
                $this->_template_args,
3279
                true
3280
            );
3281
            $this->_return_json();
3282
        } else {
3283
            EEH_Template::display_template($template_path, $this->_template_args);
3284
        }
3285
    }
3286
3287
3288
    /**
3289
     * This returns the admin_nav tabs html using the configuration in the _nav_tabs property
3290
     *
3291
     * @return string html
3292
     * @throws EE_Error
3293
     */
3294
    protected function _get_main_nav_tabs()
3295
    {
3296
        // let's generate the html using the EEH_Tabbed_Content helper.
3297
        // We do this here so that it's possible for child classes to add in nav tabs dynamically at the last minute
3298
        // (rather than setting in the page_routes array)
3299
        return EEH_Tabbed_Content::display_admin_nav_tabs($this->_nav_tabs);
3300
    }
3301
3302
3303
    /**
3304
     *        sort nav tabs
3305
     *
3306
     * @param $a
3307
     * @param $b
3308
     * @return int
3309
     */
3310
    private function _sort_nav_tabs($a, $b)
3311
    {
3312
        if ($a['order'] === $b['order']) {
3313
            return 0;
3314
        }
3315
        return ($a['order'] < $b['order']) ? -1 : 1;
3316
    }
3317
3318
3319
    /**
3320
     *    generates HTML for the forms used on admin pages
3321
     *
3322
     * @param    array $input_vars - array of input field details
3323
     * @param string   $generator  (options are 'string' or 'array', basically use this to indicate which generator to
3324
     *                             use)
3325
     * @param bool     $id
3326
     * @return string
3327
     * @uses   EEH_Form_Fields::get_form_fields (/helper/EEH_Form_Fields.helper.php)
3328
     * @uses   EEH_Form_Fields::get_form_fields_array (/helper/EEH_Form_Fields.helper.php)
3329
     */
3330
    protected function _generate_admin_form_fields($input_vars = array(), $generator = 'string', $id = false)
3331
    {
3332
        $content = $generator === 'string'
3333
            ? EEH_Form_Fields::get_form_fields($input_vars, $id)
3334
            : EEH_Form_Fields::get_form_fields_array($input_vars);
3335
        return $content;
3336
    }
3337
3338
3339
    /**
3340
     * generates the "Save" and "Save & Close" buttons for edit forms
3341
     *
3342
     * @param bool             $both     if true then both buttons will be generated.  If false then just the "Save &
3343
     *                                   Close" button.
3344
     * @param array            $text     if included, generator will use the given text for the buttons ( array([0] =>
3345
     *                                   'Save', [1] => 'save & close')
3346
     * @param array            $actions  if included allows us to set the actions that each button will carry out (i.e.
3347
     *                                   via the "name" value in the button).  We can also use this to just dump
3348
     *                                   default actions by submitting some other value.
3349
     * @param bool|string|null $referrer if false then we just do the default action on save and close.  Other wise it
3350
     *                                   will use the $referrer string. IF null, then we don't do ANYTHING on save and
3351
     *                                   close (normal form handling).
3352
     */
3353
    protected function _set_save_buttons($both = true, $text = array(), $actions = array(), $referrer = null)
3354
    {
3355
        // make sure $text and $actions are in an array
3356
        $text = (array) $text;
3357
        $actions = (array) $actions;
3358
        $referrer_url = empty($referrer)
3359
            ? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3360
              . $_SERVER['REQUEST_URI']
3361
              . '" />'
3362
            : '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3363
              . $referrer
3364
              . '" />';
3365
        $button_text = ! empty($text)
3366
            ? $text
3367
            : array(
3368
                esc_html__('Save', 'event_espresso'),
3369
                esc_html__('Save and Close', 'event_espresso'),
3370
            );
3371
        $default_names = array('save', 'save_and_close');
3372
        // add in a hidden index for the current page (so save and close redirects properly)
3373
        $this->_template_args['save_buttons'] = $referrer_url;
3374
        foreach ($button_text as $key => $button) {
3375
            $ref = $default_names[ $key ];
3376
            $this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary '
3377
                                                     . $ref
3378
                                                     . '" value="'
3379
                                                     . $button
3380
                                                     . '" name="'
3381
                                                     . (! empty($actions) ? $actions[ $key ] : $ref)
3382
                                                     . '" id="'
3383
                                                     . $this->_current_view . '_' . $ref
3384
                                                     . '" />';
3385
            if (! $both) {
3386
                break;
3387
            }
3388
        }
3389
    }
3390
3391
3392
    /**
3393
     * Wrapper for the protected function.  Allows plugins/addons to call this to set the form tags.
3394
     *
3395
     * @see   $this->_set_add_edit_form_tags() for details on params
3396
     * @since 4.6.0
3397
     * @param string $route
3398
     * @param array  $additional_hidden_fields
3399
     */
3400
    public function set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
3401
    {
3402
        $this->_set_add_edit_form_tags($route, $additional_hidden_fields);
3403
    }
3404
3405
3406
    /**
3407
     * set form open and close tags on add/edit pages.
3408
     *
3409
     * @param string $route                    the route you want the form to direct to
3410
     * @param array  $additional_hidden_fields any additional hidden fields required in the form header
3411
     * @return void
3412
     */
3413
    protected function _set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
3414
    {
3415
        if (empty($route)) {
3416
            $user_msg = esc_html__(
3417
                'An error occurred. No action was set for this page\'s form.',
3418
                'event_espresso'
3419
            );
3420
            $dev_msg = $user_msg . "\n"
3421
                       . sprintf(
3422
                           esc_html__('The $route argument is required for the %s->%s method.', 'event_espresso'),
3423
                           __FUNCTION__,
3424
                           __CLASS__
3425
                       );
3426
            EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
3427
        }
3428
        // open form
3429
        $this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="'
3430
                                                             . $this->_admin_base_url
3431
                                                             . '" id="'
3432
                                                             . $route
3433
                                                             . '_event_form" >';
3434
        // add nonce
3435
        $nonce = wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
3436
        $this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
3437
        // add REQUIRED form action
3438
        $hidden_fields = array(
3439
            'action' => array('type' => 'hidden', 'value' => $route),
3440
        );
3441
        // merge arrays
3442
        $hidden_fields = is_array($additional_hidden_fields)
3443
            ? array_merge($hidden_fields, $additional_hidden_fields)
3444
            : $hidden_fields;
3445
        // generate form fields
3446
        $form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
3447
        // add fields to form
3448
        foreach ((array) $form_fields as $field_name => $form_field) {
3449
            $this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
3450
        }
3451
        // close form
3452
        $this->_template_args['after_admin_page_content'] = '</form>';
3453
    }
3454
3455
3456
    /**
3457
     * Public Wrapper for _redirect_after_action() method since its
3458
     * discovered it would be useful for external code to have access.
3459
     *
3460
     * @param bool   $success
3461
     * @param string $what
3462
     * @param string $action_desc
3463
     * @param array  $query_args
3464
     * @param bool   $override_overwrite
3465
     * @throws EE_Error
3466
     * @throws InvalidArgumentException
3467
     * @throws InvalidDataTypeException
3468
     * @throws InvalidInterfaceException
3469
     * @see   EE_Admin_Page::_redirect_after_action() for params.
3470
     * @since 4.5.0
3471
     */
3472
    public function redirect_after_action(
3473
        $success = false,
3474
        $what = 'item',
3475
        $action_desc = 'processed',
3476
        $query_args = array(),
3477
        $override_overwrite = false
3478
    ) {
3479
        $this->_redirect_after_action(
3480
            $success,
3481
            $what,
3482
            $action_desc,
3483
            $query_args,
3484
            $override_overwrite
3485
        );
3486
    }
3487
3488
3489
    /**
3490
     * Helper method for merging existing request data with the returned redirect url.
3491
     *
3492
     * This is typically used for redirects after an action so that if the original view was a filtered view those
3493
     * filters are still applied.
3494
     *
3495
     * @param array $new_route_data
3496
     * @return array
3497
     */
3498
    protected function mergeExistingRequestParamsWithRedirectArgs(array $new_route_data)
3499
    {
3500
        foreach ($this->_req_data as $ref => $value) {
3501
            // unset nonces
3502
            if (strpos($ref, 'nonce') !== false) {
3503
                unset($this->_req_data[ $ref ]);
3504
                continue;
3505
            }
3506
            // urlencode values.
3507
            $value = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
3508
            $this->_req_data[ $ref ] = $value;
3509
        }
3510
        return array_merge($this->_req_data, $new_route_data);
3511
    }
3512
3513
3514
    /**
3515
     *    _redirect_after_action
3516
     *
3517
     * @param int    $success            - whether success was for two or more records, or just one, or none
3518
     * @param string $what               - what the action was performed on
3519
     * @param string $action_desc        - what was done ie: updated, deleted, etc
3520
     * @param array  $query_args         - an array of query_args to be added to the URL to redirect to after the admin
3521
     *                                   action is completed
3522
     * @param BOOL   $override_overwrite by default all EE_Error::success messages are overwritten, this allows you to
3523
     *                                   override this so that they show.
3524
     * @return void
3525
     * @throws EE_Error
3526
     * @throws InvalidArgumentException
3527
     * @throws InvalidDataTypeException
3528
     * @throws InvalidInterfaceException
3529
     */
3530
    protected function _redirect_after_action(
3531
        $success = 0,
3532
        $what = 'item',
3533
        $action_desc = 'processed',
3534
        $query_args = array(),
3535
        $override_overwrite = false
3536
    ) {
3537
        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3538
        // class name for actions/filters.
3539
        $classname = get_class($this);
3540
        // set redirect url.
3541
        // Note if there is a "page" index in the $query_args then we go with vanilla admin.php route,
3542
        // otherwise we go with whatever is set as the _admin_base_url
3543
        $redirect_url = isset($query_args['page']) ? admin_url('admin.php') : $this->_admin_base_url;
3544
        $notices = EE_Error::get_notices(false);
3545
        // overwrite default success messages //BUT ONLY if overwrite not overridden
3546
        if (! $override_overwrite || ! empty($notices['errors'])) {
3547
            EE_Error::overwrite_success();
3548
        }
3549
        if (! empty($what) && ! empty($action_desc) && empty($notices['errors'])) {
3550
            // how many records affected ? more than one record ? or just one ?
3551
            if ($success > 1) {
3552
                // set plural msg
3553
                EE_Error::add_success(
3554
                    sprintf(
3555
                        esc_html__('The "%s" have been successfully %s.', 'event_espresso'),
3556
                        $what,
3557
                        $action_desc
3558
                    ),
3559
                    __FILE__,
3560
                    __FUNCTION__,
3561
                    __LINE__
3562
                );
3563
            } elseif ($success === 1) {
3564
                // set singular msg
3565
                EE_Error::add_success(
3566
                    sprintf(
3567
                        esc_html__('The "%s" has been successfully %s.', 'event_espresso'),
3568
                        $what,
3569
                        $action_desc
3570
                    ),
3571
                    __FILE__,
3572
                    __FUNCTION__,
3573
                    __LINE__
3574
                );
3575
            }
3576
        }
3577
        // check that $query_args isn't something crazy
3578
        if (! is_array($query_args)) {
3579
            $query_args = array();
3580
        }
3581
        /**
3582
         * Allow injecting actions before the query_args are modified for possible different
3583
         * redirections on save and close actions
3584
         *
3585
         * @since 4.2.0
3586
         * @param array $query_args       The original query_args array coming into the
3587
         *                                method.
3588
         */
3589
        do_action(
3590
            "AHEE__{$classname}___redirect_after_action__before_redirect_modification_{$this->_req_action}",
3591
            $query_args
3592
        );
3593
        // calculate where we're going (if we have a "save and close" button pushed)
3594
        if (isset($this->_req_data['save_and_close'], $this->_req_data['save_and_close_referrer'])) {
3595
            // even though we have the save_and_close referrer, we need to parse the url for the action in order to generate a nonce
3596
            $parsed_url = parse_url($this->_req_data['save_and_close_referrer']);
3597
            // regenerate query args array from referrer URL
3598
            parse_str($parsed_url['query'], $query_args);
3599
            // correct page and action will be in the query args now
3600
            $redirect_url = admin_url('admin.php');
3601
        }
3602
        // merge any default query_args set in _default_route_query_args property
3603
        if (! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
3604
            $args_to_merge = array();
3605
            foreach ($this->_default_route_query_args as $query_param => $query_value) {
3606
                // is there a wp_referer array in our _default_route_query_args property?
3607
                if ($query_param === 'wp_referer') {
3608
                    $query_value = (array) $query_value;
3609
                    foreach ($query_value as $reference => $value) {
3610
                        if (strpos($reference, 'nonce') !== false) {
3611
                            continue;
3612
                        }
3613
                        // finally we will override any arguments in the referer with
3614
                        // what might be set on the _default_route_query_args array.
3615
                        if (isset($this->_default_route_query_args[ $reference ])) {
3616
                            $args_to_merge[ $reference ] = urlencode($this->_default_route_query_args[ $reference ]);
3617
                        } else {
3618
                            $args_to_merge[ $reference ] = urlencode($value);
3619
                        }
3620
                    }
3621
                    continue;
3622
                }
3623
                $args_to_merge[ $query_param ] = $query_value;
3624
            }
3625
            // now let's merge these arguments but override with what was specifically sent in to the
3626
            // redirect.
3627
            $query_args = array_merge($args_to_merge, $query_args);
3628
        }
3629
        $this->_process_notices($query_args);
3630
        // generate redirect url
3631
        // if redirecting to anything other than the main page, add a nonce
3632
        if (isset($query_args['action'])) {
3633
            // manually generate wp_nonce and merge that with the query vars
3634
            // becuz the wp_nonce_url function wrecks havoc on some vars
3635
            $query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
3636
        }
3637
        // we're adding some hooks and filters in here for processing any things just before redirects
3638
        // (example: an admin page has done an insert or update and we want to run something after that).
3639
        do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
3640
        $redirect_url = apply_filters(
3641
            'FHEE_redirect_' . $classname . $this->_req_action,
3642
            self::add_query_args_and_nonce($query_args, $redirect_url),
3643
            $query_args
3644
        );
3645
        // check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
3646
        if (defined('DOING_AJAX')) {
3647
            $default_data = array(
3648
                'close'        => true,
3649
                'redirect_url' => $redirect_url,
3650
                'where'        => 'main',
3651
                'what'         => 'append',
3652
            );
3653
            $this->_template_args['success'] = $success;
3654
            $this->_template_args['data'] = ! empty($this->_template_args['data']) ? array_merge(
3655
                $default_data,
3656
                $this->_template_args['data']
3657
            ) : $default_data;
3658
            $this->_return_json();
3659
        }
3660
        wp_safe_redirect($redirect_url);
3661
        exit();
3662
    }
3663
3664
3665
    /**
3666
     * process any notices before redirecting (or returning ajax request)
3667
     * This method sets the $this->_template_args['notices'] attribute;
3668
     *
3669
     * @param array $query_args         any query args that need to be used for notice transient ('action')
3670
     * @param bool  $skip_route_verify  This is typically used when we are processing notices REALLY early and
3671
     *                                  page_routes haven't been defined yet.
3672
     * @param bool  $sticky_notices     This is used to flag that regardless of whether this is doing_ajax or not, we
3673
     *                                  still save a transient for the notice.
3674
     * @return void
3675
     * @throws EE_Error
3676
     * @throws InvalidArgumentException
3677
     * @throws InvalidDataTypeException
3678
     * @throws InvalidInterfaceException
3679
     */
3680
    protected function _process_notices($query_args = array(), $skip_route_verify = false, $sticky_notices = true)
3681
    {
3682
        // first let's set individual error properties if doing_ajax and the properties aren't already set.
3683
        if (defined('DOING_AJAX') && DOING_AJAX) {
3684
            $notices = EE_Error::get_notices(false);
3685 View Code Duplication
            if (empty($this->_template_args['success'])) {
3686
                $this->_template_args['success'] = isset($notices['success']) ? $notices['success'] : false;
3687
            }
3688 View Code Duplication
            if (empty($this->_template_args['errors'])) {
3689
                $this->_template_args['errors'] = isset($notices['errors']) ? $notices['errors'] : false;
3690
            }
3691 View Code Duplication
            if (empty($this->_template_args['attention'])) {
3692
                $this->_template_args['attention'] = isset($notices['attention']) ? $notices['attention'] : false;
3693
            }
3694
        }
3695
        $this->_template_args['notices'] = EE_Error::get_notices();
3696
        // IF this isn't ajax we need to create a transient for the notices using the route (however, overridden if $sticky_notices == true)
3697
        if (! defined('DOING_AJAX') || $sticky_notices) {
3698
            $route = isset($query_args['action']) ? $query_args['action'] : 'default';
3699
            $this->_add_transient(
3700
                $route,
3701
                $this->_template_args['notices'],
3702
                true,
3703
                $skip_route_verify
3704
            );
3705
        }
3706
    }
3707
3708
3709
    /**
3710
     * get_action_link_or_button
3711
     * returns the button html for adding, editing, or deleting an item (depending on given type)
3712
     *
3713
     * @param string $action        use this to indicate which action the url is generated with.
3714
     * @param string $type          accepted strings must be defined in the $_labels['button'] array(as the key)
3715
     *                              property.
3716
     * @param array  $extra_request if the button requires extra params you can include them in $key=>$value pairs.
3717
     * @param string $class         Use this to give the class for the button. Defaults to 'button-primary'
3718
     * @param string $base_url      If this is not provided
3719
     *                              the _admin_base_url will be used as the default for the button base_url.
3720
     *                              Otherwise this value will be used.
3721
     * @param bool   $exclude_nonce If true then no nonce will be in the generated button link.
3722
     * @return string
3723
     * @throws InvalidArgumentException
3724
     * @throws InvalidInterfaceException
3725
     * @throws InvalidDataTypeException
3726
     * @throws EE_Error
3727
     */
3728
    public function get_action_link_or_button(
3729
        $action,
3730
        $type = 'add',
3731
        $extra_request = array(),
3732
        $class = 'button-primary',
3733
        $base_url = '',
3734
        $exclude_nonce = false
3735
    ) {
3736
        // first let's validate the action (if $base_url is FALSE otherwise validation will happen further along)
3737
        if (empty($base_url) && ! isset($this->_page_routes[ $action ])) {
3738
            throw new EE_Error(
3739
                sprintf(
3740
                    esc_html__(
3741
                        'There is no page route for given action for the button.  This action was given: %s',
3742
                        'event_espresso'
3743
                    ),
3744
                    $action
3745
                )
3746
            );
3747
        }
3748
        if (! isset($this->_labels['buttons'][ $type ])) {
3749
            throw new EE_Error(
3750
                sprintf(
3751
                    __(
3752
                        'There is no label for the given button type (%s). Labels are set in the <code>_page_config</code> property.',
3753
                        'event_espresso'
3754
                    ),
3755
                    $type
3756
                )
3757
            );
3758
        }
3759
        // finally check user access for this button.
3760
        $has_access = $this->check_user_access($action, true);
3761
        if (! $has_access) {
3762
            return '';
3763
        }
3764
        $_base_url = ! $base_url ? $this->_admin_base_url : $base_url;
3765
        $query_args = array(
3766
            'action' => $action,
3767
        );
3768
        // merge extra_request args but make sure our original action takes precedence and doesn't get overwritten.
3769
        if (! empty($extra_request)) {
3770
            $query_args = array_merge($extra_request, $query_args);
3771
        }
3772
        $url = self::add_query_args_and_nonce($query_args, $_base_url, false, $exclude_nonce);
3773
        return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][ $type ], $class);
3774
    }
3775
3776
3777
    /**
3778
     * _per_page_screen_option
3779
     * Utility function for adding in a per_page_option in the screen_options_dropdown.
3780
     *
3781
     * @return void
3782
     * @throws InvalidArgumentException
3783
     * @throws InvalidInterfaceException
3784
     * @throws InvalidDataTypeException
3785
     */
3786
    protected function _per_page_screen_option()
3787
    {
3788
        $option = 'per_page';
3789
        $args = array(
3790
            'label'   => apply_filters(
3791
                'FHEE__EE_Admin_Page___per_page_screen_options___label',
3792
                $this->_admin_page_title,
3793
                $this
3794
            ),
3795
            'default' => (int) apply_filters(
3796
                'FHEE__EE_Admin_Page___per_page_screen_options__default',
3797
                20
3798
            ),
3799
            'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
3800
        );
3801
        // ONLY add the screen option if the user has access to it.
3802
        if ($this->check_user_access($this->_current_view, true)) {
3803
            add_screen_option($option, $args);
3804
        }
3805
    }
3806
3807
3808
    /**
3809
     * set_per_page_screen_option
3810
     * All this does is make sure that WordPress saves any per_page screen options (if set) for the current page.
3811
     * we have to do this rather than running inside the 'set-screen-options' hook because it runs earlier than
3812
     * admin_menu.
3813
     *
3814
     * @return void
3815
     */
3816
    private function _set_per_page_screen_options()
3817
    {
3818
        if (isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options'])) {
3819
            check_admin_referer('screen-options-nonce', 'screenoptionnonce');
3820
            if (! $user = wp_get_current_user()) {
3821
                return;
3822
            }
3823
            $option = $_POST['wp_screen_options']['option'];
3824
            $value = $_POST['wp_screen_options']['value'];
3825
            if ($option !== sanitize_key($option)) {
3826
                return;
3827
            }
3828
            $map_option = $option;
3829
            $option = str_replace('-', '_', $option);
3830
            switch ($map_option) {
3831
                case $this->_current_page . '_' . $this->_current_view . '_per_page':
3832
                    $value = (int) $value;
3833
                    $max_value = apply_filters(
3834
                        'FHEE__EE_Admin_Page___set_per_page_screen_options__max_value',
3835
                        999,
3836
                        $this->_current_page,
3837
                        $this->_current_view
3838
                    );
3839
                    if ($value < 1) {
3840
                        return;
3841
                    }
3842
                    $value = min($value, $max_value);
3843
                    break;
3844
                default:
3845
                    $value = apply_filters(
3846
                        'FHEE__EE_Admin_Page___set_per_page_screen_options__value',
3847
                        false,
3848
                        $option,
3849
                        $value
3850
                    );
3851
                    if (false === $value) {
3852
                        return;
3853
                    }
3854
                    break;
3855
            }
3856
            update_user_meta($user->ID, $option, $value);
3857
            wp_safe_redirect(remove_query_arg(array('pagenum', 'apage', 'paged'), wp_get_referer()));
3858
            exit;
3859
        }
3860
    }
3861
3862
3863
    /**
3864
     * This just allows for setting the $_template_args property if it needs to be set outside the object
3865
     *
3866
     * @param array $data array that will be assigned to template args.
3867
     */
3868
    public function set_template_args($data)
3869
    {
3870
        $this->_template_args = array_merge($this->_template_args, (array) $data);
3871
    }
3872
3873
3874
    /**
3875
     * This makes available the WP transient system for temporarily moving data between routes
3876
     *
3877
     * @param string $route             the route that should receive the transient
3878
     * @param array  $data              the data that gets sent
3879
     * @param bool   $notices           If this is for notices then we use this to indicate so, otherwise its just a
3880
     *                                  normal route transient.
3881
     * @param bool   $skip_route_verify Used to indicate we want to skip route verification.  This is usually ONLY used
3882
     *                                  when we are adding a transient before page_routes have been defined.
3883
     * @return void
3884
     * @throws EE_Error
3885
     */
3886
    protected function _add_transient($route, $data, $notices = false, $skip_route_verify = false)
3887
    {
3888
        $user_id = get_current_user_id();
3889
        if (! $skip_route_verify) {
3890
            $this->_verify_route($route);
3891
        }
3892
        // now let's set the string for what kind of transient we're setting
3893
        $transient = $notices
3894
            ? 'ee_rte_n_tx_' . $route . '_' . $user_id
3895
            : 'rte_tx_' . $route . '_' . $user_id;
3896
        $data = $notices ? array('notices' => $data) : $data;
3897
        // is there already a transient for this route?  If there is then let's ADD to that transient
3898
        $existing = is_multisite() && is_network_admin()
3899
            ? get_site_transient($transient)
3900
            : get_transient($transient);
3901
        if ($existing) {
3902
            $data = array_merge((array) $data, (array) $existing);
3903
        }
3904
        if (is_multisite() && is_network_admin()) {
3905
            set_site_transient($transient, $data, 8);
3906
        } else {
3907
            set_transient($transient, $data, 8);
3908
        }
3909
    }
3910
3911
3912
    /**
3913
     * this retrieves the temporary transient that has been set for moving data between routes.
3914
     *
3915
     * @param bool   $notices true we get notices transient. False we just return normal route transient
3916
     * @param string $route
3917
     * @return mixed data
3918
     */
3919
    protected function _get_transient($notices = false, $route = '')
3920
    {
3921
        $user_id = get_current_user_id();
3922
        $route = ! $route ? $this->_req_action : $route;
3923
        $transient = $notices
3924
            ? 'ee_rte_n_tx_' . $route . '_' . $user_id
3925
            : 'rte_tx_' . $route . '_' . $user_id;
3926
        $data = is_multisite() && is_network_admin()
3927
            ? get_site_transient($transient)
3928
            : get_transient($transient);
3929
        // delete transient after retrieval (just in case it hasn't expired);
3930
        if (is_multisite() && is_network_admin()) {
3931
            delete_site_transient($transient);
3932
        } else {
3933
            delete_transient($transient);
3934
        }
3935
        return $notices && isset($data['notices']) ? $data['notices'] : $data;
3936
    }
3937
3938
3939
    /**
3940
     * The purpose of this method is just to run garbage collection on any EE transients that might have expired but
3941
     * would not be called later. This will be assigned to run on a specific EE Admin page. (place the method in the
3942
     * default route callback on the EE_Admin page you want it run.)
3943
     *
3944
     * @return void
3945
     */
3946
    protected function _transient_garbage_collection()
3947
    {
3948
        global $wpdb;
3949
        // retrieve all existing transients
3950
        $query = "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '%rte_tx_%' OR option_name LIKE '%rte_n_tx_%'";
3951
        if ($results = $wpdb->get_results($query)) {
3952
            foreach ($results as $result) {
3953
                $transient = str_replace('_transient_', '', $result->option_name);
3954
                get_transient($transient);
3955
                if (is_multisite() && is_network_admin()) {
3956
                    get_site_transient($transient);
3957
                }
3958
            }
3959
        }
3960
    }
3961
3962
3963
    /**
3964
     * get_view
3965
     *
3966
     * @return string content of _view property
3967
     */
3968
    public function get_view()
3969
    {
3970
        return $this->_view;
3971
    }
3972
3973
3974
    /**
3975
     * getter for the protected $_views property
3976
     *
3977
     * @return array
3978
     */
3979
    public function get_views()
3980
    {
3981
        return $this->_views;
3982
    }
3983
3984
3985
    /**
3986
     * get_current_page
3987
     *
3988
     * @return string _current_page property value
3989
     */
3990
    public function get_current_page()
3991
    {
3992
        return $this->_current_page;
3993
    }
3994
3995
3996
    /**
3997
     * get_current_view
3998
     *
3999
     * @return string _current_view property value
4000
     */
4001
    public function get_current_view()
4002
    {
4003
        return $this->_current_view;
4004
    }
4005
4006
4007
    /**
4008
     * get_current_screen
4009
     *
4010
     * @return object The current WP_Screen object
4011
     */
4012
    public function get_current_screen()
4013
    {
4014
        return $this->_current_screen;
4015
    }
4016
4017
4018
    /**
4019
     * get_current_page_view_url
4020
     *
4021
     * @return string This returns the url for the current_page_view.
4022
     */
4023
    public function get_current_page_view_url()
4024
    {
4025
        return $this->_current_page_view_url;
4026
    }
4027
4028
4029
    /**
4030
     * just returns the _req_data property
4031
     *
4032
     * @return array
4033
     */
4034
    public function get_request_data()
4035
    {
4036
        return $this->_req_data;
4037
    }
4038
4039
4040
    /**
4041
     * returns the _req_data protected property
4042
     *
4043
     * @return string
4044
     */
4045
    public function get_req_action()
4046
    {
4047
        return $this->_req_action;
4048
    }
4049
4050
4051
    /**
4052
     * @return bool  value of $_is_caf property
4053
     */
4054
    public function is_caf()
4055
    {
4056
        return $this->_is_caf;
4057
    }
4058
4059
4060
    /**
4061
     * @return mixed
4062
     */
4063
    public function default_espresso_metaboxes()
4064
    {
4065
        return $this->_default_espresso_metaboxes;
4066
    }
4067
4068
4069
    /**
4070
     * @return mixed
4071
     */
4072
    public function admin_base_url()
4073
    {
4074
        return $this->_admin_base_url;
4075
    }
4076
4077
4078
    /**
4079
     * @return mixed
4080
     */
4081
    public function wp_page_slug()
4082
    {
4083
        return $this->_wp_page_slug;
4084
    }
4085
4086
4087
    /**
4088
     * updates  espresso configuration settings
4089
     *
4090
     * @param string                   $tab
4091
     * @param EE_Config_Base|EE_Config $config
4092
     * @param string                   $file file where error occurred
4093
     * @param string                   $func function  where error occurred
4094
     * @param string                   $line line no where error occurred
4095
     * @return boolean
4096
     */
4097
    protected function _update_espresso_configuration($tab, $config, $file = '', $func = '', $line = '')
4098
    {
4099
        // remove any options that are NOT going to be saved with the config settings.
4100
        if (isset($config->core->ee_ueip_optin)) {
4101
            // TODO: remove the following two lines and make sure values are migrated from 3.1
4102
            update_option('ee_ueip_optin', $config->core->ee_ueip_optin);
4103
            update_option('ee_ueip_has_notified', true);
4104
        }
4105
        // and save it (note we're also doing the network save here)
4106
        $net_saved = is_main_site() ? EE_Network_Config::instance()->update_config(false, false) : true;
4107
        $config_saved = EE_Config::instance()->update_espresso_config(false, false);
4108
        if ($config_saved && $net_saved) {
4109
            EE_Error::add_success(sprintf(__('"%s" have been successfully updated.', 'event_espresso'), $tab));
4110
            return true;
4111
        }
4112
        EE_Error::add_error(sprintf(__('The "%s" were not updated.', 'event_espresso'), $tab), $file, $func, $line);
4113
        return false;
4114
    }
4115
4116
4117
    /**
4118
     * Returns an array to be used for EE_FOrm_Fields.helper.php's select_input as the $values argument.
4119
     *
4120
     * @return array
4121
     */
4122
    public function get_yes_no_values()
4123
    {
4124
        return $this->_yes_no_values;
4125
    }
4126
4127
4128
    protected function _get_dir()
4129
    {
4130
        $reflector = new ReflectionClass(get_class($this));
4131
        return dirname($reflector->getFileName());
4132
    }
4133
4134
4135
    /**
4136
     * A helper for getting a "next link".
4137
     *
4138
     * @param string $url   The url to link to
4139
     * @param string $class The class to use.
4140
     * @return string
4141
     */
4142
    protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
4143
    {
4144
        return '<a class="' . $class . '" href="' . $url . '"></a>';
4145
    }
4146
4147
4148
    /**
4149
     * A helper for getting a "previous link".
4150
     *
4151
     * @param string $url   The url to link to
4152
     * @param string $class The class to use.
4153
     * @return string
4154
     */
4155
    protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
4156
    {
4157
        return '<a class="' . $class . '" href="' . $url . '"></a>';
4158
    }
4159
4160
4161
4162
4163
4164
4165
4166
    // below are some messages related methods that should be available across the EE_Admin system.  Note, these methods are NOT page specific
4167
4168
4169
    /**
4170
     * This processes an request to resend a registration and assumes we have a _REG_ID for doing so. So if the caller
4171
     * knows that the _REG_ID isn't in the req_data array but CAN obtain it, the caller should ADD the _REG_ID to the
4172
     * _req_data array.
4173
     *
4174
     * @return bool success/fail
4175
     * @throws EE_Error
4176
     * @throws InvalidArgumentException
4177
     * @throws ReflectionException
4178
     * @throws InvalidDataTypeException
4179
     * @throws InvalidInterfaceException
4180
     */
4181
    protected function _process_resend_registration()
4182
    {
4183
        $this->_template_args['success'] = EED_Messages::process_resend($this->_req_data);
4184
        do_action(
4185
            'AHEE__EE_Admin_Page___process_resend_registration',
4186
            $this->_template_args['success'],
4187
            $this->_req_data
4188
        );
4189
        return $this->_template_args['success'];
4190
    }
4191
4192
4193
    /**
4194
     * This automatically processes any payment message notifications when manual payment has been applied.
4195
     *
4196
     * @param EE_Payment $payment
4197
     * @return bool success/fail
4198
     */
4199
    protected function _process_payment_notification(EE_Payment $payment)
4200
    {
4201
        add_filter('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', '__return_true');
4202
        do_action('AHEE__EE_Admin_Page___process_admin_payment_notification', $payment);
4203
        $this->_template_args['success'] = apply_filters(
4204
            'FHEE__EE_Admin_Page___process_admin_payment_notification__success',
4205
            false,
4206
            $payment
4207
        );
4208
        return $this->_template_args['success'];
4209
    }
4210
}
4211